id
int64 1
3.65k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
---|---|---|---|---|---|---|
3,383 |
Minimum Runes to Add to Cast Spell
|
Hard
|
<p>Alice has just graduated from wizard school, and wishes to cast a magic spell to celebrate. The magic spell contains certain <strong>focus points</strong> where magic needs to be concentrated, and some of these focus points contain <strong>magic crystals</strong> which serve as the spell's energy source. Focus points can be linked through <strong>directed runes</strong>, which channel magic flow from one focus point to another.</p>
<p>You are given a integer <code>n</code> denoting the <em>number</em> of focus points and an array of integers <code>crystals</code> where <code>crystals[i]</code> indicates a focus point which holds a magic crystal. You are also given two integer arrays <code>flowFrom</code> and <code>flowTo</code>, which represent the existing <strong>directed runes</strong>. The <code>i<sup>th</sup></code> rune allows magic to freely flow from focus point <code>flowFrom[i]</code> to focus point <code>flowTo[i]</code>.</p>
<p>You need to find the number of directed runes Alice must add to her spell, such that <em>each</em> focus point either:</p>
<ul>
<li><strong>Contains</strong> a magic crystal.</li>
<li><strong>Receives</strong> magic flow <em>from</em> another focus point.</li>
</ul>
<p>Return the <strong>minimum</strong> number of directed runes that she should add.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 6, crystals = [0], flowFrom = [0,1,2,3], flowTo = [1,2,3,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample0.png" style="width: 250px; height: 252px;" /></p>
<p>Add two directed runes:</p>
<ul>
<li>From focus point 0 to focus point 4.</li>
<li>From focus point 0 to focus point 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 7, crystals = [3,5], flowFrom = [0,1,2,3,5], flowTo = [1,2,0,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample1.png" style="width: 250px; height: 250px;" /></p>
<p>Add a directed rune from focus point 4 to focus point 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= crystals.length <= n</code></li>
<li><code>0 <= crystals[i] <= n - 1</code></li>
<li><code>1 <= flowFrom.length == flowTo.length <= min(2 * 10<sup>5</sup>, (n * (n - 1)) / 2)</code></li>
<li><code>0 <= flowFrom[i], flowTo[i] <= n - 1</code></li>
<li><code>flowFrom[i] != flowTo[i]</code></li>
<li>All pre-existing directed runes are <strong>distinct</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Topological Sort; Array
|
Go
|
func minRunesToAdd(n int, crystals []int, flowFrom []int, flowTo []int) (ans int) {
g := make([][]int, n)
for i := 0; i < len(flowFrom); i++ {
a, b := flowFrom[i], flowTo[i]
g[a] = append(g[a], b)
}
vis := make([]int, n)
for _, x := range crystals {
vis[x] = 1
}
bfs := func(q []int) {
for len(q) > 0 {
a := q[0]
q = q[1:]
for _, b := range g[a] {
if vis[b] == 1 {
continue
}
vis[b] = 1
q = append(q, b)
}
}
}
seq := []int{}
var dfs func(a int)
dfs = func(a int) {
vis[a] = 2
for _, b := range g[a] {
if vis[b] > 0 {
continue
}
dfs(b)
}
seq = append(seq, a)
}
q := crystals
bfs(q)
for i := 0; i < n; i++ {
if vis[i] == 0 {
dfs(i)
}
}
for i, j := 0, len(seq)-1; i < j; i, j = i+1, j-1 {
seq[i], seq[j] = seq[j], seq[i]
}
for _, i := range seq {
if vis[i] == 2 {
q = []int{i}
vis[i] = 1
bfs(q)
ans++
}
}
return
}
|
3,383 |
Minimum Runes to Add to Cast Spell
|
Hard
|
<p>Alice has just graduated from wizard school, and wishes to cast a magic spell to celebrate. The magic spell contains certain <strong>focus points</strong> where magic needs to be concentrated, and some of these focus points contain <strong>magic crystals</strong> which serve as the spell's energy source. Focus points can be linked through <strong>directed runes</strong>, which channel magic flow from one focus point to another.</p>
<p>You are given a integer <code>n</code> denoting the <em>number</em> of focus points and an array of integers <code>crystals</code> where <code>crystals[i]</code> indicates a focus point which holds a magic crystal. You are also given two integer arrays <code>flowFrom</code> and <code>flowTo</code>, which represent the existing <strong>directed runes</strong>. The <code>i<sup>th</sup></code> rune allows magic to freely flow from focus point <code>flowFrom[i]</code> to focus point <code>flowTo[i]</code>.</p>
<p>You need to find the number of directed runes Alice must add to her spell, such that <em>each</em> focus point either:</p>
<ul>
<li><strong>Contains</strong> a magic crystal.</li>
<li><strong>Receives</strong> magic flow <em>from</em> another focus point.</li>
</ul>
<p>Return the <strong>minimum</strong> number of directed runes that she should add.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 6, crystals = [0], flowFrom = [0,1,2,3], flowTo = [1,2,3,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample0.png" style="width: 250px; height: 252px;" /></p>
<p>Add two directed runes:</p>
<ul>
<li>From focus point 0 to focus point 4.</li>
<li>From focus point 0 to focus point 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 7, crystals = [3,5], flowFrom = [0,1,2,3,5], flowTo = [1,2,0,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample1.png" style="width: 250px; height: 250px;" /></p>
<p>Add a directed rune from focus point 4 to focus point 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= crystals.length <= n</code></li>
<li><code>0 <= crystals[i] <= n - 1</code></li>
<li><code>1 <= flowFrom.length == flowTo.length <= min(2 * 10<sup>5</sup>, (n * (n - 1)) / 2)</code></li>
<li><code>0 <= flowFrom[i], flowTo[i] <= n - 1</code></li>
<li><code>flowFrom[i] != flowTo[i]</code></li>
<li>All pre-existing directed runes are <strong>distinct</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Topological Sort; Array
|
Java
|
class Solution {
private int[] vis;
private List<Integer>[] g;
private List<Integer> seq = new ArrayList<>();
public int minRunesToAdd(int n, int[] crystals, int[] flowFrom, int[] flowTo) {
g = new List[n];
Arrays.setAll(g, i -> new ArrayList<>());
for (int i = 0; i < flowFrom.length; ++i) {
g[flowFrom[i]].add(flowTo[i]);
}
Deque<Integer> q = new ArrayDeque<>();
vis = new int[n];
for (int i : crystals) {
vis[i] = 1;
q.offer(i);
}
bfs(q);
for (int i = 0; i < n; ++i) {
if (vis[i] == 0) {
dfs(i);
}
}
int ans = 0;
for (int i = seq.size() - 1; i >= 0; --i) {
int a = seq.get(i);
if (vis[a] == 2) {
vis[a] = 1;
q.clear();
q.offer(a);
bfs(q);
++ans;
}
}
return ans;
}
private void bfs(Deque<Integer> q) {
while (!q.isEmpty()) {
int a = q.poll();
for (int b : g[a]) {
if (vis[b] == 1) {
continue;
}
vis[b] = 1;
q.offer(b);
}
}
}
private void dfs(int a) {
vis[a] = 2;
for (int b : g[a]) {
if (vis[b] > 0) {
continue;
}
dfs(b);
}
seq.add(a);
}
}
|
3,383 |
Minimum Runes to Add to Cast Spell
|
Hard
|
<p>Alice has just graduated from wizard school, and wishes to cast a magic spell to celebrate. The magic spell contains certain <strong>focus points</strong> where magic needs to be concentrated, and some of these focus points contain <strong>magic crystals</strong> which serve as the spell's energy source. Focus points can be linked through <strong>directed runes</strong>, which channel magic flow from one focus point to another.</p>
<p>You are given a integer <code>n</code> denoting the <em>number</em> of focus points and an array of integers <code>crystals</code> where <code>crystals[i]</code> indicates a focus point which holds a magic crystal. You are also given two integer arrays <code>flowFrom</code> and <code>flowTo</code>, which represent the existing <strong>directed runes</strong>. The <code>i<sup>th</sup></code> rune allows magic to freely flow from focus point <code>flowFrom[i]</code> to focus point <code>flowTo[i]</code>.</p>
<p>You need to find the number of directed runes Alice must add to her spell, such that <em>each</em> focus point either:</p>
<ul>
<li><strong>Contains</strong> a magic crystal.</li>
<li><strong>Receives</strong> magic flow <em>from</em> another focus point.</li>
</ul>
<p>Return the <strong>minimum</strong> number of directed runes that she should add.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 6, crystals = [0], flowFrom = [0,1,2,3], flowTo = [1,2,3,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample0.png" style="width: 250px; height: 252px;" /></p>
<p>Add two directed runes:</p>
<ul>
<li>From focus point 0 to focus point 4.</li>
<li>From focus point 0 to focus point 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 7, crystals = [3,5], flowFrom = [0,1,2,3,5], flowTo = [1,2,0,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample1.png" style="width: 250px; height: 250px;" /></p>
<p>Add a directed rune from focus point 4 to focus point 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= crystals.length <= n</code></li>
<li><code>0 <= crystals[i] <= n - 1</code></li>
<li><code>1 <= flowFrom.length == flowTo.length <= min(2 * 10<sup>5</sup>, (n * (n - 1)) / 2)</code></li>
<li><code>0 <= flowFrom[i], flowTo[i] <= n - 1</code></li>
<li><code>flowFrom[i] != flowTo[i]</code></li>
<li>All pre-existing directed runes are <strong>distinct</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Topological Sort; Array
|
Python
|
class Solution:
def minRunesToAdd(
self, n: int, crystals: List[int], flowFrom: List[int], flowTo: List[int]
) -> int:
def bfs(q: Deque[int]):
while q:
a = q.popleft()
for b in g[a]:
if vis[b] == 1:
continue
vis[b] = 1
q.append(b)
def dfs(a: int):
vis[a] = 2
for b in g[a]:
if vis[b] > 0:
continue
dfs(b)
seq.append(a)
g = [[] for _ in range(n)]
for a, b in zip(flowFrom, flowTo):
g[a].append(b)
q = deque(crystals)
vis = [0] * n
for x in crystals:
vis[x] = 1
bfs(q)
seq = []
for i in range(n):
if vis[i] == 0:
dfs(i)
seq.reverse()
ans = 0
for i in seq:
if vis[i] == 2:
q = deque([i])
vis[i] = 1
bfs(q)
ans += 1
return ans
|
3,383 |
Minimum Runes to Add to Cast Spell
|
Hard
|
<p>Alice has just graduated from wizard school, and wishes to cast a magic spell to celebrate. The magic spell contains certain <strong>focus points</strong> where magic needs to be concentrated, and some of these focus points contain <strong>magic crystals</strong> which serve as the spell's energy source. Focus points can be linked through <strong>directed runes</strong>, which channel magic flow from one focus point to another.</p>
<p>You are given a integer <code>n</code> denoting the <em>number</em> of focus points and an array of integers <code>crystals</code> where <code>crystals[i]</code> indicates a focus point which holds a magic crystal. You are also given two integer arrays <code>flowFrom</code> and <code>flowTo</code>, which represent the existing <strong>directed runes</strong>. The <code>i<sup>th</sup></code> rune allows magic to freely flow from focus point <code>flowFrom[i]</code> to focus point <code>flowTo[i]</code>.</p>
<p>You need to find the number of directed runes Alice must add to her spell, such that <em>each</em> focus point either:</p>
<ul>
<li><strong>Contains</strong> a magic crystal.</li>
<li><strong>Receives</strong> magic flow <em>from</em> another focus point.</li>
</ul>
<p>Return the <strong>minimum</strong> number of directed runes that she should add.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 6, crystals = [0], flowFrom = [0,1,2,3], flowTo = [1,2,3,0]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample0.png" style="width: 250px; height: 252px;" /></p>
<p>Add two directed runes:</p>
<ul>
<li>From focus point 0 to focus point 4.</li>
<li>From focus point 0 to focus point 5.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 7, crystals = [3,5], flowFrom = [0,1,2,3,5], flowTo = [1,2,0,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3383.Minimum%20Runes%20to%20Add%20to%20Cast%20Spell/images/runesexample1.png" style="width: 250px; height: 250px;" /></p>
<p>Add a directed rune from focus point 4 to focus point 2.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= crystals.length <= n</code></li>
<li><code>0 <= crystals[i] <= n - 1</code></li>
<li><code>1 <= flowFrom.length == flowTo.length <= min(2 * 10<sup>5</sup>, (n * (n - 1)) / 2)</code></li>
<li><code>0 <= flowFrom[i], flowTo[i] <= n - 1</code></li>
<li><code>flowFrom[i] != flowTo[i]</code></li>
<li>All pre-existing directed runes are <strong>distinct</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Union Find; Graph; Topological Sort; Array
|
TypeScript
|
function minRunesToAdd(
n: number,
crystals: number[],
flowFrom: number[],
flowTo: number[],
): number {
const g: number[][] = Array.from({ length: n }, () => []);
for (let i = 0; i < flowFrom.length; i++) {
const a = flowFrom[i],
b = flowTo[i];
g[a].push(b);
}
const vis: number[] = Array(n).fill(0);
for (const x of crystals) {
vis[x] = 1;
}
const bfs = (q: number[]) => {
while (q.length > 0) {
const a = q.shift()!;
for (const b of g[a]) {
if (vis[b] === 1) continue;
vis[b] = 1;
q.push(b);
}
}
};
const seq: number[] = [];
const dfs = (a: number) => {
vis[a] = 2;
for (const b of g[a]) {
if (vis[b] > 0) continue;
dfs(b);
}
seq.push(a);
};
bfs(crystals);
for (let i = 0; i < n; i++) {
if (vis[i] === 0) {
dfs(i);
}
}
seq.reverse();
let ans = 0;
for (const i of seq) {
if (vis[i] === 2) {
bfs([i]);
vis[i] = 1;
ans++;
}
}
return ans;
}
|
3,384 |
Team Dominance by Pass Success
|
Hard
|
<p>Table: <code>Teams</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| player_id | int |
| team_name | varchar |
+-------------+---------+
player_id is the unique key for this table.
Each row contains the unique identifier for player and the name of one of the teams participating in that match.
</pre>
<p>Table: <code>Passes</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| pass_from | int |
| time_stamp | varchar |
| pass_to | int |
+-------------+---------+
(pass_from, time_stamp) is the primary key for this table.
pass_from is a foreign key to player_id from Teams table.
Each row represents a pass made during a match, time_stamp represents the time in minutes (00:00-90:00) when the pass was made,
pass_to is the player_id of the player receiving the pass.
</pre>
<p>Write a solution to calculate the <strong>dominance score</strong> for each team in<strong> both halves of the match</strong>. The rules are as follows:</p>
<ul>
<li>A match is divided into two halves: <strong>first half</strong> (<code>00:00</code>-<code><font face="monospace">45:00</font></code> minutes) and <strong>second half </strong>(<code>45:01</code>-<code>90:00</code> minutes)</li>
<li>The dominance score is calculated based on successful and intercepted passes:
<ul>
<li>When pass_to is a player from the <strong>same team</strong>: +<code>1</code> point</li>
<li>When pass_to is a player from the <strong>opposing team</strong> (interception): <code>-1</code> point</li>
</ul>
</li>
<li>A higher dominance score indicates better passing performance</li>
</ul>
<p>Return <em>the result table ordered </em><em>by</em> <code>team_name</code> and <code>half_number</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Teams table:</p>
<pre class="example-io">
+------------+-----------+
| player_id | team_name |
+------------+-----------+
| 1 | Arsenal |
| 2 | Arsenal |
| 3 | Arsenal |
| 4 | Chelsea |
| 5 | Chelsea |
| 6 | Chelsea |
+------------+-----------+
</pre>
<p>Passes table:</p>
<pre class="example-io">
+-----------+------------+---------+
| pass_from | time_stamp | pass_to |
+-----------+------------+---------+
| 1 | 00:15 | 2 |
| 2 | 00:45 | 3 |
| 3 | 01:15 | 1 |
| 4 | 00:30 | 1 |
| 2 | 46:00 | 3 |
| 3 | 46:15 | 4 |
| 1 | 46:45 | 2 |
| 5 | 46:30 | 6 |
+-----------+------------+---------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-----------+-------------+-----------+
| team_name | half_number | dominance |
+-----------+-------------+-----------+
| Arsenal | 1 | 3 |
| Arsenal | 2 | 1 |
| Chelsea | 1 | -1 |
| Chelsea | 2 | 1 |
+-----------+-------------+-----------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>First Half (00:00-45:00):</strong>
<ul>
<li>Arsenal's passes:
<ul>
<li>1 → 2 (00:15): Successful pass (+1)</li>
<li>2 → 3 (00:45): Successful pass (+1)</li>
<li>3 → 1 (01:15): Successful pass (+1)</li>
</ul>
</li>
<li>Chelsea's passes:
<ul>
<li>4 → 1 (00:30): Intercepted by Arsenal (-1)</li>
</ul>
</li>
</ul>
</li>
<li><strong>Second Half (45:01-90:00):</strong>
<ul>
<li>Arsenal's passes:
<ul>
<li>2 → 3 (46:00): Successful pass (+1)</li>
<li>3 → 4 (46:15): Intercepted by Chelsea (-1)</li>
<li>1 → 2 (46:45): Successful pass (+1)</li>
</ul>
</li>
<li>Chelsea's passes:
<ul>
<li>5 → 6 (46:30): Successful pass (+1)</li>
</ul>
</li>
</ul>
</li>
<li>The results are ordered by team_name and then half_number</li>
</ul>
</div>
|
Database
|
Python
|
import pandas as pd
def calculate_team_dominance(teams: pd.DataFrame, passes: pd.DataFrame) -> pd.DataFrame:
passes_with_teams = passes.merge(
teams, left_on="pass_from", right_on="player_id", suffixes=("", "_team_from")
).merge(
teams,
left_on="pass_to",
right_on="player_id",
suffixes=("_team_from", "_team_to"),
)
passes_with_teams["half_number"] = passes_with_teams["time_stamp"].apply(
lambda x: 1 if x <= "45:00" else 2
)
passes_with_teams["dominance"] = passes_with_teams.apply(
lambda row: 1 if row["team_name_team_from"] == row["team_name_team_to"] else -1,
axis=1,
)
result = (
passes_with_teams.groupby(["team_name_team_from", "half_number"])["dominance"]
.sum()
.reset_index()
)
result.columns = ["team_name", "half_number", "dominance"]
result = result.sort_values(by=["team_name", "half_number"])
return result
|
3,384 |
Team Dominance by Pass Success
|
Hard
|
<p>Table: <code>Teams</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| player_id | int |
| team_name | varchar |
+-------------+---------+
player_id is the unique key for this table.
Each row contains the unique identifier for player and the name of one of the teams participating in that match.
</pre>
<p>Table: <code>Passes</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| pass_from | int |
| time_stamp | varchar |
| pass_to | int |
+-------------+---------+
(pass_from, time_stamp) is the primary key for this table.
pass_from is a foreign key to player_id from Teams table.
Each row represents a pass made during a match, time_stamp represents the time in minutes (00:00-90:00) when the pass was made,
pass_to is the player_id of the player receiving the pass.
</pre>
<p>Write a solution to calculate the <strong>dominance score</strong> for each team in<strong> both halves of the match</strong>. The rules are as follows:</p>
<ul>
<li>A match is divided into two halves: <strong>first half</strong> (<code>00:00</code>-<code><font face="monospace">45:00</font></code> minutes) and <strong>second half </strong>(<code>45:01</code>-<code>90:00</code> minutes)</li>
<li>The dominance score is calculated based on successful and intercepted passes:
<ul>
<li>When pass_to is a player from the <strong>same team</strong>: +<code>1</code> point</li>
<li>When pass_to is a player from the <strong>opposing team</strong> (interception): <code>-1</code> point</li>
</ul>
</li>
<li>A higher dominance score indicates better passing performance</li>
</ul>
<p>Return <em>the result table ordered </em><em>by</em> <code>team_name</code> and <code>half_number</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Teams table:</p>
<pre class="example-io">
+------------+-----------+
| player_id | team_name |
+------------+-----------+
| 1 | Arsenal |
| 2 | Arsenal |
| 3 | Arsenal |
| 4 | Chelsea |
| 5 | Chelsea |
| 6 | Chelsea |
+------------+-----------+
</pre>
<p>Passes table:</p>
<pre class="example-io">
+-----------+------------+---------+
| pass_from | time_stamp | pass_to |
+-----------+------------+---------+
| 1 | 00:15 | 2 |
| 2 | 00:45 | 3 |
| 3 | 01:15 | 1 |
| 4 | 00:30 | 1 |
| 2 | 46:00 | 3 |
| 3 | 46:15 | 4 |
| 1 | 46:45 | 2 |
| 5 | 46:30 | 6 |
+-----------+------------+---------+
</pre>
<p><strong>Output:</strong></p>
<pre class="example-io">
+-----------+-------------+-----------+
| team_name | half_number | dominance |
+-----------+-------------+-----------+
| Arsenal | 1 | 3 |
| Arsenal | 2 | 1 |
| Chelsea | 1 | -1 |
| Chelsea | 2 | 1 |
+-----------+-------------+-----------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>First Half (00:00-45:00):</strong>
<ul>
<li>Arsenal's passes:
<ul>
<li>1 → 2 (00:15): Successful pass (+1)</li>
<li>2 → 3 (00:45): Successful pass (+1)</li>
<li>3 → 1 (01:15): Successful pass (+1)</li>
</ul>
</li>
<li>Chelsea's passes:
<ul>
<li>4 → 1 (00:30): Intercepted by Arsenal (-1)</li>
</ul>
</li>
</ul>
</li>
<li><strong>Second Half (45:01-90:00):</strong>
<ul>
<li>Arsenal's passes:
<ul>
<li>2 → 3 (46:00): Successful pass (+1)</li>
<li>3 → 4 (46:15): Intercepted by Chelsea (-1)</li>
<li>1 → 2 (46:45): Successful pass (+1)</li>
</ul>
</li>
<li>Chelsea's passes:
<ul>
<li>5 → 6 (46:30): Successful pass (+1)</li>
</ul>
</li>
</ul>
</li>
<li>The results are ordered by team_name and then half_number</li>
</ul>
</div>
|
Database
|
SQL
|
# Write your MySQL query statement below
WITH
T AS (
SELECT
t1.team_name,
IF(time_stamp <= '45:00', 1, 2) half_number,
IF(t1.team_name = t2.team_name, 1, -1) dominance
FROM
Passes p
JOIN Teams t1 ON p.pass_from = t1.player_id
JOIN Teams t2 ON p.pass_to = t2.player_id
)
SELECT team_name, half_number, SUM(dominance) dominance
FROM T
GROUP BY 1, 2
ORDER BY 1, 2;
|
3,385 |
Minimum Time to Break Locks II
|
Hard
|
<p>Bob is stuck in a dungeon and must break <code>n</code> locks, each requiring some amount of <strong>energy</strong> to break. The required energy for each lock is stored in an array called <code>strength</code> where <code>strength[i]</code> indicates the energy needed to break the <code>i<sup>th</sup></code> lock.</p>
<p>To break a lock, Bob uses a sword with the following characteristics:</p>
<ul>
<li>The initial energy of the sword is 0.</li>
<li>The initial factor <code><font face="monospace">X</font></code> by which the energy of the sword increases is 1.</li>
<li>Every minute, the energy of the sword increases by the current factor <code>X</code>.</li>
<li>To break the <code>i<sup>th</sup></code> lock, the energy of the sword must reach at least <code>strength[i]</code>.</li>
<li>After breaking a lock, the energy of the sword resets to 0, and the factor <code>X</code> increases by 1.</li>
</ul>
<p>Your task is to determine the <strong>minimum</strong> time in minutes required for Bob to break all <code>n</code> locks and escape the dungeon.</p>
<p>Return the <strong>minimum </strong>time required for Bob to break all <code>n</code> locks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [3,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Time</th>
<th>Energy</th>
<th>X</th>
<th>Action</th>
<th>Updated X</th>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>1</td>
<td>Nothing</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>Break 3<sup>rd</sup> Lock</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>2</td>
<td>Nothing</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>2</td>
<td>Break 2<sup>nd</sup> Lock</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>3</td>
<td>Break 1<sup>st</sup> Lock</td>
<td>3</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 4 minutes; thus, the answer is 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [2,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Time</th>
<th>Energy</th>
<th>X</th>
<th>Action</th>
<th>Updated X</th>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>1</td>
<td>Nothing</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>Nothing</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>1</td>
<td>Break 1<sup>st</sup> Lock</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>2</td>
<td>Nothing</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>4</td>
<td>2</td>
<td>Break 3<sup>rd</sup> Lock</td>
<td>3</td>
</tr>
<tr>
<td>5</td>
<td>3</td>
<td>3</td>
<td>Nothing</td>
<td>3</td>
</tr>
<tr>
<td>6</td>
<td>6</td>
<td>3</td>
<td>Break 2<sup>nd</sup> Lock</td>
<td>4</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 6 minutes; thus, the answer is 6.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == strength.length</code></li>
<li><code>1 <= n <= 80</code></li>
<li><code>1 <= strength[i] <= 10<sup>6</sup></code></li>
<li><code>n == strength.length</code></li>
</ul>
|
Depth-First Search; Graph; Array
|
Java
|
class MCFGraph {
static class Edge {
int src, dst, cap, flow, cost;
Edge(int src, int dst, int cap, int flow, int cost) {
this.src = src;
this.dst = dst;
this.cap = cap;
this.flow = flow;
this.cost = cost;
}
}
static class _Edge {
int dst, cap, cost;
_Edge rev;
_Edge(int dst, int cap, int cost) {
this.dst = dst;
this.cap = cap;
this.cost = cost;
this.rev = null;
}
}
private int n;
private List<List<_Edge>> graph;
private List<_Edge> edges;
public MCFGraph(int n) {
this.n = n;
this.graph = new ArrayList<>();
this.edges = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
}
public int addEdge(int src, int dst, int cap, int cost) {
assert (0 <= src && src < n);
assert (0 <= dst && dst < n);
assert (0 <= cap);
int m = edges.size();
_Edge e = new _Edge(dst, cap, cost);
_Edge re = new _Edge(src, 0, -cost);
e.rev = re;
re.rev = e;
graph.get(src).add(e);
graph.get(dst).add(re);
edges.add(e);
return m;
}
public Edge getEdge(int i) {
assert (0 <= i && i < edges.size());
_Edge e = edges.get(i);
_Edge re = e.rev;
return new Edge(re.dst, e.dst, e.cap + re.cap, re.cap, e.cost);
}
public List<Edge> edges() {
List<Edge> result = new ArrayList<>();
for (int i = 0; i < edges.size(); i++) {
result.add(getEdge(i));
}
return result;
}
public int[] flow(int s, int t, Integer flowLimit) {
List<int[]> result = slope(s, t, flowLimit);
return result.get(result.size() - 1);
}
public List<int[]> slope(int s, int t, Integer flowLimit) {
assert (0 <= s && s < n);
assert (0 <= t && t < n);
assert (s != t);
if (flowLimit == null) {
flowLimit = graph.get(s).stream().mapToInt(e -> e.cap).sum();
}
int[] dual = new int[n];
Tuple[] prev = new Tuple[n];
List<int[]> result = new ArrayList<>();
result.add(new int[] {0, 0});
while (true) {
if (!refineDual(s, t, dual, prev)) {
break;
}
int f = flowLimit;
int v = t;
while (prev[v] != null) {
Tuple tuple = prev[v];
int u = tuple.first;
_Edge e = tuple.second;
f = Math.min(f, e.cap);
v = u;
}
v = t;
while (prev[v] != null) {
Tuple tuple = prev[v];
int u = tuple.first;
_Edge e = tuple.second;
e.cap -= f;
e.rev.cap += f;
v = u;
}
int c = -dual[s];
result.add(new int[] {
result.get(result.size() - 1)[0] + f, result.get(result.size() - 1)[1] + f * c});
if (c == result.get(result.size() - 2)[1]) {
result.remove(result.size() - 2);
}
}
return result;
}
private boolean refineDual(int s, int t, int[] dual, Tuple[] prev) {
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
pq.add(new int[] {0, s});
boolean[] visited = new boolean[n];
Integer[] dist = new Integer[n];
Arrays.fill(dist, null);
dist[s] = 0;
while (!pq.isEmpty()) {
int[] current = pq.poll();
int distV = current[0];
int v = current[1];
if (visited[v]) continue;
visited[v] = true;
if (v == t) break;
int dualV = dual[v];
for (_Edge e : graph.get(v)) {
int w = e.dst;
if (visited[w] || e.cap == 0) continue;
int reducedCost = e.cost - dual[w] + dualV;
int newDist = distV + reducedCost;
Integer distW = dist[w];
if (distW == null || newDist < distW) {
dist[w] = newDist;
prev[w] = new Tuple(v, e);
pq.add(new int[] {newDist, w});
}
}
}
if (!visited[t]) return false;
int distT = dist[t];
for (int v = 0; v < n; v++) {
if (visited[v]) {
dual[v] -= distT - dist[v];
}
}
return true;
}
static class Tuple {
int first;
_Edge second;
Tuple(int first, _Edge second) {
this.first = first;
this.second = second;
}
}
}
class Solution {
public int findMinimumTime(int[] strength) {
int n = strength.length;
int s = n * 2;
int t = s + 1;
MCFGraph g = new MCFGraph(t + 1);
for (int i = 0; i < n; i++) {
g.addEdge(s, i, 1, 0);
g.addEdge(i + n, t, 1, 0);
for (int j = 0; j < n; j++) {
g.addEdge(i, j + n, 1, (strength[i] - 1) / (j + 1) + 1);
}
}
return g.flow(s, t, n)[1];
}
}
|
3,385 |
Minimum Time to Break Locks II
|
Hard
|
<p>Bob is stuck in a dungeon and must break <code>n</code> locks, each requiring some amount of <strong>energy</strong> to break. The required energy for each lock is stored in an array called <code>strength</code> where <code>strength[i]</code> indicates the energy needed to break the <code>i<sup>th</sup></code> lock.</p>
<p>To break a lock, Bob uses a sword with the following characteristics:</p>
<ul>
<li>The initial energy of the sword is 0.</li>
<li>The initial factor <code><font face="monospace">X</font></code> by which the energy of the sword increases is 1.</li>
<li>Every minute, the energy of the sword increases by the current factor <code>X</code>.</li>
<li>To break the <code>i<sup>th</sup></code> lock, the energy of the sword must reach at least <code>strength[i]</code>.</li>
<li>After breaking a lock, the energy of the sword resets to 0, and the factor <code>X</code> increases by 1.</li>
</ul>
<p>Your task is to determine the <strong>minimum</strong> time in minutes required for Bob to break all <code>n</code> locks and escape the dungeon.</p>
<p>Return the <strong>minimum </strong>time required for Bob to break all <code>n</code> locks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [3,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Time</th>
<th>Energy</th>
<th>X</th>
<th>Action</th>
<th>Updated X</th>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>1</td>
<td>Nothing</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>Break 3<sup>rd</sup> Lock</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>2</td>
<td>Nothing</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>2</td>
<td>Break 2<sup>nd</sup> Lock</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>3</td>
<td>Break 1<sup>st</sup> Lock</td>
<td>3</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 4 minutes; thus, the answer is 4.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">strength = [2,5,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<table>
<tbody>
<tr>
<th>Time</th>
<th>Energy</th>
<th>X</th>
<th>Action</th>
<th>Updated X</th>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>1</td>
<td>Nothing</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>Nothing</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>1</td>
<td>Break 1<sup>st</sup> Lock</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>2</td>
<td>Nothing</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>4</td>
<td>2</td>
<td>Break 3<sup>rd</sup> Lock</td>
<td>3</td>
</tr>
<tr>
<td>5</td>
<td>3</td>
<td>3</td>
<td>Nothing</td>
<td>3</td>
</tr>
<tr>
<td>6</td>
<td>6</td>
<td>3</td>
<td>Break 2<sup>nd</sup> Lock</td>
<td>4</td>
</tr>
</tbody>
</table>
<p>The locks cannot be broken in less than 6 minutes; thus, the answer is 6.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == strength.length</code></li>
<li><code>1 <= n <= 80</code></li>
<li><code>1 <= strength[i] <= 10<sup>6</sup></code></li>
<li><code>n == strength.length</code></li>
</ul>
|
Depth-First Search; Graph; Array
|
Python
|
class MCFGraph:
class Edge(NamedTuple):
src: int
dst: int
cap: int
flow: int
cost: int
class _Edge:
def __init__(self, dst: int, cap: int, cost: int) -> None:
self.dst = dst
self.cap = cap
self.cost = cost
self.rev: Optional[MCFGraph._Edge] = None
def __init__(self, n: int) -> None:
self._n = n
self._g: List[List[MCFGraph._Edge]] = [[] for _ in range(n)]
self._edges: List[MCFGraph._Edge] = []
def add_edge(self, src: int, dst: int, cap: int, cost: int) -> int:
assert 0 <= src < self._n
assert 0 <= dst < self._n
assert 0 <= cap
m = len(self._edges)
e = MCFGraph._Edge(dst, cap, cost)
re = MCFGraph._Edge(src, 0, -cost)
e.rev = re
re.rev = e
self._g[src].append(e)
self._g[dst].append(re)
self._edges.append(e)
return m
def get_edge(self, i: int) -> Edge:
assert 0 <= i < len(self._edges)
e = self._edges[i]
re = cast(MCFGraph._Edge, e.rev)
return MCFGraph.Edge(re.dst, e.dst, e.cap + re.cap, re.cap, e.cost)
def edges(self) -> List[Edge]:
return [self.get_edge(i) for i in range(len(self._edges))]
def flow(self, s: int, t: int, flow_limit: Optional[int] = None) -> Tuple[int, int]:
return self.slope(s, t, flow_limit)[-1]
def slope(
self, s: int, t: int, flow_limit: Optional[int] = None
) -> List[Tuple[int, int]]:
assert 0 <= s < self._n
assert 0 <= t < self._n
assert s != t
if flow_limit is None:
flow_limit = cast(int, sum(e.cap for e in self._g[s]))
dual = [0] * self._n
prev: List[Optional[Tuple[int, MCFGraph._Edge]]] = [None] * self._n
def refine_dual() -> bool:
pq = [(0, s)]
visited = [False] * self._n
dist: List[Optional[int]] = [None] * self._n
dist[s] = 0
while pq:
dist_v, v = heappop(pq)
if visited[v]:
continue
visited[v] = True
if v == t:
break
dual_v = dual[v]
for e in self._g[v]:
w = e.dst
if visited[w] or e.cap == 0:
continue
reduced_cost = e.cost - dual[w] + dual_v
new_dist = dist_v + reduced_cost
dist_w = dist[w]
if dist_w is None or new_dist < dist_w:
dist[w] = new_dist
prev[w] = v, e
heappush(pq, (new_dist, w))
else:
return False
dist_t = dist[t]
for v in range(self._n):
if visited[v]:
dual[v] -= cast(int, dist_t) - cast(int, dist[v])
return True
flow = 0
cost = 0
prev_cost_per_flow: Optional[int] = None
result = [(flow, cost)]
while flow < flow_limit:
if not refine_dual():
break
f = flow_limit - flow
v = t
while prev[v] is not None:
u, e = cast(Tuple[int, MCFGraph._Edge], prev[v])
f = min(f, e.cap)
v = u
v = t
while prev[v] is not None:
u, e = cast(Tuple[int, MCFGraph._Edge], prev[v])
e.cap -= f
assert e.rev is not None
e.rev.cap += f
v = u
c = -dual[s]
flow += f
cost += f * c
if c == prev_cost_per_flow:
result.pop()
result.append((flow, cost))
prev_cost_per_flow = c
return result
class Solution:
def findMinimumTime(self, a: List[int]) -> int:
n = len(a)
s = n * 2
t = s + 1
g = MCFGraph(t + 1)
for i in range(n):
g.add_edge(s, i, 1, 0)
g.add_edge(i + n, t, 1, 0)
for j in range(n):
g.add_edge(i, j + n, 1, (a[i] - 1) // (j + 1) + 1)
return g.flow(s, t, n)[1]
|
3,386 |
Button with Longest Push Time
|
Easy
|
<p>You are given a 2D array <code>events</code> which represents a sequence of events where a child pushes a series of buttons on a keyboard.</p>
<p>Each <code>events[i] = [index<sub>i</sub>, time<sub>i</sub>]</code> indicates that the button at index <code>index<sub>i</sub></code> was pressed at time <code>time<sub>i</sub></code>.</p>
<ul>
<li>The array is <strong>sorted</strong> in increasing order of <code>time</code>.</li>
<li>The time taken to press a button is the difference in time between consecutive button presses. The time for the first button is simply the time at which it was pressed.</li>
</ul>
<p>Return the <code>index</code> of the button that took the <strong>longest</strong> time to push. If multiple buttons have the same longest time, return the button with the <strong>smallest</strong> <code>index</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[1,2],[2,5],[3,9],[1,15]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 1 is pressed at time 2.</li>
<li>Button with index 2 is pressed at time 5, so it took <code>5 - 2 = 3</code> units of time.</li>
<li>Button with index 3 is pressed at time 9, so it took <code>9 - 5 = 4</code> units of time.</li>
<li>Button with index 1 is pressed again at time 15, so it took <code>15 - 9 = 6</code> units of time.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[10,5],[1,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 10 is pressed at time 5.</li>
<li>Button with index 1 is pressed at time 7, so it took <code>7 - 5 = 2</code> units of time.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= events.length <= 1000</code></li>
<li><code>events[i] == [index<sub>i</sub>, time<sub>i</sub>]</code></li>
<li><code>1 <= index<sub>i</sub>, time<sub>i</sub> <= 10<sup>5</sup></code></li>
<li>The input is generated such that <code>events</code> is sorted in increasing order of <code>time<sub>i</sub></code>.</li>
</ul>
|
Array
|
C++
|
class Solution {
public:
int buttonWithLongestTime(vector<vector<int>>& events) {
int ans = events[0][0], t = events[0][1];
for (int k = 1; k < events.size(); ++k) {
int i = events[k][0], t2 = events[k][1], t1 = events[k - 1][1];
int d = t2 - t1;
if (d > t || (d == t && ans > i)) {
ans = i;
t = d;
}
}
return ans;
}
};
|
3,386 |
Button with Longest Push Time
|
Easy
|
<p>You are given a 2D array <code>events</code> which represents a sequence of events where a child pushes a series of buttons on a keyboard.</p>
<p>Each <code>events[i] = [index<sub>i</sub>, time<sub>i</sub>]</code> indicates that the button at index <code>index<sub>i</sub></code> was pressed at time <code>time<sub>i</sub></code>.</p>
<ul>
<li>The array is <strong>sorted</strong> in increasing order of <code>time</code>.</li>
<li>The time taken to press a button is the difference in time between consecutive button presses. The time for the first button is simply the time at which it was pressed.</li>
</ul>
<p>Return the <code>index</code> of the button that took the <strong>longest</strong> time to push. If multiple buttons have the same longest time, return the button with the <strong>smallest</strong> <code>index</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[1,2],[2,5],[3,9],[1,15]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 1 is pressed at time 2.</li>
<li>Button with index 2 is pressed at time 5, so it took <code>5 - 2 = 3</code> units of time.</li>
<li>Button with index 3 is pressed at time 9, so it took <code>9 - 5 = 4</code> units of time.</li>
<li>Button with index 1 is pressed again at time 15, so it took <code>15 - 9 = 6</code> units of time.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[10,5],[1,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 10 is pressed at time 5.</li>
<li>Button with index 1 is pressed at time 7, so it took <code>7 - 5 = 2</code> units of time.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= events.length <= 1000</code></li>
<li><code>events[i] == [index<sub>i</sub>, time<sub>i</sub>]</code></li>
<li><code>1 <= index<sub>i</sub>, time<sub>i</sub> <= 10<sup>5</sup></code></li>
<li>The input is generated such that <code>events</code> is sorted in increasing order of <code>time<sub>i</sub></code>.</li>
</ul>
|
Array
|
Go
|
func buttonWithLongestTime(events [][]int) int {
ans, t := events[0][0], events[0][1]
for k, e := range events[1:] {
i, t2, t1 := e[0], e[1], events[k][1]
d := t2 - t1
if d > t || (d == t && i < ans) {
ans, t = i, d
}
}
return ans
}
|
3,386 |
Button with Longest Push Time
|
Easy
|
<p>You are given a 2D array <code>events</code> which represents a sequence of events where a child pushes a series of buttons on a keyboard.</p>
<p>Each <code>events[i] = [index<sub>i</sub>, time<sub>i</sub>]</code> indicates that the button at index <code>index<sub>i</sub></code> was pressed at time <code>time<sub>i</sub></code>.</p>
<ul>
<li>The array is <strong>sorted</strong> in increasing order of <code>time</code>.</li>
<li>The time taken to press a button is the difference in time between consecutive button presses. The time for the first button is simply the time at which it was pressed.</li>
</ul>
<p>Return the <code>index</code> of the button that took the <strong>longest</strong> time to push. If multiple buttons have the same longest time, return the button with the <strong>smallest</strong> <code>index</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[1,2],[2,5],[3,9],[1,15]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 1 is pressed at time 2.</li>
<li>Button with index 2 is pressed at time 5, so it took <code>5 - 2 = 3</code> units of time.</li>
<li>Button with index 3 is pressed at time 9, so it took <code>9 - 5 = 4</code> units of time.</li>
<li>Button with index 1 is pressed again at time 15, so it took <code>15 - 9 = 6</code> units of time.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[10,5],[1,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 10 is pressed at time 5.</li>
<li>Button with index 1 is pressed at time 7, so it took <code>7 - 5 = 2</code> units of time.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= events.length <= 1000</code></li>
<li><code>events[i] == [index<sub>i</sub>, time<sub>i</sub>]</code></li>
<li><code>1 <= index<sub>i</sub>, time<sub>i</sub> <= 10<sup>5</sup></code></li>
<li>The input is generated such that <code>events</code> is sorted in increasing order of <code>time<sub>i</sub></code>.</li>
</ul>
|
Array
|
Java
|
class Solution {
public int buttonWithLongestTime(int[][] events) {
int ans = events[0][0], t = events[0][1];
for (int k = 1; k < events.length; ++k) {
int i = events[k][0], t2 = events[k][1], t1 = events[k - 1][1];
int d = t2 - t1;
if (d > t || (d == t && ans > i)) {
ans = i;
t = d;
}
}
return ans;
}
}
|
3,386 |
Button with Longest Push Time
|
Easy
|
<p>You are given a 2D array <code>events</code> which represents a sequence of events where a child pushes a series of buttons on a keyboard.</p>
<p>Each <code>events[i] = [index<sub>i</sub>, time<sub>i</sub>]</code> indicates that the button at index <code>index<sub>i</sub></code> was pressed at time <code>time<sub>i</sub></code>.</p>
<ul>
<li>The array is <strong>sorted</strong> in increasing order of <code>time</code>.</li>
<li>The time taken to press a button is the difference in time between consecutive button presses. The time for the first button is simply the time at which it was pressed.</li>
</ul>
<p>Return the <code>index</code> of the button that took the <strong>longest</strong> time to push. If multiple buttons have the same longest time, return the button with the <strong>smallest</strong> <code>index</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[1,2],[2,5],[3,9],[1,15]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 1 is pressed at time 2.</li>
<li>Button with index 2 is pressed at time 5, so it took <code>5 - 2 = 3</code> units of time.</li>
<li>Button with index 3 is pressed at time 9, so it took <code>9 - 5 = 4</code> units of time.</li>
<li>Button with index 1 is pressed again at time 15, so it took <code>15 - 9 = 6</code> units of time.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[10,5],[1,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 10 is pressed at time 5.</li>
<li>Button with index 1 is pressed at time 7, so it took <code>7 - 5 = 2</code> units of time.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= events.length <= 1000</code></li>
<li><code>events[i] == [index<sub>i</sub>, time<sub>i</sub>]</code></li>
<li><code>1 <= index<sub>i</sub>, time<sub>i</sub> <= 10<sup>5</sup></code></li>
<li>The input is generated such that <code>events</code> is sorted in increasing order of <code>time<sub>i</sub></code>.</li>
</ul>
|
Array
|
Python
|
class Solution:
def buttonWithLongestTime(self, events: List[List[int]]) -> int:
ans, t = events[0]
for (_, t1), (i, t2) in pairwise(events):
d = t2 - t1
if d > t or (d == t and i < ans):
ans, t = i, d
return ans
|
3,386 |
Button with Longest Push Time
|
Easy
|
<p>You are given a 2D array <code>events</code> which represents a sequence of events where a child pushes a series of buttons on a keyboard.</p>
<p>Each <code>events[i] = [index<sub>i</sub>, time<sub>i</sub>]</code> indicates that the button at index <code>index<sub>i</sub></code> was pressed at time <code>time<sub>i</sub></code>.</p>
<ul>
<li>The array is <strong>sorted</strong> in increasing order of <code>time</code>.</li>
<li>The time taken to press a button is the difference in time between consecutive button presses. The time for the first button is simply the time at which it was pressed.</li>
</ul>
<p>Return the <code>index</code> of the button that took the <strong>longest</strong> time to push. If multiple buttons have the same longest time, return the button with the <strong>smallest</strong> <code>index</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[1,2],[2,5],[3,9],[1,15]]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 1 is pressed at time 2.</li>
<li>Button with index 2 is pressed at time 5, so it took <code>5 - 2 = 3</code> units of time.</li>
<li>Button with index 3 is pressed at time 9, so it took <code>9 - 5 = 4</code> units of time.</li>
<li>Button with index 1 is pressed again at time 15, so it took <code>15 - 9 = 6</code> units of time.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">events = [[10,5],[1,7]]</span></p>
<p><strong>Output:</strong> <span class="example-io">10</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>Button with index 10 is pressed at time 5.</li>
<li>Button with index 1 is pressed at time 7, so it took <code>7 - 5 = 2</code> units of time.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= events.length <= 1000</code></li>
<li><code>events[i] == [index<sub>i</sub>, time<sub>i</sub>]</code></li>
<li><code>1 <= index<sub>i</sub>, time<sub>i</sub> <= 10<sup>5</sup></code></li>
<li>The input is generated such that <code>events</code> is sorted in increasing order of <code>time<sub>i</sub></code>.</li>
</ul>
|
Array
|
TypeScript
|
function buttonWithLongestTime(events: number[][]): number {
let [ans, t] = events[0];
for (let k = 1; k < events.length; ++k) {
const [i, t2] = events[k];
const d = t2 - events[k - 1][1];
if (d > t || (d === t && i < ans)) {
ans = i;
t = d;
}
}
return ans;
}
|
3,387 |
Maximize Amount After Two Days of Conversions
|
Medium
|
<p>You are given a string <code>initialCurrency</code>, and you start with <code>1.0</code> of <code>initialCurrency</code>.</p>
<p>You are also given four arrays with currency pairs (strings) and rates (real numbers):</p>
<ul>
<li><code>pairs1[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates1[i]</code> on <strong>day 1</strong>.</li>
<li><code>pairs2[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates2[i]</code> on <strong>day 2</strong>.</li>
<li>Also, each <code>targetCurrency</code> can be converted back to its corresponding <code>startCurrency</code> at a rate of <code>1 / rate</code>.</li>
</ul>
<p>You can perform <strong>any</strong> number of conversions, <strong>including zero</strong>, using <code>rates1</code> on day 1, <strong>followed</strong> by any number of additional conversions, <strong>including zero</strong>, using <code>rates2</code> on day 2.</p>
<p>Return the <strong>maximum</strong> amount of <code>initialCurrency</code> you can have after performing any number of conversions on both days <strong>in order</strong>.</p>
<p><strong>Note: </strong>Conversion rates are valid, and there will be no contradictions in the rates for either day. The rates for the days are independent of each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "EUR", pairs1 = [["EUR","USD"],["USD","JPY"]], rates1 = [2.0,3.0], pairs2 = [["JPY","USD"],["USD","CHF"],["CHF","EUR"]], rates2 = [4.0,5.0,6.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">720.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>To get the maximum amount of <strong>EUR</strong>, starting with 1.0 <strong>EUR</strong>:</p>
<ul>
<li>On Day 1:
<ul>
<li>Convert <strong>EUR </strong>to <strong>USD</strong> to get 2.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>JPY</strong> to get 6.0 <strong>JPY</strong>.</li>
</ul>
</li>
<li>On Day 2:
<ul>
<li>Convert <strong>JPY</strong> to <strong>USD</strong> to get 24.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>CHF</strong> to get 120.0 <strong>CHF</strong>.</li>
<li>Finally, convert <strong>CHF</strong> to <strong>EUR</strong> to get 720.0 <strong>EUR</strong>.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "NGN", pairs1 = </span>[["NGN","EUR"]]<span class="example-io">, rates1 = </span>[9.0]<span class="example-io">, pairs2 = </span>[["NGN","EUR"]]<span class="example-io">, rates2 = </span>[6.0]</p>
<p><strong>Output:</strong> 1.50000</p>
<p><strong>Explanation:</strong></p>
<p>Converting <strong>NGN</strong> to <strong>EUR</strong> on day 1 and <strong>EUR</strong> to <strong>NGN</strong> using the inverse rate on day 2 gives the maximum amount.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "USD", pairs1 = [["USD","EUR"]], rates1 = [1.0], pairs2 = [["EUR","JPY"]], rates2 = [10.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>In this example, there is no need to make any conversions on either day.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initialCurrency.length <= 3</code></li>
<li><code>initialCurrency</code> consists only of uppercase English letters.</li>
<li><code>1 <= n == pairs1.length <= 10</code></li>
<li><code>1 <= m == pairs2.length <= 10</code></li>
<li><code>pairs1[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!-- notionvc: c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4 --></li>
<li><code>pairs2[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!--{C}%3C!%2D%2D%20notionvc%3A%20c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4%20%2D%2D%3E--></li>
<li><code>1 <= startCurrency<sub>i</sub>.length, targetCurrency<sub>i</sub>.length <= 3</code></li>
<li><code>startCurrency<sub>i</sub></code> and <code>targetCurrency<sub>i</sub></code> consist only of uppercase English letters.</li>
<li><code>rates1.length == n</code></li>
<li><code>rates2.length == m</code></li>
<li><code>1.0 <= rates1[i], rates2[i] <= 10.0</code></li>
<li>The input is generated such that there are no contradictions or cycles in the conversion graphs for either day.</li>
<li>The input is generated such that the output is <strong>at most</strong> <code>5 * 10<sup>10</sup></code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Array; String
|
C++
|
class Solution {
public:
double maxAmount(string initialCurrency, vector<vector<string>>& pairs1, vector<double>& rates1, vector<vector<string>>& pairs2, vector<double>& rates2) {
unordered_map<string, double> d1 = build(pairs1, rates1, initialCurrency);
unordered_map<string, double> d2 = build(pairs2, rates2, initialCurrency);
double ans = 0;
for (const auto& [currency, rate] : d2) {
if (d1.find(currency) != d1.end()) {
ans = max(ans, d1[currency] / rate);
}
}
return ans;
}
private:
unordered_map<string, double> build(vector<vector<string>>& pairs, vector<double>& rates, const string& init) {
unordered_map<string, vector<pair<string, double>>> g;
unordered_map<string, double> d;
for (int i = 0; i < pairs.size(); ++i) {
const string& a = pairs[i][0];
const string& b = pairs[i][1];
double r = rates[i];
g[a].push_back({b, r});
g[b].push_back({a, 1 / r});
}
auto dfs = [&](this auto&& dfs, const string& a, double v) -> void {
if (d.find(a) != d.end()) {
return;
}
d[a] = v;
for (const auto& [b, r] : g[a]) {
if (d.find(b) == d.end()) {
dfs(b, v * r);
}
}
};
dfs(init, 1.0);
return d;
}
};
|
3,387 |
Maximize Amount After Two Days of Conversions
|
Medium
|
<p>You are given a string <code>initialCurrency</code>, and you start with <code>1.0</code> of <code>initialCurrency</code>.</p>
<p>You are also given four arrays with currency pairs (strings) and rates (real numbers):</p>
<ul>
<li><code>pairs1[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates1[i]</code> on <strong>day 1</strong>.</li>
<li><code>pairs2[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates2[i]</code> on <strong>day 2</strong>.</li>
<li>Also, each <code>targetCurrency</code> can be converted back to its corresponding <code>startCurrency</code> at a rate of <code>1 / rate</code>.</li>
</ul>
<p>You can perform <strong>any</strong> number of conversions, <strong>including zero</strong>, using <code>rates1</code> on day 1, <strong>followed</strong> by any number of additional conversions, <strong>including zero</strong>, using <code>rates2</code> on day 2.</p>
<p>Return the <strong>maximum</strong> amount of <code>initialCurrency</code> you can have after performing any number of conversions on both days <strong>in order</strong>.</p>
<p><strong>Note: </strong>Conversion rates are valid, and there will be no contradictions in the rates for either day. The rates for the days are independent of each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "EUR", pairs1 = [["EUR","USD"],["USD","JPY"]], rates1 = [2.0,3.0], pairs2 = [["JPY","USD"],["USD","CHF"],["CHF","EUR"]], rates2 = [4.0,5.0,6.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">720.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>To get the maximum amount of <strong>EUR</strong>, starting with 1.0 <strong>EUR</strong>:</p>
<ul>
<li>On Day 1:
<ul>
<li>Convert <strong>EUR </strong>to <strong>USD</strong> to get 2.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>JPY</strong> to get 6.0 <strong>JPY</strong>.</li>
</ul>
</li>
<li>On Day 2:
<ul>
<li>Convert <strong>JPY</strong> to <strong>USD</strong> to get 24.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>CHF</strong> to get 120.0 <strong>CHF</strong>.</li>
<li>Finally, convert <strong>CHF</strong> to <strong>EUR</strong> to get 720.0 <strong>EUR</strong>.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "NGN", pairs1 = </span>[["NGN","EUR"]]<span class="example-io">, rates1 = </span>[9.0]<span class="example-io">, pairs2 = </span>[["NGN","EUR"]]<span class="example-io">, rates2 = </span>[6.0]</p>
<p><strong>Output:</strong> 1.50000</p>
<p><strong>Explanation:</strong></p>
<p>Converting <strong>NGN</strong> to <strong>EUR</strong> on day 1 and <strong>EUR</strong> to <strong>NGN</strong> using the inverse rate on day 2 gives the maximum amount.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "USD", pairs1 = [["USD","EUR"]], rates1 = [1.0], pairs2 = [["EUR","JPY"]], rates2 = [10.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>In this example, there is no need to make any conversions on either day.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initialCurrency.length <= 3</code></li>
<li><code>initialCurrency</code> consists only of uppercase English letters.</li>
<li><code>1 <= n == pairs1.length <= 10</code></li>
<li><code>1 <= m == pairs2.length <= 10</code></li>
<li><code>pairs1[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!-- notionvc: c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4 --></li>
<li><code>pairs2[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!--{C}%3C!%2D%2D%20notionvc%3A%20c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4%20%2D%2D%3E--></li>
<li><code>1 <= startCurrency<sub>i</sub>.length, targetCurrency<sub>i</sub>.length <= 3</code></li>
<li><code>startCurrency<sub>i</sub></code> and <code>targetCurrency<sub>i</sub></code> consist only of uppercase English letters.</li>
<li><code>rates1.length == n</code></li>
<li><code>rates2.length == m</code></li>
<li><code>1.0 <= rates1[i], rates2[i] <= 10.0</code></li>
<li>The input is generated such that there are no contradictions or cycles in the conversion graphs for either day.</li>
<li>The input is generated such that the output is <strong>at most</strong> <code>5 * 10<sup>10</sup></code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Array; String
|
Go
|
type Pair struct {
Key string
Value float64
}
func maxAmount(initialCurrency string, pairs1 [][]string, rates1 []float64, pairs2 [][]string, rates2 []float64) (ans float64) {
d1 := build(pairs1, rates1, initialCurrency)
d2 := build(pairs2, rates2, initialCurrency)
for currency, rate := range d2 {
if val, found := d1[currency]; found {
ans = max(ans, val/rate)
}
}
return
}
func build(pairs [][]string, rates []float64, init string) map[string]float64 {
g := make(map[string][]Pair)
d := make(map[string]float64)
for i := 0; i < len(pairs); i++ {
a := pairs[i][0]
b := pairs[i][1]
r := rates[i]
g[a] = append(g[a], Pair{Key: b, Value: r})
g[b] = append(g[b], Pair{Key: a, Value: 1.0 / r})
}
dfs(g, d, init, 1.0)
return d
}
func dfs(g map[string][]Pair, d map[string]float64, a string, v float64) {
if _, found := d[a]; found {
return
}
d[a] = v
for _, pair := range g[a] {
b := pair.Key
r := pair.Value
if _, found := d[b]; !found {
dfs(g, d, b, v*r)
}
}
}
|
3,387 |
Maximize Amount After Two Days of Conversions
|
Medium
|
<p>You are given a string <code>initialCurrency</code>, and you start with <code>1.0</code> of <code>initialCurrency</code>.</p>
<p>You are also given four arrays with currency pairs (strings) and rates (real numbers):</p>
<ul>
<li><code>pairs1[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates1[i]</code> on <strong>day 1</strong>.</li>
<li><code>pairs2[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates2[i]</code> on <strong>day 2</strong>.</li>
<li>Also, each <code>targetCurrency</code> can be converted back to its corresponding <code>startCurrency</code> at a rate of <code>1 / rate</code>.</li>
</ul>
<p>You can perform <strong>any</strong> number of conversions, <strong>including zero</strong>, using <code>rates1</code> on day 1, <strong>followed</strong> by any number of additional conversions, <strong>including zero</strong>, using <code>rates2</code> on day 2.</p>
<p>Return the <strong>maximum</strong> amount of <code>initialCurrency</code> you can have after performing any number of conversions on both days <strong>in order</strong>.</p>
<p><strong>Note: </strong>Conversion rates are valid, and there will be no contradictions in the rates for either day. The rates for the days are independent of each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "EUR", pairs1 = [["EUR","USD"],["USD","JPY"]], rates1 = [2.0,3.0], pairs2 = [["JPY","USD"],["USD","CHF"],["CHF","EUR"]], rates2 = [4.0,5.0,6.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">720.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>To get the maximum amount of <strong>EUR</strong>, starting with 1.0 <strong>EUR</strong>:</p>
<ul>
<li>On Day 1:
<ul>
<li>Convert <strong>EUR </strong>to <strong>USD</strong> to get 2.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>JPY</strong> to get 6.0 <strong>JPY</strong>.</li>
</ul>
</li>
<li>On Day 2:
<ul>
<li>Convert <strong>JPY</strong> to <strong>USD</strong> to get 24.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>CHF</strong> to get 120.0 <strong>CHF</strong>.</li>
<li>Finally, convert <strong>CHF</strong> to <strong>EUR</strong> to get 720.0 <strong>EUR</strong>.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "NGN", pairs1 = </span>[["NGN","EUR"]]<span class="example-io">, rates1 = </span>[9.0]<span class="example-io">, pairs2 = </span>[["NGN","EUR"]]<span class="example-io">, rates2 = </span>[6.0]</p>
<p><strong>Output:</strong> 1.50000</p>
<p><strong>Explanation:</strong></p>
<p>Converting <strong>NGN</strong> to <strong>EUR</strong> on day 1 and <strong>EUR</strong> to <strong>NGN</strong> using the inverse rate on day 2 gives the maximum amount.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "USD", pairs1 = [["USD","EUR"]], rates1 = [1.0], pairs2 = [["EUR","JPY"]], rates2 = [10.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>In this example, there is no need to make any conversions on either day.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initialCurrency.length <= 3</code></li>
<li><code>initialCurrency</code> consists only of uppercase English letters.</li>
<li><code>1 <= n == pairs1.length <= 10</code></li>
<li><code>1 <= m == pairs2.length <= 10</code></li>
<li><code>pairs1[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!-- notionvc: c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4 --></li>
<li><code>pairs2[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!--{C}%3C!%2D%2D%20notionvc%3A%20c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4%20%2D%2D%3E--></li>
<li><code>1 <= startCurrency<sub>i</sub>.length, targetCurrency<sub>i</sub>.length <= 3</code></li>
<li><code>startCurrency<sub>i</sub></code> and <code>targetCurrency<sub>i</sub></code> consist only of uppercase English letters.</li>
<li><code>rates1.length == n</code></li>
<li><code>rates2.length == m</code></li>
<li><code>1.0 <= rates1[i], rates2[i] <= 10.0</code></li>
<li>The input is generated such that there are no contradictions or cycles in the conversion graphs for either day.</li>
<li>The input is generated such that the output is <strong>at most</strong> <code>5 * 10<sup>10</sup></code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Array; String
|
Java
|
class Solution {
public double maxAmount(String initialCurrency, List<List<String>> pairs1, double[] rates1,
List<List<String>> pairs2, double[] rates2) {
Map<String, Double> d1 = build(pairs1, rates1, initialCurrency);
Map<String, Double> d2 = build(pairs2, rates2, initialCurrency);
double ans = 0;
for (Map.Entry<String, Double> entry : d2.entrySet()) {
String currency = entry.getKey();
double rate = entry.getValue();
if (d1.containsKey(currency)) {
ans = Math.max(ans, d1.get(currency) / rate);
}
}
return ans;
}
private Map<String, Double> build(List<List<String>> pairs, double[] rates, String init) {
Map<String, List<Pair<String, Double>>> g = new HashMap<>();
Map<String, Double> d = new HashMap<>();
for (int i = 0; i < pairs.size(); ++i) {
String a = pairs.get(i).get(0);
String b = pairs.get(i).get(1);
double r = rates[i];
g.computeIfAbsent(a, k -> new ArrayList<>()).add(new Pair<>(b, r));
g.computeIfAbsent(b, k -> new ArrayList<>()).add(new Pair<>(a, 1 / r));
}
dfs(g, d, init, 1.0);
return d;
}
private void dfs(
Map<String, List<Pair<String, Double>>> g, Map<String, Double> d, String a, double v) {
if (d.containsKey(a)) {
return;
}
d.put(a, v);
for (Pair<String, Double> pair : g.getOrDefault(a, List.of())) {
String b = pair.getKey();
double r = pair.getValue();
if (!d.containsKey(b)) {
dfs(g, d, b, v * r);
}
}
}
}
|
3,387 |
Maximize Amount After Two Days of Conversions
|
Medium
|
<p>You are given a string <code>initialCurrency</code>, and you start with <code>1.0</code> of <code>initialCurrency</code>.</p>
<p>You are also given four arrays with currency pairs (strings) and rates (real numbers):</p>
<ul>
<li><code>pairs1[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates1[i]</code> on <strong>day 1</strong>.</li>
<li><code>pairs2[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates2[i]</code> on <strong>day 2</strong>.</li>
<li>Also, each <code>targetCurrency</code> can be converted back to its corresponding <code>startCurrency</code> at a rate of <code>1 / rate</code>.</li>
</ul>
<p>You can perform <strong>any</strong> number of conversions, <strong>including zero</strong>, using <code>rates1</code> on day 1, <strong>followed</strong> by any number of additional conversions, <strong>including zero</strong>, using <code>rates2</code> on day 2.</p>
<p>Return the <strong>maximum</strong> amount of <code>initialCurrency</code> you can have after performing any number of conversions on both days <strong>in order</strong>.</p>
<p><strong>Note: </strong>Conversion rates are valid, and there will be no contradictions in the rates for either day. The rates for the days are independent of each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "EUR", pairs1 = [["EUR","USD"],["USD","JPY"]], rates1 = [2.0,3.0], pairs2 = [["JPY","USD"],["USD","CHF"],["CHF","EUR"]], rates2 = [4.0,5.0,6.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">720.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>To get the maximum amount of <strong>EUR</strong>, starting with 1.0 <strong>EUR</strong>:</p>
<ul>
<li>On Day 1:
<ul>
<li>Convert <strong>EUR </strong>to <strong>USD</strong> to get 2.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>JPY</strong> to get 6.0 <strong>JPY</strong>.</li>
</ul>
</li>
<li>On Day 2:
<ul>
<li>Convert <strong>JPY</strong> to <strong>USD</strong> to get 24.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>CHF</strong> to get 120.0 <strong>CHF</strong>.</li>
<li>Finally, convert <strong>CHF</strong> to <strong>EUR</strong> to get 720.0 <strong>EUR</strong>.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "NGN", pairs1 = </span>[["NGN","EUR"]]<span class="example-io">, rates1 = </span>[9.0]<span class="example-io">, pairs2 = </span>[["NGN","EUR"]]<span class="example-io">, rates2 = </span>[6.0]</p>
<p><strong>Output:</strong> 1.50000</p>
<p><strong>Explanation:</strong></p>
<p>Converting <strong>NGN</strong> to <strong>EUR</strong> on day 1 and <strong>EUR</strong> to <strong>NGN</strong> using the inverse rate on day 2 gives the maximum amount.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "USD", pairs1 = [["USD","EUR"]], rates1 = [1.0], pairs2 = [["EUR","JPY"]], rates2 = [10.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>In this example, there is no need to make any conversions on either day.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initialCurrency.length <= 3</code></li>
<li><code>initialCurrency</code> consists only of uppercase English letters.</li>
<li><code>1 <= n == pairs1.length <= 10</code></li>
<li><code>1 <= m == pairs2.length <= 10</code></li>
<li><code>pairs1[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!-- notionvc: c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4 --></li>
<li><code>pairs2[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!--{C}%3C!%2D%2D%20notionvc%3A%20c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4%20%2D%2D%3E--></li>
<li><code>1 <= startCurrency<sub>i</sub>.length, targetCurrency<sub>i</sub>.length <= 3</code></li>
<li><code>startCurrency<sub>i</sub></code> and <code>targetCurrency<sub>i</sub></code> consist only of uppercase English letters.</li>
<li><code>rates1.length == n</code></li>
<li><code>rates2.length == m</code></li>
<li><code>1.0 <= rates1[i], rates2[i] <= 10.0</code></li>
<li>The input is generated such that there are no contradictions or cycles in the conversion graphs for either day.</li>
<li>The input is generated such that the output is <strong>at most</strong> <code>5 * 10<sup>10</sup></code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Array; String
|
Python
|
class Solution:
def maxAmount(
self,
initialCurrency: str,
pairs1: List[List[str]],
rates1: List[float],
pairs2: List[List[str]],
rates2: List[float],
) -> float:
d1 = self.build(pairs1, rates1, initialCurrency)
d2 = self.build(pairs2, rates2, initialCurrency)
return max(d1.get(a, 0) / r2 for a, r2 in d2.items())
def build(
self, pairs: List[List[str]], rates: List[float], init: str
) -> Dict[str, float]:
def dfs(a: str, v: float):
d[a] = v
for b, r in g[a]:
if b not in d:
dfs(b, v * r)
g = defaultdict(list)
for (a, b), r in zip(pairs, rates):
g[a].append((b, r))
g[b].append((a, 1 / r))
d = {}
dfs(init, 1)
return d
|
3,387 |
Maximize Amount After Two Days of Conversions
|
Medium
|
<p>You are given a string <code>initialCurrency</code>, and you start with <code>1.0</code> of <code>initialCurrency</code>.</p>
<p>You are also given four arrays with currency pairs (strings) and rates (real numbers):</p>
<ul>
<li><code>pairs1[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates1[i]</code> on <strong>day 1</strong>.</li>
<li><code>pairs2[i] = [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code> denotes that you can convert from <code>startCurrency<sub>i</sub></code> to <code>targetCurrency<sub>i</sub></code> at a rate of <code>rates2[i]</code> on <strong>day 2</strong>.</li>
<li>Also, each <code>targetCurrency</code> can be converted back to its corresponding <code>startCurrency</code> at a rate of <code>1 / rate</code>.</li>
</ul>
<p>You can perform <strong>any</strong> number of conversions, <strong>including zero</strong>, using <code>rates1</code> on day 1, <strong>followed</strong> by any number of additional conversions, <strong>including zero</strong>, using <code>rates2</code> on day 2.</p>
<p>Return the <strong>maximum</strong> amount of <code>initialCurrency</code> you can have after performing any number of conversions on both days <strong>in order</strong>.</p>
<p><strong>Note: </strong>Conversion rates are valid, and there will be no contradictions in the rates for either day. The rates for the days are independent of each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "EUR", pairs1 = [["EUR","USD"],["USD","JPY"]], rates1 = [2.0,3.0], pairs2 = [["JPY","USD"],["USD","CHF"],["CHF","EUR"]], rates2 = [4.0,5.0,6.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">720.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>To get the maximum amount of <strong>EUR</strong>, starting with 1.0 <strong>EUR</strong>:</p>
<ul>
<li>On Day 1:
<ul>
<li>Convert <strong>EUR </strong>to <strong>USD</strong> to get 2.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>JPY</strong> to get 6.0 <strong>JPY</strong>.</li>
</ul>
</li>
<li>On Day 2:
<ul>
<li>Convert <strong>JPY</strong> to <strong>USD</strong> to get 24.0 <strong>USD</strong>.</li>
<li>Convert <strong>USD</strong> to <strong>CHF</strong> to get 120.0 <strong>CHF</strong>.</li>
<li>Finally, convert <strong>CHF</strong> to <strong>EUR</strong> to get 720.0 <strong>EUR</strong>.</li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "NGN", pairs1 = </span>[["NGN","EUR"]]<span class="example-io">, rates1 = </span>[9.0]<span class="example-io">, pairs2 = </span>[["NGN","EUR"]]<span class="example-io">, rates2 = </span>[6.0]</p>
<p><strong>Output:</strong> 1.50000</p>
<p><strong>Explanation:</strong></p>
<p>Converting <strong>NGN</strong> to <strong>EUR</strong> on day 1 and <strong>EUR</strong> to <strong>NGN</strong> using the inverse rate on day 2 gives the maximum amount.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">initialCurrency = "USD", pairs1 = [["USD","EUR"]], rates1 = [1.0], pairs2 = [["EUR","JPY"]], rates2 = [10.0]</span></p>
<p><strong>Output:</strong> <span class="example-io">1.00000</span></p>
<p><strong>Explanation:</strong></p>
<p>In this example, there is no need to make any conversions on either day.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= initialCurrency.length <= 3</code></li>
<li><code>initialCurrency</code> consists only of uppercase English letters.</li>
<li><code>1 <= n == pairs1.length <= 10</code></li>
<li><code>1 <= m == pairs2.length <= 10</code></li>
<li><code>pairs1[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!-- notionvc: c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4 --></li>
<li><code>pairs2[i] == [startCurrency<sub>i</sub>, targetCurrency<sub>i</sub>]</code><!--{C}%3C!%2D%2D%20notionvc%3A%20c31b5bb8-4df6-4987-9bcd-6dff8a5f7cd4%20%2D%2D%3E--></li>
<li><code>1 <= startCurrency<sub>i</sub>.length, targetCurrency<sub>i</sub>.length <= 3</code></li>
<li><code>startCurrency<sub>i</sub></code> and <code>targetCurrency<sub>i</sub></code> consist only of uppercase English letters.</li>
<li><code>rates1.length == n</code></li>
<li><code>rates2.length == m</code></li>
<li><code>1.0 <= rates1[i], rates2[i] <= 10.0</code></li>
<li>The input is generated such that there are no contradictions or cycles in the conversion graphs for either day.</li>
<li>The input is generated such that the output is <strong>at most</strong> <code>5 * 10<sup>10</sup></code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Graph; Array; String
|
TypeScript
|
class Pair {
constructor(
public key: string,
public value: number,
) {}
}
function maxAmount(
initialCurrency: string,
pairs1: string[][],
rates1: number[],
pairs2: string[][],
rates2: number[],
): number {
const d1 = build(pairs1, rates1, initialCurrency);
const d2 = build(pairs2, rates2, initialCurrency);
let ans = 0;
for (const [currency, rate] of Object.entries(d2)) {
if (currency in d1) {
ans = Math.max(ans, d1[currency] / rate);
}
}
return ans;
}
function build(pairs: string[][], rates: number[], init: string): { [key: string]: number } {
const g: { [key: string]: Pair[] } = {};
const d: { [key: string]: number } = {};
for (let i = 0; i < pairs.length; ++i) {
const a = pairs[i][0];
const b = pairs[i][1];
const r = rates[i];
if (!g[a]) g[a] = [];
if (!g[b]) g[b] = [];
g[a].push(new Pair(b, r));
g[b].push(new Pair(a, 1 / r));
}
dfs(g, d, init, 1.0);
return d;
}
function dfs(
g: { [key: string]: Pair[] },
d: { [key: string]: number },
a: string,
v: number,
): void {
if (a in d) {
return;
}
d[a] = v;
for (const pair of g[a] || []) {
const b = pair.key;
const r = pair.value;
if (!(b in d)) {
dfs(g, d, b, v * r);
}
}
}
|
3,388 |
Count Beautiful Splits in an Array
|
Medium
|
<p>You are given an array <code>nums</code>.</p>
<p>A split of an array <code>nums</code> is <strong>beautiful</strong> if:</p>
<ol>
<li>The array <code>nums</code> is split into three <span data-keyword="subarray-nonempty">subarrays</span>: <code>nums1</code>, <code>nums2</code>, and <code>nums3</code>, such that <code>nums</code> can be formed by concatenating <code>nums1</code>, <code>nums2</code>, and <code>nums3</code> in that order.</li>
<li>The subarray <code>nums1</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums2</code> <strong>OR</strong> <code>nums2</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums3</code>.</li>
</ol>
<p>Return the <strong>number of ways</strong> you can make this split.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The beautiful splits are:</p>
<ol>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1,2]</code>, <code>nums3 = [1]</code>.</li>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1]</code>, <code>nums3 = [2,1]</code>.</li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 0 beautiful splits.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5000</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 50</font></code></li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
int beautifulSplits(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> lcp(n + 1, vector<int>(n + 1, 0));
for (int i = n - 1; i >= 0; i--) {
for (int j = n - 1; j > i; j--) {
if (nums[i] == nums[j]) {
lcp[i][j] = lcp[i + 1][j + 1] + 1;
}
}
}
int ans = 0;
for (int i = 1; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
bool a = (i <= j - i) && (lcp[0][i] >= i);
bool b = (j - i <= n - j) && (lcp[i][j] >= j - i);
if (a || b) {
ans++;
}
}
}
return ans;
}
};
|
3,388 |
Count Beautiful Splits in an Array
|
Medium
|
<p>You are given an array <code>nums</code>.</p>
<p>A split of an array <code>nums</code> is <strong>beautiful</strong> if:</p>
<ol>
<li>The array <code>nums</code> is split into three <span data-keyword="subarray-nonempty">subarrays</span>: <code>nums1</code>, <code>nums2</code>, and <code>nums3</code>, such that <code>nums</code> can be formed by concatenating <code>nums1</code>, <code>nums2</code>, and <code>nums3</code> in that order.</li>
<li>The subarray <code>nums1</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums2</code> <strong>OR</strong> <code>nums2</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums3</code>.</li>
</ol>
<p>Return the <strong>number of ways</strong> you can make this split.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The beautiful splits are:</p>
<ol>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1,2]</code>, <code>nums3 = [1]</code>.</li>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1]</code>, <code>nums3 = [2,1]</code>.</li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 0 beautiful splits.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5000</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 50</font></code></li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func beautifulSplits(nums []int) (ans int) {
n := len(nums)
lcp := make([][]int, n+1)
for i := range lcp {
lcp[i] = make([]int, n+1)
}
for i := n - 1; i >= 0; i-- {
for j := n - 1; j > i; j-- {
if nums[i] == nums[j] {
lcp[i][j] = lcp[i+1][j+1] + 1
}
}
}
for i := 1; i < n-1; i++ {
for j := i + 1; j < n; j++ {
a := i <= j-i && lcp[0][i] >= i
b := j-i <= n-j && lcp[i][j] >= j-i
if a || b {
ans++
}
}
}
return
}
|
3,388 |
Count Beautiful Splits in an Array
|
Medium
|
<p>You are given an array <code>nums</code>.</p>
<p>A split of an array <code>nums</code> is <strong>beautiful</strong> if:</p>
<ol>
<li>The array <code>nums</code> is split into three <span data-keyword="subarray-nonempty">subarrays</span>: <code>nums1</code>, <code>nums2</code>, and <code>nums3</code>, such that <code>nums</code> can be formed by concatenating <code>nums1</code>, <code>nums2</code>, and <code>nums3</code> in that order.</li>
<li>The subarray <code>nums1</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums2</code> <strong>OR</strong> <code>nums2</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums3</code>.</li>
</ol>
<p>Return the <strong>number of ways</strong> you can make this split.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The beautiful splits are:</p>
<ol>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1,2]</code>, <code>nums3 = [1]</code>.</li>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1]</code>, <code>nums3 = [2,1]</code>.</li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 0 beautiful splits.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5000</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 50</font></code></li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
public int beautifulSplits(int[] nums) {
int n = nums.length;
int[][] lcp = new int[n + 1][n + 1];
for (int i = n - 1; i >= 0; i--) {
for (int j = n - 1; j > i; j--) {
if (nums[i] == nums[j]) {
lcp[i][j] = lcp[i + 1][j + 1] + 1;
}
}
}
int ans = 0;
for (int i = 1; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
boolean a = (i <= j - i) && (lcp[0][i] >= i);
boolean b = (j - i <= n - j) && (lcp[i][j] >= j - i);
if (a || b) {
ans++;
}
}
}
return ans;
}
}
|
3,388 |
Count Beautiful Splits in an Array
|
Medium
|
<p>You are given an array <code>nums</code>.</p>
<p>A split of an array <code>nums</code> is <strong>beautiful</strong> if:</p>
<ol>
<li>The array <code>nums</code> is split into three <span data-keyword="subarray-nonempty">subarrays</span>: <code>nums1</code>, <code>nums2</code>, and <code>nums3</code>, such that <code>nums</code> can be formed by concatenating <code>nums1</code>, <code>nums2</code>, and <code>nums3</code> in that order.</li>
<li>The subarray <code>nums1</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums2</code> <strong>OR</strong> <code>nums2</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums3</code>.</li>
</ol>
<p>Return the <strong>number of ways</strong> you can make this split.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The beautiful splits are:</p>
<ol>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1,2]</code>, <code>nums3 = [1]</code>.</li>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1]</code>, <code>nums3 = [2,1]</code>.</li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 0 beautiful splits.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5000</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 50</font></code></li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def beautifulSplits(self, nums: List[int]) -> int:
n = len(nums)
lcp = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for j in range(n - 1, i - 1, -1):
if nums[i] == nums[j]:
lcp[i][j] = lcp[i + 1][j + 1] + 1
ans = 0
for i in range(1, n - 1):
for j in range(i + 1, n):
a = i <= j - i and lcp[0][i] >= i
b = j - i <= n - j and lcp[i][j] >= j - i
ans += int(a or b)
return ans
|
3,388 |
Count Beautiful Splits in an Array
|
Medium
|
<p>You are given an array <code>nums</code>.</p>
<p>A split of an array <code>nums</code> is <strong>beautiful</strong> if:</p>
<ol>
<li>The array <code>nums</code> is split into three <span data-keyword="subarray-nonempty">subarrays</span>: <code>nums1</code>, <code>nums2</code>, and <code>nums3</code>, such that <code>nums</code> can be formed by concatenating <code>nums1</code>, <code>nums2</code>, and <code>nums3</code> in that order.</li>
<li>The subarray <code>nums1</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums2</code> <strong>OR</strong> <code>nums2</code> is a <span data-keyword="array-prefix">prefix</span> of <code>nums3</code>.</li>
</ol>
<p>Return the <strong>number of ways</strong> you can make this split.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<p>The beautiful splits are:</p>
<ol>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1,2]</code>, <code>nums3 = [1]</code>.</li>
<li>A split with <code>nums1 = [1]</code>, <code>nums2 = [1]</code>, <code>nums3 = [2,1]</code>.</li>
</ol>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>There are 0 beautiful splits.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 5000</code></li>
<li><code><font face="monospace">0 <= nums[i] <= 50</font></code></li>
</ul>
|
Array; Dynamic Programming
|
TypeScript
|
function beautifulSplits(nums: number[]): number {
const n = nums.length;
const lcp: number[][] = Array.from({ length: n + 1 }, () => Array(n + 1).fill(0));
for (let i = n - 1; i >= 0; i--) {
for (let j = n - 1; j > i; j--) {
if (nums[i] === nums[j]) {
lcp[i][j] = lcp[i + 1][j + 1] + 1;
}
}
}
let ans = 0;
for (let i = 1; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
const a = i <= j - i && lcp[0][i] >= i;
const b = j - i <= n - j && lcp[i][j] >= j - i;
if (a || b) {
ans++;
}
}
}
return ans;
}
|
3,390 |
Longest Team Pass Streak
|
Hard
|
<p>Table: <code>Teams</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| player_id | int |
| team_name | varchar |
+-------------+---------+
player_id is the unique key for this table.
Each row contains the unique identifier for player and the name of one of the teams participating in that match.
</pre>
<p>Table: <code>Passes</code></p>
<pre>
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| pass_from | int |
| time_stamp | varchar |
| pass_to | int |
+-------------+---------+
(pass_from, time_stamp) is the unique key for this table.
pass_from is a foreign key to player_id from Teams table.
Each row represents a pass made during a match, time_stamp represents the time in minutes (00:00-90:00) when the pass was made,
pass_to is the player_id of the player receiving the pass.
</pre>
<p>Write a solution to find the <strong>longest successful pass streak</strong> for <strong>each team</strong> during the match. The rules are as follows:</p>
<ul>
<li>A successful pass streak is defined as consecutive passes where:
<ul>
<li>Both the <code>pass_from</code> and <code>pass_to</code> players belong to the same team</li>
</ul>
</li>
<li>A streak breaks when either:
<ul>
<li>The pass is intercepted (received by a player from the opposing team)</li>
</ul>
</li>
</ul>
<p>Return <em>the result table ordered by</em> <code>team_name</code> <em>in <strong>ascending</strong> order</em>.</p>
<p>The result format is in the following example.</p>
<p> </p>
<p><strong class="example">Example:</strong></p>
<div class="example-block">
<p><strong>Input:</strong></p>
<p>Teams table:</p>
<pre>
+-----------+-----------+
| player_id | team_name |
+-----------+-----------+
| 1 | Arsenal |
| 2 | Arsenal |
| 3 | Arsenal |
| 4 | Arsenal |
| 5 | Chelsea |
| 6 | Chelsea |
| 7 | Chelsea |
| 8 | Chelsea |
+-----------+-----------+
</pre>
<p>Passes table:</p>
<pre>
+-----------+------------+---------+
| pass_from | time_stamp | pass_to |
+-----------+------------+---------+
| 1 | 00:05 | 2 |
| 2 | 00:07 | 3 |
| 3 | 00:08 | 4 |
| 4 | 00:10 | 5 |
| 6 | 00:15 | 7 |
| 7 | 00:17 | 8 |
| 8 | 00:20 | 6 |
| 6 | 00:22 | 5 |
| 1 | 00:25 | 2 |
| 2 | 00:27 | 3 |
+-----------+------------+---------+
</pre>
<p><strong>Output:</strong></p>
<pre>
+-----------+----------------+
| team_name | longest_streak |
+-----------+----------------+
| Arsenal | 3 |
| Chelsea | 4 |
+-----------+----------------+
</pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><strong>Arsenal</strong>'s streaks:
<ul>
<li>First streak: 3 passes (1→2→3→4) ended when player 4 passed to Chelsea's player 5</li>
<li>Second streak: 2 passes (1→2→3)</li>
<li>Longest streak = 3</li>
</ul>
</li>
<li><strong>Chelsea</strong>'s streaks:
<ul>
<li>First streak: 3 passes (6→7→8→6→5)</li>
<li>Longest streak = 4</li>
</ul>
</li>
</ul>
</div>
|
Database
|
SQL
|
WITH
PassesWithTeams AS (
SELECT
p.pass_from,
p.pass_to,
t1.team_name AS team_from,
t2.team_name AS team_to,
IF(t1.team_name = t2.team_name, 1, 0) same_team_flag,
p.time_stamp
FROM
Passes p
JOIN Teams t1 ON p.pass_from = t1.player_id
JOIN Teams t2 ON p.pass_to = t2.player_id
),
StreakGroups AS (
SELECT
team_from AS team_name,
time_stamp,
same_team_flag,
SUM(
CASE
WHEN same_team_flag = 0 THEN 1
ELSE 0
END
) OVER (
PARTITION BY team_from
ORDER BY time_stamp
) AS group_id
FROM PassesWithTeams
),
StreakLengths AS (
SELECT
team_name,
group_id,
COUNT(*) AS streak_length
FROM StreakGroups
WHERE same_team_flag = 1
GROUP BY 1, 2
),
LongestStreaks AS (
SELECT
team_name,
MAX(streak_length) AS longest_streak
FROM StreakLengths
GROUP BY 1
)
SELECT
team_name,
longest_streak
FROM LongestStreaks
ORDER BY 1;
|
3,391 |
Design a 3D Binary Matrix with Efficient Layer Tracking
|
Medium
|
<p>You are given a <code>n x n x n</code> <strong>binary</strong> 3D array <code>matrix</code>.</p>
<p>Implement the <code>Matrix3D</code> class:</p>
<ul>
<li><code>Matrix3D(int n)</code> Initializes the object with the 3D binary array <code>matrix</code>, where <strong>all</strong> elements are initially set to 0.</li>
<li><code>void setCell(int x, int y, int z)</code> Sets the value at <code>matrix[x][y][z]</code> to 1.</li>
<li><code>void unsetCell(int x, int y, int z)</code> Sets the value at <code>matrix[x][y][z]</code> to 0.</li>
<li><code>int largestMatrix()</code> Returns the index <code>x</code> where <code>matrix[x]</code> contains the most number of 1's. If there are multiple such indices, return the <strong>largest</strong> <code>x</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["Matrix3D", "setCell", "largestMatrix", "setCell", "largestMatrix", "setCell", "largestMatrix"]<br />
[[3], [0, 0, 0], [], [1, 1, 2], [], [0, 0, 1], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, 0, null, 1, null, 0] </span></p>
<p><strong>Explanation</strong></p>
Matrix3D matrix3D = new Matrix3D(3); // Initializes a <code>3 x 3 x 3</code> 3D array <code>matrix</code>, filled with all 0's.<br />
matrix3D.setCell(0, 0, 0); // Sets <code>matrix[0][0][0]</code> to 1.<br />
matrix3D.largestMatrix(); // Returns 0. <code>matrix[0]</code> has the most number of 1's.<br />
matrix3D.setCell(1, 1, 2); // Sets <code>matrix[1][1][2]</code> to 1.<br />
matrix3D.largestMatrix(); // Returns 1. <code>matrix[0]</code> and <code>matrix[1]</code> tie with the most number of 1's, but index 1 is bigger.<br />
matrix3D.setCell(0, 0, 1); // Sets <code>matrix[0][0][1]</code> to 1.<br />
matrix3D.largestMatrix(); // Returns 0. <code>matrix[0]</code> has the most number of 1's.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["Matrix3D", "setCell", "largestMatrix", "unsetCell", "largestMatrix"]<br />
[[4], [2, 1, 1], [], [2, 1, 1], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, 2, null, 3] </span></p>
<p><strong>Explanation</strong></p>
Matrix3D matrix3D = new Matrix3D(4); // Initializes a <code>4 x 4 x 4</code> 3D array <code>matrix</code>, filled with all 0's.<br />
matrix3D.setCell(2, 1, 1); // Sets <code>matrix[2][1][1]</code> to 1.<br />
matrix3D.largestMatrix(); // Returns 2. <code>matrix[2]</code> has the most number of 1's.<br />
matrix3D.unsetCell(2, 1, 1); // Sets <code>matrix[2][1][1]</code> to 0.<br />
matrix3D.largestMatrix(); // Returns 3. All indices from 0 to 3 tie with the same number of 1's, but index 3 is the biggest.</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>0 <= x, y, z < n</code></li>
<li>At most <code>10<sup>5</sup></code> calls are made in total to <code>setCell</code> and <code>unsetCell</code>.</li>
<li>At most <code>10<sup>4</sup></code> calls are made to <code>largestMatrix</code>.</li>
</ul>
|
Design; Array; Hash Table; Matrix; Ordered Set; Heap (Priority Queue)
|
C++
|
class matrix3D {
private:
vector<vector<vector<int>>> g;
vector<int> cnt;
set<pair<int, int>> sl;
public:
matrix3D(int n) {
g.resize(n, vector<vector<int>>(n, vector<int>(n, 0)));
cnt.resize(n, 0);
}
void setCell(int x, int y, int z) {
if (g[x][y][z] == 1) {
return;
}
g[x][y][z] = 1;
sl.erase({-cnt[x], -x});
cnt[x]++;
sl.insert({-cnt[x], -x});
}
void unsetCell(int x, int y, int z) {
if (g[x][y][z] == 0) {
return;
}
g[x][y][z] = 0;
sl.erase({-cnt[x], -x});
cnt[x]--;
if (cnt[x]) {
sl.insert({-cnt[x], -x});
}
}
int largestMatrix() {
return sl.empty() ? g.size() - 1 : -sl.begin()->second;
}
};
/**
* Your matrix3D object will be instantiated and called as such:
* matrix3D* obj = new matrix3D(n);
* obj->setCell(x,y,z);
* obj->unsetCell(x,y,z);
* int param_3 = obj->largestMatrix();
*/
|
3,391 |
Design a 3D Binary Matrix with Efficient Layer Tracking
|
Medium
|
<p>You are given a <code>n x n x n</code> <strong>binary</strong> 3D array <code>matrix</code>.</p>
<p>Implement the <code>Matrix3D</code> class:</p>
<ul>
<li><code>Matrix3D(int n)</code> Initializes the object with the 3D binary array <code>matrix</code>, where <strong>all</strong> elements are initially set to 0.</li>
<li><code>void setCell(int x, int y, int z)</code> Sets the value at <code>matrix[x][y][z]</code> to 1.</li>
<li><code>void unsetCell(int x, int y, int z)</code> Sets the value at <code>matrix[x][y][z]</code> to 0.</li>
<li><code>int largestMatrix()</code> Returns the index <code>x</code> where <code>matrix[x]</code> contains the most number of 1's. If there are multiple such indices, return the <strong>largest</strong> <code>x</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["Matrix3D", "setCell", "largestMatrix", "setCell", "largestMatrix", "setCell", "largestMatrix"]<br />
[[3], [0, 0, 0], [], [1, 1, 2], [], [0, 0, 1], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, 0, null, 1, null, 0] </span></p>
<p><strong>Explanation</strong></p>
Matrix3D matrix3D = new Matrix3D(3); // Initializes a <code>3 x 3 x 3</code> 3D array <code>matrix</code>, filled with all 0's.<br />
matrix3D.setCell(0, 0, 0); // Sets <code>matrix[0][0][0]</code> to 1.<br />
matrix3D.largestMatrix(); // Returns 0. <code>matrix[0]</code> has the most number of 1's.<br />
matrix3D.setCell(1, 1, 2); // Sets <code>matrix[1][1][2]</code> to 1.<br />
matrix3D.largestMatrix(); // Returns 1. <code>matrix[0]</code> and <code>matrix[1]</code> tie with the most number of 1's, but index 1 is bigger.<br />
matrix3D.setCell(0, 0, 1); // Sets <code>matrix[0][0][1]</code> to 1.<br />
matrix3D.largestMatrix(); // Returns 0. <code>matrix[0]</code> has the most number of 1's.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["Matrix3D", "setCell", "largestMatrix", "unsetCell", "largestMatrix"]<br />
[[4], [2, 1, 1], [], [2, 1, 1], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, 2, null, 3] </span></p>
<p><strong>Explanation</strong></p>
Matrix3D matrix3D = new Matrix3D(4); // Initializes a <code>4 x 4 x 4</code> 3D array <code>matrix</code>, filled with all 0's.<br />
matrix3D.setCell(2, 1, 1); // Sets <code>matrix[2][1][1]</code> to 1.<br />
matrix3D.largestMatrix(); // Returns 2. <code>matrix[2]</code> has the most number of 1's.<br />
matrix3D.unsetCell(2, 1, 1); // Sets <code>matrix[2][1][1]</code> to 0.<br />
matrix3D.largestMatrix(); // Returns 3. All indices from 0 to 3 tie with the same number of 1's, but index 3 is the biggest.</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>0 <= x, y, z < n</code></li>
<li>At most <code>10<sup>5</sup></code> calls are made in total to <code>setCell</code> and <code>unsetCell</code>.</li>
<li>At most <code>10<sup>4</sup></code> calls are made to <code>largestMatrix</code>.</li>
</ul>
|
Design; Array; Hash Table; Matrix; Ordered Set; Heap (Priority Queue)
|
Java
|
class matrix3D {
private final int[][][] g;
private final int[] cnt;
private final TreeSet<int[]> sl
= new TreeSet<>((a, b) -> a[0] == b[0] ? b[1] - a[1] : b[0] - a[0]);
public matrix3D(int n) {
g = new int[n][n][n];
cnt = new int[n];
}
public void setCell(int x, int y, int z) {
if (g[x][y][z] == 1) {
return;
}
g[x][y][z] = 1;
sl.remove(new int[] {cnt[x], x});
cnt[x]++;
sl.add(new int[] {cnt[x], x});
}
public void unsetCell(int x, int y, int z) {
if (g[x][y][z] == 0) {
return;
}
g[x][y][z] = 0;
sl.remove(new int[] {cnt[x], x});
cnt[x]--;
if (cnt[x] > 0) {
sl.add(new int[] {cnt[x], x});
}
}
public int largestMatrix() {
return sl.isEmpty() ? g.length - 1 : sl.first()[1];
}
}
/**
* Your matrix3D object will be instantiated and called as such:
* matrix3D obj = new matrix3D(n);
* obj.setCell(x,y,z);
* obj.unsetCell(x,y,z);
* int param_3 = obj.largestMatrix();
*/
|
3,391 |
Design a 3D Binary Matrix with Efficient Layer Tracking
|
Medium
|
<p>You are given a <code>n x n x n</code> <strong>binary</strong> 3D array <code>matrix</code>.</p>
<p>Implement the <code>Matrix3D</code> class:</p>
<ul>
<li><code>Matrix3D(int n)</code> Initializes the object with the 3D binary array <code>matrix</code>, where <strong>all</strong> elements are initially set to 0.</li>
<li><code>void setCell(int x, int y, int z)</code> Sets the value at <code>matrix[x][y][z]</code> to 1.</li>
<li><code>void unsetCell(int x, int y, int z)</code> Sets the value at <code>matrix[x][y][z]</code> to 0.</li>
<li><code>int largestMatrix()</code> Returns the index <code>x</code> where <code>matrix[x]</code> contains the most number of 1's. If there are multiple such indices, return the <strong>largest</strong> <code>x</code>.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["Matrix3D", "setCell", "largestMatrix", "setCell", "largestMatrix", "setCell", "largestMatrix"]<br />
[[3], [0, 0, 0], [], [1, 1, 2], [], [0, 0, 1], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, 0, null, 1, null, 0] </span></p>
<p><strong>Explanation</strong></p>
Matrix3D matrix3D = new Matrix3D(3); // Initializes a <code>3 x 3 x 3</code> 3D array <code>matrix</code>, filled with all 0's.<br />
matrix3D.setCell(0, 0, 0); // Sets <code>matrix[0][0][0]</code> to 1.<br />
matrix3D.largestMatrix(); // Returns 0. <code>matrix[0]</code> has the most number of 1's.<br />
matrix3D.setCell(1, 1, 2); // Sets <code>matrix[1][1][2]</code> to 1.<br />
matrix3D.largestMatrix(); // Returns 1. <code>matrix[0]</code> and <code>matrix[1]</code> tie with the most number of 1's, but index 1 is bigger.<br />
matrix3D.setCell(0, 0, 1); // Sets <code>matrix[0][0][1]</code> to 1.<br />
matrix3D.largestMatrix(); // Returns 0. <code>matrix[0]</code> has the most number of 1's.</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["Matrix3D", "setCell", "largestMatrix", "unsetCell", "largestMatrix"]<br />
[[4], [2, 1, 1], [], [2, 1, 1], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, 2, null, 3] </span></p>
<p><strong>Explanation</strong></p>
Matrix3D matrix3D = new Matrix3D(4); // Initializes a <code>4 x 4 x 4</code> 3D array <code>matrix</code>, filled with all 0's.<br />
matrix3D.setCell(2, 1, 1); // Sets <code>matrix[2][1][1]</code> to 1.<br />
matrix3D.largestMatrix(); // Returns 2. <code>matrix[2]</code> has the most number of 1's.<br />
matrix3D.unsetCell(2, 1, 1); // Sets <code>matrix[2][1][1]</code> to 0.<br />
matrix3D.largestMatrix(); // Returns 3. All indices from 0 to 3 tie with the same number of 1's, but index 3 is the biggest.</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 100</code></li>
<li><code>0 <= x, y, z < n</code></li>
<li>At most <code>10<sup>5</sup></code> calls are made in total to <code>setCell</code> and <code>unsetCell</code>.</li>
<li>At most <code>10<sup>4</sup></code> calls are made to <code>largestMatrix</code>.</li>
</ul>
|
Design; Array; Hash Table; Matrix; Ordered Set; Heap (Priority Queue)
|
Python
|
class matrix3D:
def __init__(self, n: int):
self.g = [[[0] * n for _ in range(n)] for _ in range(n)]
self.cnt = [0] * n
self.sl = SortedList(key=lambda x: (-x[0], -x[1]))
def setCell(self, x: int, y: int, z: int) -> None:
if self.g[x][y][z]:
return
self.g[x][y][z] = 1
self.sl.discard((self.cnt[x], x))
self.cnt[x] += 1
self.sl.add((self.cnt[x], x))
def unsetCell(self, x: int, y: int, z: int) -> None:
if self.g[x][y][z] == 0:
return
self.g[x][y][z] = 0
self.sl.discard((self.cnt[x], x))
self.cnt[x] -= 1
if self.cnt[x]:
self.sl.add((self.cnt[x], x))
def largestMatrix(self) -> int:
return self.sl[0][1] if self.sl else len(self.g) - 1
# Your matrix3D object will be instantiated and called as such:
# obj = matrix3D(n)
# obj.setCell(x,y,z)
# obj.unsetCell(x,y,z)
# param_3 = obj.largestMatrix()
|
3,392 |
Count Subarrays of Length Three With a Condition
|
Easy
|
<p>Given an integer array <code>nums</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of length 3 such that the sum of the first and third numbers equals <em>exactly</em> half of the second number.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Only the subarray <code>[1,4,1]</code> contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>[1,1,1]</code> is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 100</code></li>
<li><code><font face="monospace">-100 <= nums[i] <= 100</font></code></li>
</ul>
|
Array
|
C++
|
class Solution {
public:
int countSubarrays(vector<int>& nums) {
int ans = 0;
for (int i = 1; i + 1 < nums.size(); ++i) {
if ((nums[i - 1] + nums[i + 1]) * 2 == nums[i]) {
++ans;
}
}
return ans;
}
};
|
3,392 |
Count Subarrays of Length Three With a Condition
|
Easy
|
<p>Given an integer array <code>nums</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of length 3 such that the sum of the first and third numbers equals <em>exactly</em> half of the second number.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Only the subarray <code>[1,4,1]</code> contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>[1,1,1]</code> is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 100</code></li>
<li><code><font face="monospace">-100 <= nums[i] <= 100</font></code></li>
</ul>
|
Array
|
Go
|
func countSubarrays(nums []int) (ans int) {
for i := 1; i+1 < len(nums); i++ {
if (nums[i-1]+nums[i+1])*2 == nums[i] {
ans++
}
}
return
}
|
3,392 |
Count Subarrays of Length Three With a Condition
|
Easy
|
<p>Given an integer array <code>nums</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of length 3 such that the sum of the first and third numbers equals <em>exactly</em> half of the second number.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Only the subarray <code>[1,4,1]</code> contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>[1,1,1]</code> is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 100</code></li>
<li><code><font face="monospace">-100 <= nums[i] <= 100</font></code></li>
</ul>
|
Array
|
Java
|
class Solution {
public int countSubarrays(int[] nums) {
int ans = 0;
for (int i = 1; i + 1 < nums.length; ++i) {
if ((nums[i - 1] + nums[i + 1]) * 2 == nums[i]) {
++ans;
}
}
return ans;
}
}
|
3,392 |
Count Subarrays of Length Three With a Condition
|
Easy
|
<p>Given an integer array <code>nums</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of length 3 such that the sum of the first and third numbers equals <em>exactly</em> half of the second number.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Only the subarray <code>[1,4,1]</code> contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>[1,1,1]</code> is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 100</code></li>
<li><code><font face="monospace">-100 <= nums[i] <= 100</font></code></li>
</ul>
|
Array
|
Python
|
class Solution:
def countSubarrays(self, nums: List[int]) -> int:
return sum(
(nums[i - 1] + nums[i + 1]) * 2 == nums[i] for i in range(1, len(nums) - 1)
)
|
3,392 |
Count Subarrays of Length Three With a Condition
|
Easy
|
<p>Given an integer array <code>nums</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of length 3 such that the sum of the first and third numbers equals <em>exactly</em> half of the second number.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Only the subarray <code>[1,4,1]</code> contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>[1,1,1]</code> is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 100</code></li>
<li><code><font face="monospace">-100 <= nums[i] <= 100</font></code></li>
</ul>
|
Array
|
Rust
|
impl Solution {
pub fn count_subarrays(nums: Vec<i32>) -> i32 {
let mut ans = 0;
for i in 1..nums.len() - 1 {
if (nums[i - 1] + nums[i + 1]) * 2 == nums[i] {
ans += 1;
}
}
ans
}
}
|
3,392 |
Count Subarrays of Length Three With a Condition
|
Easy
|
<p>Given an integer array <code>nums</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of length 3 such that the sum of the first and third numbers equals <em>exactly</em> half of the second number.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,4,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>Only the subarray <code>[1,4,1]</code> contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p><code>[1,1,1]</code> is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= nums.length <= 100</code></li>
<li><code><font face="monospace">-100 <= nums[i] <= 100</font></code></li>
</ul>
|
Array
|
TypeScript
|
function countSubarrays(nums: number[]): number {
let ans: number = 0;
for (let i = 1; i + 1 < nums.length; ++i) {
if ((nums[i - 1] + nums[i + 1]) * 2 === nums[i]) {
++ans;
}
}
return ans;
}
|
3,394 |
Check if Grid can be Cut into Sections
|
Medium
|
<p>You are given an integer <code>n</code> representing the dimensions of an <code>n x n</code><!-- notionvc: fa9fe4ed-dff8-4410-8196-346f2d430795 --> grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates <code>rectangles</code>, where <code>rectangles[i]</code> is in the form <code>[start<sub>x</sub>, start<sub>y</sub>, end<sub>x</sub>, end<sub>y</sub>]</code>, representing a rectangle on the grid. Each rectangle is defined as follows:</p>
<ul>
<li><code>(start<sub>x</sub>, start<sub>y</sub>)</code>: The bottom-left corner of the rectangle.</li>
<li><code>(end<sub>x</sub>, end<sub>y</sub>)</code>: The top-right corner of the rectangle.</li>
</ul>
<p><strong>Note </strong>that the rectangles do not overlap. Your task is to determine if it is possible to make <strong>either two horizontal or two vertical cuts</strong> on the grid such that:</p>
<ul>
<li>Each of the three resulting sections formed by the cuts contains <strong>at least</strong> one rectangle.</li>
<li>Every rectangle belongs to <strong>exactly</strong> one section.</li>
</ul>
<p>Return <code>true</code> if such cuts can be made; otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tt1drawio.png" style="width: 285px; height: 280px;" /></p>
<p>The grid is shown in the diagram. We can make horizontal cuts at <code>y = 2</code> and <code>y = 4</code>. Hence, output is true.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tc2drawio.png" style="width: 240px; height: 240px;" /></p>
<p>We can make vertical cuts at <code>x = 2</code> and <code>x = 3</code>. Hence, output is true.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>We cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 10<sup>9</sup></code></li>
<li><code>3 <= rectangles.length <= 10<sup>5</sup></code></li>
<li><code>0 <= rectangles[i][0] < rectangles[i][2] <= n</code></li>
<li><code>0 <= rectangles[i][1] < rectangles[i][3] <= n</code></li>
<li>No two rectangles overlap.</li>
</ul>
|
Array; Sorting
|
C++
|
class Solution {
#define pii pair<int, int>
bool countLineIntersections(vector<pii>& coordinates) {
int lines = 0;
int overlap = 0;
for (int i = 0; i < coordinates.size(); ++i) {
if (coordinates[i].second == 0)
overlap--;
else
overlap++;
if (overlap == 0)
lines++;
}
return lines >= 3;
}
public:
bool checkValidCuts(int n, vector<vector<int>>& rectangles) {
vector<pii> y_cordinates, x_cordinates;
for (auto& rectangle : rectangles) {
y_cordinates.push_back(make_pair(rectangle[1], 1));
y_cordinates.push_back(make_pair(rectangle[3], 0));
x_cordinates.push_back(make_pair(rectangle[0], 1));
x_cordinates.push_back(make_pair(rectangle[2], 0));
}
sort(y_cordinates.begin(), y_cordinates.end());
sort(x_cordinates.begin(), x_cordinates.end());
// Line-Sweep on x and y cordinates
return (countLineIntersections(y_cordinates) or countLineIntersections(x_cordinates));
}
};
|
3,394 |
Check if Grid can be Cut into Sections
|
Medium
|
<p>You are given an integer <code>n</code> representing the dimensions of an <code>n x n</code><!-- notionvc: fa9fe4ed-dff8-4410-8196-346f2d430795 --> grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates <code>rectangles</code>, where <code>rectangles[i]</code> is in the form <code>[start<sub>x</sub>, start<sub>y</sub>, end<sub>x</sub>, end<sub>y</sub>]</code>, representing a rectangle on the grid. Each rectangle is defined as follows:</p>
<ul>
<li><code>(start<sub>x</sub>, start<sub>y</sub>)</code>: The bottom-left corner of the rectangle.</li>
<li><code>(end<sub>x</sub>, end<sub>y</sub>)</code>: The top-right corner of the rectangle.</li>
</ul>
<p><strong>Note </strong>that the rectangles do not overlap. Your task is to determine if it is possible to make <strong>either two horizontal or two vertical cuts</strong> on the grid such that:</p>
<ul>
<li>Each of the three resulting sections formed by the cuts contains <strong>at least</strong> one rectangle.</li>
<li>Every rectangle belongs to <strong>exactly</strong> one section.</li>
</ul>
<p>Return <code>true</code> if such cuts can be made; otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tt1drawio.png" style="width: 285px; height: 280px;" /></p>
<p>The grid is shown in the diagram. We can make horizontal cuts at <code>y = 2</code> and <code>y = 4</code>. Hence, output is true.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tc2drawio.png" style="width: 240px; height: 240px;" /></p>
<p>We can make vertical cuts at <code>x = 2</code> and <code>x = 3</code>. Hence, output is true.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>We cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 10<sup>9</sup></code></li>
<li><code>3 <= rectangles.length <= 10<sup>5</sup></code></li>
<li><code>0 <= rectangles[i][0] < rectangles[i][2] <= n</code></li>
<li><code>0 <= rectangles[i][1] < rectangles[i][3] <= n</code></li>
<li>No two rectangles overlap.</li>
</ul>
|
Array; Sorting
|
Go
|
type Pair struct {
val int
typ int // 1 = start, 0 = end
}
func countLineIntersections(coords []Pair) bool {
lines := 0
overlap := 0
for _, p := range coords {
if p.typ == 0 {
overlap--
} else {
overlap++
}
if overlap == 0 {
lines++
}
}
return lines >= 3
}
func checkValidCuts(n int, rectangles [][]int) bool {
var xCoords []Pair
var yCoords []Pair
for _, rect := range rectangles {
x1, y1, x2, y2 := rect[0], rect[1], rect[2], rect[3]
yCoords = append(yCoords, Pair{y1, 1}) // start
yCoords = append(yCoords, Pair{y2, 0}) // end
xCoords = append(xCoords, Pair{x1, 1})
xCoords = append(xCoords, Pair{x2, 0})
}
sort.Slice(yCoords, func(i, j int) bool {
if yCoords[i].val == yCoords[j].val {
return yCoords[i].typ < yCoords[j].typ // end before start
}
return yCoords[i].val < yCoords[j].val
})
sort.Slice(xCoords, func(i, j int) bool {
if xCoords[i].val == xCoords[j].val {
return xCoords[i].typ < xCoords[j].typ
}
return xCoords[i].val < xCoords[j].val
})
return countLineIntersections(yCoords) || countLineIntersections(xCoords)
}
|
3,394 |
Check if Grid can be Cut into Sections
|
Medium
|
<p>You are given an integer <code>n</code> representing the dimensions of an <code>n x n</code><!-- notionvc: fa9fe4ed-dff8-4410-8196-346f2d430795 --> grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates <code>rectangles</code>, where <code>rectangles[i]</code> is in the form <code>[start<sub>x</sub>, start<sub>y</sub>, end<sub>x</sub>, end<sub>y</sub>]</code>, representing a rectangle on the grid. Each rectangle is defined as follows:</p>
<ul>
<li><code>(start<sub>x</sub>, start<sub>y</sub>)</code>: The bottom-left corner of the rectangle.</li>
<li><code>(end<sub>x</sub>, end<sub>y</sub>)</code>: The top-right corner of the rectangle.</li>
</ul>
<p><strong>Note </strong>that the rectangles do not overlap. Your task is to determine if it is possible to make <strong>either two horizontal or two vertical cuts</strong> on the grid such that:</p>
<ul>
<li>Each of the three resulting sections formed by the cuts contains <strong>at least</strong> one rectangle.</li>
<li>Every rectangle belongs to <strong>exactly</strong> one section.</li>
</ul>
<p>Return <code>true</code> if such cuts can be made; otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tt1drawio.png" style="width: 285px; height: 280px;" /></p>
<p>The grid is shown in the diagram. We can make horizontal cuts at <code>y = 2</code> and <code>y = 4</code>. Hence, output is true.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tc2drawio.png" style="width: 240px; height: 240px;" /></p>
<p>We can make vertical cuts at <code>x = 2</code> and <code>x = 3</code>. Hence, output is true.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>We cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 10<sup>9</sup></code></li>
<li><code>3 <= rectangles.length <= 10<sup>5</sup></code></li>
<li><code>0 <= rectangles[i][0] < rectangles[i][2] <= n</code></li>
<li><code>0 <= rectangles[i][1] < rectangles[i][3] <= n</code></li>
<li>No two rectangles overlap.</li>
</ul>
|
Array; Sorting
|
Java
|
class Solution {
// Helper class to mimic C++ pair<int, int>
static class Pair {
int value;
int type;
Pair(int value, int type) {
this.value = value;
this.type = type;
}
}
private boolean countLineIntersections(List<Pair> coordinates) {
int lines = 0;
int overlap = 0;
for (Pair coord : coordinates) {
if (coord.type == 0) {
overlap--;
} else {
overlap++;
}
if (overlap == 0) {
lines++;
}
}
return lines >= 3;
}
public boolean checkValidCuts(int n, int[][] rectangles) {
List<Pair> yCoordinates = new ArrayList<>();
List<Pair> xCoordinates = new ArrayList<>();
for (int[] rectangle : rectangles) {
// rectangle = [x1, y1, x2, y2]
yCoordinates.add(new Pair(rectangle[1], 1)); // y1, start
yCoordinates.add(new Pair(rectangle[3], 0)); // y2, end
xCoordinates.add(new Pair(rectangle[0], 1)); // x1, start
xCoordinates.add(new Pair(rectangle[2], 0)); // x2, end
}
Comparator<Pair> comparator = (a, b) -> {
if (a.value != b.value) return Integer.compare(a.value, b.value);
return Integer.compare(a.type, b.type); // End (0) before Start (1)
};
Collections.sort(yCoordinates, comparator);
Collections.sort(xCoordinates, comparator);
return countLineIntersections(yCoordinates) || countLineIntersections(xCoordinates);
}
}
|
3,394 |
Check if Grid can be Cut into Sections
|
Medium
|
<p>You are given an integer <code>n</code> representing the dimensions of an <code>n x n</code><!-- notionvc: fa9fe4ed-dff8-4410-8196-346f2d430795 --> grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates <code>rectangles</code>, where <code>rectangles[i]</code> is in the form <code>[start<sub>x</sub>, start<sub>y</sub>, end<sub>x</sub>, end<sub>y</sub>]</code>, representing a rectangle on the grid. Each rectangle is defined as follows:</p>
<ul>
<li><code>(start<sub>x</sub>, start<sub>y</sub>)</code>: The bottom-left corner of the rectangle.</li>
<li><code>(end<sub>x</sub>, end<sub>y</sub>)</code>: The top-right corner of the rectangle.</li>
</ul>
<p><strong>Note </strong>that the rectangles do not overlap. Your task is to determine if it is possible to make <strong>either two horizontal or two vertical cuts</strong> on the grid such that:</p>
<ul>
<li>Each of the three resulting sections formed by the cuts contains <strong>at least</strong> one rectangle.</li>
<li>Every rectangle belongs to <strong>exactly</strong> one section.</li>
</ul>
<p>Return <code>true</code> if such cuts can be made; otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tt1drawio.png" style="width: 285px; height: 280px;" /></p>
<p>The grid is shown in the diagram. We can make horizontal cuts at <code>y = 2</code> and <code>y = 4</code>. Hence, output is true.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tc2drawio.png" style="width: 240px; height: 240px;" /></p>
<p>We can make vertical cuts at <code>x = 2</code> and <code>x = 3</code>. Hence, output is true.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>We cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 10<sup>9</sup></code></li>
<li><code>3 <= rectangles.length <= 10<sup>5</sup></code></li>
<li><code>0 <= rectangles[i][0] < rectangles[i][2] <= n</code></li>
<li><code>0 <= rectangles[i][1] < rectangles[i][3] <= n</code></li>
<li>No two rectangles overlap.</li>
</ul>
|
Array; Sorting
|
JavaScript
|
function checkValidCuts(n, rectangles) {
const check = (arr, getVals) => {
let [c, longest] = [3, 0];
for (const x of arr) {
const [start, end] = getVals(x);
if (start < longest) {
longest = Math.max(longest, end);
} else {
longest = end;
if (--c === 0) return true;
}
}
return false;
};
const sortByX = ([a], [b]) => a - b;
const sortByY = ([, a], [, b]) => a - b;
const getX = ([x1, , x2]) => [x1, x2];
const getY = ([, y1, , y2]) => [y1, y2];
return check(rectangles.toSorted(sortByX), getX) || check(rectangles.toSorted(sortByY), getY);
}
|
3,394 |
Check if Grid can be Cut into Sections
|
Medium
|
<p>You are given an integer <code>n</code> representing the dimensions of an <code>n x n</code><!-- notionvc: fa9fe4ed-dff8-4410-8196-346f2d430795 --> grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates <code>rectangles</code>, where <code>rectangles[i]</code> is in the form <code>[start<sub>x</sub>, start<sub>y</sub>, end<sub>x</sub>, end<sub>y</sub>]</code>, representing a rectangle on the grid. Each rectangle is defined as follows:</p>
<ul>
<li><code>(start<sub>x</sub>, start<sub>y</sub>)</code>: The bottom-left corner of the rectangle.</li>
<li><code>(end<sub>x</sub>, end<sub>y</sub>)</code>: The top-right corner of the rectangle.</li>
</ul>
<p><strong>Note </strong>that the rectangles do not overlap. Your task is to determine if it is possible to make <strong>either two horizontal or two vertical cuts</strong> on the grid such that:</p>
<ul>
<li>Each of the three resulting sections formed by the cuts contains <strong>at least</strong> one rectangle.</li>
<li>Every rectangle belongs to <strong>exactly</strong> one section.</li>
</ul>
<p>Return <code>true</code> if such cuts can be made; otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tt1drawio.png" style="width: 285px; height: 280px;" /></p>
<p>The grid is shown in the diagram. We can make horizontal cuts at <code>y = 2</code> and <code>y = 4</code>. Hence, output is true.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tc2drawio.png" style="width: 240px; height: 240px;" /></p>
<p>We can make vertical cuts at <code>x = 2</code> and <code>x = 3</code>. Hence, output is true.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>We cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 10<sup>9</sup></code></li>
<li><code>3 <= rectangles.length <= 10<sup>5</sup></code></li>
<li><code>0 <= rectangles[i][0] < rectangles[i][2] <= n</code></li>
<li><code>0 <= rectangles[i][1] < rectangles[i][3] <= n</code></li>
<li>No two rectangles overlap.</li>
</ul>
|
Array; Sorting
|
Python
|
class Solution:
def countLineIntersections(self, coordinates: List[tuple[int, int]]) -> bool:
lines = 0
overlap = 0
for value, marker in coordinates:
if marker == 0:
overlap -= 1
else:
overlap += 1
if overlap == 0:
lines += 1
return lines >= 3
def checkValidCuts(self, n: int, rectangles: List[List[int]]) -> bool:
y_coordinates = []
x_coordinates = []
for rect in rectangles:
x1, y1, x2, y2 = rect
y_coordinates.append((y1, 1)) # start
y_coordinates.append((y2, 0)) # end
x_coordinates.append((x1, 1)) # start
x_coordinates.append((x2, 0)) # end
# Sort by coordinate value, and for tie, put end (0) before start (1)
y_coordinates.sort(key=lambda x: (x[0], x[1]))
x_coordinates.sort(key=lambda x: (x[0], x[1]))
return self.countLineIntersections(
y_coordinates
) or self.countLineIntersections(x_coordinates)
|
3,394 |
Check if Grid can be Cut into Sections
|
Medium
|
<p>You are given an integer <code>n</code> representing the dimensions of an <code>n x n</code><!-- notionvc: fa9fe4ed-dff8-4410-8196-346f2d430795 --> grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates <code>rectangles</code>, where <code>rectangles[i]</code> is in the form <code>[start<sub>x</sub>, start<sub>y</sub>, end<sub>x</sub>, end<sub>y</sub>]</code>, representing a rectangle on the grid. Each rectangle is defined as follows:</p>
<ul>
<li><code>(start<sub>x</sub>, start<sub>y</sub>)</code>: The bottom-left corner of the rectangle.</li>
<li><code>(end<sub>x</sub>, end<sub>y</sub>)</code>: The top-right corner of the rectangle.</li>
</ul>
<p><strong>Note </strong>that the rectangles do not overlap. Your task is to determine if it is possible to make <strong>either two horizontal or two vertical cuts</strong> on the grid such that:</p>
<ul>
<li>Each of the three resulting sections formed by the cuts contains <strong>at least</strong> one rectangle.</li>
<li>Every rectangle belongs to <strong>exactly</strong> one section.</li>
</ul>
<p>Return <code>true</code> if such cuts can be made; otherwise, return <code>false</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tt1drawio.png" style="width: 285px; height: 280px;" /></p>
<p>The grid is shown in the diagram. We can make horizontal cuts at <code>y = 2</code> and <code>y = 4</code>. Hence, output is true.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tc2drawio.png" style="width: 240px; height: 240px;" /></p>
<p>We can make vertical cuts at <code>x = 2</code> and <code>x = 3</code>. Hence, output is true.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>We cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= n <= 10<sup>9</sup></code></li>
<li><code>3 <= rectangles.length <= 10<sup>5</sup></code></li>
<li><code>0 <= rectangles[i][0] < rectangles[i][2] <= n</code></li>
<li><code>0 <= rectangles[i][1] < rectangles[i][3] <= n</code></li>
<li>No two rectangles overlap.</li>
</ul>
|
Array; Sorting
|
TypeScript
|
function checkValidCuts(n: number, rectangles: number[][]): boolean {
const check = (arr: number[][], getVals: (x: number[]) => number[]) => {
let [c, longest] = [3, 0];
for (const x of arr) {
const [start, end] = getVals(x);
if (start < longest) {
longest = Math.max(longest, end);
} else {
longest = end;
if (--c === 0) return true;
}
}
return false;
};
const sortByX = ([a]: number[], [b]: number[]) => a - b;
const sortByY = ([, a]: number[], [, b]: number[]) => a - b;
const getX = ([x1, , x2]: number[]) => [x1, x2];
const getY = ([, y1, , y2]: number[]) => [y1, y2];
return check(rectangles.toSorted(sortByX), getX) || check(rectangles.toSorted(sortByY), getY);
}
|
3,396 |
Minimum Number of Operations to Make Elements in Array Distinct
|
Easy
|
<p>You are given an integer array <code>nums</code>. You need to ensure that the elements in the array are <strong>distinct</strong>. To achieve this, you can perform the following operation any number of times:</p>
<ul>
<li>Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, remove all remaining elements.</li>
</ul>
<p><strong>Note</strong> that an empty array is considered to have distinct elements. Return the <strong>minimum</strong> number of operations needed to make the elements in the array distinct.<!-- notionvc: 210ee4f2-90af-4cdf-8dbc-96d1fa8f67c7 --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,2,3,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 2, 3, 3, 5, 7]</code>.</li>
<li>In the second operation, the next 3 elements are removed, resulting in the array <code>[3, 5, 7]</code>, which has distinct elements.</li>
</ul>
<p>Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,4,4]</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 4]</code>.</li>
<li>In the second operation, all remaining elements are removed, resulting in an empty array.</li>
</ul>
<p>Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [6,7,8,9]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The array already contains distinct elements. Therefore, the answer is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table
|
C++
|
class Solution {
public:
int minimumOperations(vector<int>& nums) {
unordered_set<int> s;
for (int i = nums.size() - 1; ~i; --i) {
if (s.contains(nums[i])) {
return i / 3 + 1;
}
s.insert(nums[i]);
}
return 0;
}
};
|
3,396 |
Minimum Number of Operations to Make Elements in Array Distinct
|
Easy
|
<p>You are given an integer array <code>nums</code>. You need to ensure that the elements in the array are <strong>distinct</strong>. To achieve this, you can perform the following operation any number of times:</p>
<ul>
<li>Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, remove all remaining elements.</li>
</ul>
<p><strong>Note</strong> that an empty array is considered to have distinct elements. Return the <strong>minimum</strong> number of operations needed to make the elements in the array distinct.<!-- notionvc: 210ee4f2-90af-4cdf-8dbc-96d1fa8f67c7 --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,2,3,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 2, 3, 3, 5, 7]</code>.</li>
<li>In the second operation, the next 3 elements are removed, resulting in the array <code>[3, 5, 7]</code>, which has distinct elements.</li>
</ul>
<p>Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,4,4]</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 4]</code>.</li>
<li>In the second operation, all remaining elements are removed, resulting in an empty array.</li>
</ul>
<p>Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [6,7,8,9]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The array already contains distinct elements. Therefore, the answer is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table
|
Go
|
func minimumOperations(nums []int) int {
s := map[int]bool{}
for i := len(nums) - 1; i >= 0; i-- {
if s[nums[i]] {
return i/3 + 1
}
s[nums[i]] = true
}
return 0
}
|
3,396 |
Minimum Number of Operations to Make Elements in Array Distinct
|
Easy
|
<p>You are given an integer array <code>nums</code>. You need to ensure that the elements in the array are <strong>distinct</strong>. To achieve this, you can perform the following operation any number of times:</p>
<ul>
<li>Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, remove all remaining elements.</li>
</ul>
<p><strong>Note</strong> that an empty array is considered to have distinct elements. Return the <strong>minimum</strong> number of operations needed to make the elements in the array distinct.<!-- notionvc: 210ee4f2-90af-4cdf-8dbc-96d1fa8f67c7 --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,2,3,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 2, 3, 3, 5, 7]</code>.</li>
<li>In the second operation, the next 3 elements are removed, resulting in the array <code>[3, 5, 7]</code>, which has distinct elements.</li>
</ul>
<p>Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,4,4]</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 4]</code>.</li>
<li>In the second operation, all remaining elements are removed, resulting in an empty array.</li>
</ul>
<p>Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [6,7,8,9]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The array already contains distinct elements. Therefore, the answer is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table
|
Java
|
class Solution {
public int minimumOperations(int[] nums) {
Set<Integer> s = new HashSet<>();
for (int i = nums.length - 1; i >= 0; --i) {
if (!s.add(nums[i])) {
return i / 3 + 1;
}
}
return 0;
}
}
|
3,396 |
Minimum Number of Operations to Make Elements in Array Distinct
|
Easy
|
<p>You are given an integer array <code>nums</code>. You need to ensure that the elements in the array are <strong>distinct</strong>. To achieve this, you can perform the following operation any number of times:</p>
<ul>
<li>Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, remove all remaining elements.</li>
</ul>
<p><strong>Note</strong> that an empty array is considered to have distinct elements. Return the <strong>minimum</strong> number of operations needed to make the elements in the array distinct.<!-- notionvc: 210ee4f2-90af-4cdf-8dbc-96d1fa8f67c7 --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,2,3,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 2, 3, 3, 5, 7]</code>.</li>
<li>In the second operation, the next 3 elements are removed, resulting in the array <code>[3, 5, 7]</code>, which has distinct elements.</li>
</ul>
<p>Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,4,4]</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 4]</code>.</li>
<li>In the second operation, all remaining elements are removed, resulting in an empty array.</li>
</ul>
<p>Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [6,7,8,9]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The array already contains distinct elements. Therefore, the answer is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table
|
Python
|
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
s = set()
for i in range(len(nums) - 1, -1, -1):
if nums[i] in s:
return i // 3 + 1
s.add(nums[i])
return 0
|
3,396 |
Minimum Number of Operations to Make Elements in Array Distinct
|
Easy
|
<p>You are given an integer array <code>nums</code>. You need to ensure that the elements in the array are <strong>distinct</strong>. To achieve this, you can perform the following operation any number of times:</p>
<ul>
<li>Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, remove all remaining elements.</li>
</ul>
<p><strong>Note</strong> that an empty array is considered to have distinct elements. Return the <strong>minimum</strong> number of operations needed to make the elements in the array distinct.<!-- notionvc: 210ee4f2-90af-4cdf-8dbc-96d1fa8f67c7 --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,2,3,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 2, 3, 3, 5, 7]</code>.</li>
<li>In the second operation, the next 3 elements are removed, resulting in the array <code>[3, 5, 7]</code>, which has distinct elements.</li>
</ul>
<p>Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,4,4]</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 4]</code>.</li>
<li>In the second operation, all remaining elements are removed, resulting in an empty array.</li>
</ul>
<p>Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [6,7,8,9]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The array already contains distinct elements. Therefore, the answer is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table
|
Rust
|
use std::collections::HashSet;
impl Solution {
pub fn minimum_operations(nums: Vec<i32>) -> i32 {
let mut s = HashSet::new();
for i in (0..nums.len()).rev() {
if !s.insert(nums[i]) {
return (i / 3) as i32 + 1;
}
}
0
}
}
|
3,396 |
Minimum Number of Operations to Make Elements in Array Distinct
|
Easy
|
<p>You are given an integer array <code>nums</code>. You need to ensure that the elements in the array are <strong>distinct</strong>. To achieve this, you can perform the following operation any number of times:</p>
<ul>
<li>Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, remove all remaining elements.</li>
</ul>
<p><strong>Note</strong> that an empty array is considered to have distinct elements. Return the <strong>minimum</strong> number of operations needed to make the elements in the array distinct.<!-- notionvc: 210ee4f2-90af-4cdf-8dbc-96d1fa8f67c7 --></p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,2,3,3,5,7]</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 2, 3, 3, 5, 7]</code>.</li>
<li>In the second operation, the next 3 elements are removed, resulting in the array <code>[3, 5, 7]</code>, which has distinct elements.</li>
</ul>
<p>Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,4,4]</span></p>
<p><strong>Output:</strong> 2</p>
<p><strong>Explanation:</strong></p>
<ul>
<li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 4]</code>.</li>
<li>In the second operation, all remaining elements are removed, resulting in an empty array.</li>
</ul>
<p>Therefore, the answer is 2.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [6,7,8,9]</span></p>
<p><strong>Output:</strong> <span class="example-io">0</span></p>
<p><strong>Explanation:</strong></p>
<p>The array already contains distinct elements. Therefore, the answer is 0.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 100</code></li>
</ul>
|
Array; Hash Table
|
TypeScript
|
function minimumOperations(nums: number[]): number {
const s = new Set<number>();
for (let i = nums.length - 1; ~i; --i) {
if (s.has(nums[i])) {
return Math.ceil((i + 1) / 3);
}
s.add(nums[i]);
}
return 0;
}
|
3,397 |
Maximum Number of Distinct Elements After Operations
|
Medium
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>You are allowed to perform the following <strong>operation</strong> on each element of the array <strong>at most</strong> <em>once</em>:</p>
<ul>
<li>Add an integer in the range <code>[-k, k]</code> to the element.</li>
</ul>
<p>Return the <strong>maximum</strong> possible number of <strong>distinct</strong> elements in <code>nums</code> after performing the <strong>operations</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,3,3,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> changes to <code>[-1, 0, 1, 2, 3, 4]</code> after performing operations on the first four elements.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,4,4,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>By adding -1 to <code>nums[0]</code> and 1 to <code>nums[1]</code>, <code>nums</code> changes to <code>[3, 5, 4, 4]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
C++
|
class Solution {
public:
int maxDistinctElements(vector<int>& nums, int k) {
ranges::sort(nums);
int ans = 0, pre = INT_MIN;
for (int x : nums) {
int cur = min(x + k, max(x - k, pre + 1));
if (cur > pre) {
++ans;
pre = cur;
}
}
return ans;
}
};
|
3,397 |
Maximum Number of Distinct Elements After Operations
|
Medium
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>You are allowed to perform the following <strong>operation</strong> on each element of the array <strong>at most</strong> <em>once</em>:</p>
<ul>
<li>Add an integer in the range <code>[-k, k]</code> to the element.</li>
</ul>
<p>Return the <strong>maximum</strong> possible number of <strong>distinct</strong> elements in <code>nums</code> after performing the <strong>operations</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,3,3,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> changes to <code>[-1, 0, 1, 2, 3, 4]</code> after performing operations on the first four elements.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,4,4,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>By adding -1 to <code>nums[0]</code> and 1 to <code>nums[1]</code>, <code>nums</code> changes to <code>[3, 5, 4, 4]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
Go
|
func maxDistinctElements(nums []int, k int) (ans int) {
sort.Ints(nums)
pre := math.MinInt32
for _, x := range nums {
cur := min(x+k, max(x-k, pre+1))
if cur > pre {
ans++
pre = cur
}
}
return
}
|
3,397 |
Maximum Number of Distinct Elements After Operations
|
Medium
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>You are allowed to perform the following <strong>operation</strong> on each element of the array <strong>at most</strong> <em>once</em>:</p>
<ul>
<li>Add an integer in the range <code>[-k, k]</code> to the element.</li>
</ul>
<p>Return the <strong>maximum</strong> possible number of <strong>distinct</strong> elements in <code>nums</code> after performing the <strong>operations</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,3,3,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> changes to <code>[-1, 0, 1, 2, 3, 4]</code> after performing operations on the first four elements.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,4,4,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>By adding -1 to <code>nums[0]</code> and 1 to <code>nums[1]</code>, <code>nums</code> changes to <code>[3, 5, 4, 4]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
Java
|
class Solution {
public int maxDistinctElements(int[] nums, int k) {
Arrays.sort(nums);
int n = nums.length;
int ans = 0, pre = Integer.MIN_VALUE;
for (int x : nums) {
int cur = Math.min(x + k, Math.max(x - k, pre + 1));
if (cur > pre) {
++ans;
pre = cur;
}
}
return ans;
}
}
|
3,397 |
Maximum Number of Distinct Elements After Operations
|
Medium
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>You are allowed to perform the following <strong>operation</strong> on each element of the array <strong>at most</strong> <em>once</em>:</p>
<ul>
<li>Add an integer in the range <code>[-k, k]</code> to the element.</li>
</ul>
<p>Return the <strong>maximum</strong> possible number of <strong>distinct</strong> elements in <code>nums</code> after performing the <strong>operations</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,3,3,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> changes to <code>[-1, 0, 1, 2, 3, 4]</code> after performing operations on the first four elements.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,4,4,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>By adding -1 to <code>nums[0]</code> and 1 to <code>nums[1]</code>, <code>nums</code> changes to <code>[3, 5, 4, 4]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
Python
|
class Solution:
def maxDistinctElements(self, nums: List[int], k: int) -> int:
nums.sort()
ans = 0
pre = -inf
for x in nums:
cur = min(x + k, max(x - k, pre + 1))
if cur > pre:
ans += 1
pre = cur
return ans
|
3,397 |
Maximum Number of Distinct Elements After Operations
|
Medium
|
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>
<p>You are allowed to perform the following <strong>operation</strong> on each element of the array <strong>at most</strong> <em>once</em>:</p>
<ul>
<li>Add an integer in the range <code>[-k, k]</code> to the element.</li>
</ul>
<p>Return the <strong>maximum</strong> possible number of <strong>distinct</strong> elements in <code>nums</code> after performing the <strong>operations</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,3,3,4], k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p><code>nums</code> changes to <code>[-1, 0, 1, 2, 3, 4]</code> after performing operations on the first four elements.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [4,4,4,4], k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>By adding -1 to <code>nums[0]</code> and 1 to <code>nums[1]</code>, <code>nums</code> changes to <code>[3, 5, 4, 4]</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>9</sup></code></li>
<li><code>0 <= k <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Sorting
|
TypeScript
|
function maxDistinctElements(nums: number[], k: number): number {
nums.sort((a, b) => a - b);
let [ans, pre] = [0, -Infinity];
for (const x of nums) {
const cur = Math.min(x + k, Math.max(x - k, pre + 1));
if (cur > pre) {
++ans;
pre = cur;
}
}
return ans;
}
|
3,398 |
Smallest Substring With Identical Characters I
|
Hard
|
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p>
<p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p>
<ul>
<li>Select any index <code>i</code> (where <code>0 <= i < n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == '1'</code>, change <code>s[i]</code> to <code>'0'</code> and vice versa.</li>
</ul>
<p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p>
<p>Return the <strong>minimum</strong> length after the operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "000001", numOps = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"001001"</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0000", numOps = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"1010"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0101", numOps = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 1000</code></li>
<li><code>s</code> consists only of <code>'0'</code> and <code>'1'</code>.</li>
<li><code>0 <= numOps <= n</code></li>
</ul>
|
Array; Binary Search; Enumeration
|
C++
|
class Solution {
public:
int minLength(string s, int numOps) {
int n = s.size();
auto check = [&](int m) {
int cnt = 0;
if (m == 1) {
string t = "01";
for (int i = 0; i < n; ++i) {
if (s[i] == t[i & 1]) {
++cnt;
}
}
cnt = min(cnt, n - cnt);
} else {
int k = 0;
for (int i = 0; i < n; ++i) {
++k;
if (i == n - 1 || s[i] != s[i + 1]) {
cnt += k / (m + 1);
k = 0;
}
}
}
return cnt <= numOps;
};
int l = 1, r = n;
while (l < r) {
int mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
};
|
3,398 |
Smallest Substring With Identical Characters I
|
Hard
|
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p>
<p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p>
<ul>
<li>Select any index <code>i</code> (where <code>0 <= i < n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == '1'</code>, change <code>s[i]</code> to <code>'0'</code> and vice versa.</li>
</ul>
<p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p>
<p>Return the <strong>minimum</strong> length after the operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "000001", numOps = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"001001"</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0000", numOps = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"1010"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0101", numOps = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 1000</code></li>
<li><code>s</code> consists only of <code>'0'</code> and <code>'1'</code>.</li>
<li><code>0 <= numOps <= n</code></li>
</ul>
|
Array; Binary Search; Enumeration
|
Go
|
func minLength(s string, numOps int) int {
check := func(m int) bool {
m++
cnt := 0
if m == 1 {
t := "01"
for i := range s {
if s[i] == t[i&1] {
cnt++
}
}
cnt = min(cnt, len(s)-cnt)
} else {
k := 0
for i := range s {
k++
if i == len(s)-1 || s[i] != s[i+1] {
cnt += k / (m + 1)
k = 0
}
}
}
return cnt <= numOps
}
return 1 + sort.Search(len(s), func(m int) bool { return check(m) })
}
|
3,398 |
Smallest Substring With Identical Characters I
|
Hard
|
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p>
<p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p>
<ul>
<li>Select any index <code>i</code> (where <code>0 <= i < n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == '1'</code>, change <code>s[i]</code> to <code>'0'</code> and vice versa.</li>
</ul>
<p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p>
<p>Return the <strong>minimum</strong> length after the operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "000001", numOps = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"001001"</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0000", numOps = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"1010"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0101", numOps = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 1000</code></li>
<li><code>s</code> consists only of <code>'0'</code> and <code>'1'</code>.</li>
<li><code>0 <= numOps <= n</code></li>
</ul>
|
Array; Binary Search; Enumeration
|
Java
|
class Solution {
private char[] s;
private int numOps;
public int minLength(String s, int numOps) {
this.numOps = numOps;
this.s = s.toCharArray();
int l = 1, r = s.length();
while (l < r) {
int mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
private boolean check(int m) {
int cnt = 0;
if (m == 1) {
char[] t = {'0', '1'};
for (int i = 0; i < s.length; ++i) {
if (s[i] == t[i & 1]) {
++cnt;
}
}
cnt = Math.min(cnt, s.length - cnt);
} else {
int k = 0;
for (int i = 0; i < s.length; ++i) {
++k;
if (i == s.length - 1 || s[i] != s[i + 1]) {
cnt += k / (m + 1);
k = 0;
}
}
}
return cnt <= numOps;
}
}
|
3,398 |
Smallest Substring With Identical Characters I
|
Hard
|
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p>
<p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p>
<ul>
<li>Select any index <code>i</code> (where <code>0 <= i < n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == '1'</code>, change <code>s[i]</code> to <code>'0'</code> and vice versa.</li>
</ul>
<p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p>
<p>Return the <strong>minimum</strong> length after the operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "000001", numOps = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"001001"</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0000", numOps = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"1010"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0101", numOps = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 1000</code></li>
<li><code>s</code> consists only of <code>'0'</code> and <code>'1'</code>.</li>
<li><code>0 <= numOps <= n</code></li>
</ul>
|
Array; Binary Search; Enumeration
|
Python
|
class Solution:
def minLength(self, s: str, numOps: int) -> int:
def check(m: int) -> bool:
cnt = 0
if m == 1:
t = "01"
cnt = sum(c == t[i & 1] for i, c in enumerate(s))
cnt = min(cnt, n - cnt)
else:
k = 0
for i, c in enumerate(s):
k += 1
if i == len(s) - 1 or c != s[i + 1]:
cnt += k // (m + 1)
k = 0
return cnt <= numOps
n = len(s)
return bisect_left(range(n), True, lo=1, key=check)
|
3,398 |
Smallest Substring With Identical Characters I
|
Hard
|
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p>
<p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p>
<ul>
<li>Select any index <code>i</code> (where <code>0 <= i < n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == '1'</code>, change <code>s[i]</code> to <code>'0'</code> and vice versa.</li>
</ul>
<p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p>
<p>Return the <strong>minimum</strong> length after the operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "000001", numOps = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"001001"</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0000", numOps = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"1010"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0101", numOps = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 1000</code></li>
<li><code>s</code> consists only of <code>'0'</code> and <code>'1'</code>.</li>
<li><code>0 <= numOps <= n</code></li>
</ul>
|
Array; Binary Search; Enumeration
|
TypeScript
|
function minLength(s: string, numOps: number): number {
const n = s.length;
const check = (m: number): boolean => {
let cnt = 0;
if (m === 1) {
const t = '01';
for (let i = 0; i < n; ++i) {
if (s[i] === t[i & 1]) {
++cnt;
}
}
cnt = Math.min(cnt, n - cnt);
} else {
let k = 0;
for (let i = 0; i < n; ++i) {
++k;
if (i === n - 1 || s[i] !== s[i + 1]) {
cnt += Math.floor(k / (m + 1));
k = 0;
}
}
}
return cnt <= numOps;
};
let [l, r] = [1, n];
while (l < r) {
const mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
|
3,399 |
Smallest Substring With Identical Characters II
|
Hard
|
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p>
<p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p>
<ul>
<li>Select any index <code>i</code> (where <code>0 <= i < n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == '1'</code>, change <code>s[i]</code> to <code>'0'</code> and vice versa.</li>
</ul>
<p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p>
<p>Return the <strong>minimum</strong> length after the operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "000001", numOps = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"001001"</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0000", numOps = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"1010"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0101", numOps = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of <code>'0'</code> and <code>'1'</code>.</li>
<li><code>0 <= numOps <= n</code></li>
</ul>
|
String; Binary Search
|
C++
|
class Solution {
public:
int minLength(string s, int numOps) {
int n = s.size();
auto check = [&](int m) {
int cnt = 0;
if (m == 1) {
string t = "01";
for (int i = 0; i < n; ++i) {
if (s[i] == t[i & 1]) {
++cnt;
}
}
cnt = min(cnt, n - cnt);
} else {
int k = 0;
for (int i = 0; i < n; ++i) {
++k;
if (i == n - 1 || s[i] != s[i + 1]) {
cnt += k / (m + 1);
k = 0;
}
}
}
return cnt <= numOps;
};
int l = 1, r = n;
while (l < r) {
int mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
};
|
3,399 |
Smallest Substring With Identical Characters II
|
Hard
|
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p>
<p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p>
<ul>
<li>Select any index <code>i</code> (where <code>0 <= i < n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == '1'</code>, change <code>s[i]</code> to <code>'0'</code> and vice versa.</li>
</ul>
<p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p>
<p>Return the <strong>minimum</strong> length after the operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "000001", numOps = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"001001"</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0000", numOps = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"1010"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0101", numOps = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of <code>'0'</code> and <code>'1'</code>.</li>
<li><code>0 <= numOps <= n</code></li>
</ul>
|
String; Binary Search
|
Go
|
func minLength(s string, numOps int) int {
check := func(m int) bool {
m++
cnt := 0
if m == 1 {
t := "01"
for i := range s {
if s[i] == t[i&1] {
cnt++
}
}
cnt = min(cnt, len(s)-cnt)
} else {
k := 0
for i := range s {
k++
if i == len(s)-1 || s[i] != s[i+1] {
cnt += k / (m + 1)
k = 0
}
}
}
return cnt <= numOps
}
return 1 + sort.Search(len(s), func(m int) bool { return check(m) })
}
|
3,399 |
Smallest Substring With Identical Characters II
|
Hard
|
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p>
<p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p>
<ul>
<li>Select any index <code>i</code> (where <code>0 <= i < n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == '1'</code>, change <code>s[i]</code> to <code>'0'</code> and vice versa.</li>
</ul>
<p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p>
<p>Return the <strong>minimum</strong> length after the operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "000001", numOps = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"001001"</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0000", numOps = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"1010"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0101", numOps = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of <code>'0'</code> and <code>'1'</code>.</li>
<li><code>0 <= numOps <= n</code></li>
</ul>
|
String; Binary Search
|
Java
|
class Solution {
private char[] s;
private int numOps;
public int minLength(String s, int numOps) {
this.numOps = numOps;
this.s = s.toCharArray();
int l = 1, r = s.length();
while (l < r) {
int mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
private boolean check(int m) {
int cnt = 0;
if (m == 1) {
char[] t = {'0', '1'};
for (int i = 0; i < s.length; ++i) {
if (s[i] == t[i & 1]) {
++cnt;
}
}
cnt = Math.min(cnt, s.length - cnt);
} else {
int k = 0;
for (int i = 0; i < s.length; ++i) {
++k;
if (i == s.length - 1 || s[i] != s[i + 1]) {
cnt += k / (m + 1);
k = 0;
}
}
}
return cnt <= numOps;
}
}
|
3,399 |
Smallest Substring With Identical Characters II
|
Hard
|
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p>
<p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p>
<ul>
<li>Select any index <code>i</code> (where <code>0 <= i < n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == '1'</code>, change <code>s[i]</code> to <code>'0'</code> and vice versa.</li>
</ul>
<p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p>
<p>Return the <strong>minimum</strong> length after the operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "000001", numOps = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"001001"</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0000", numOps = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"1010"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0101", numOps = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of <code>'0'</code> and <code>'1'</code>.</li>
<li><code>0 <= numOps <= n</code></li>
</ul>
|
String; Binary Search
|
Python
|
class Solution:
def minLength(self, s: str, numOps: int) -> int:
def check(m: int) -> bool:
cnt = 0
if m == 1:
t = "01"
cnt = sum(c == t[i & 1] for i, c in enumerate(s))
cnt = min(cnt, n - cnt)
else:
k = 0
for i, c in enumerate(s):
k += 1
if i == len(s) - 1 or c != s[i + 1]:
cnt += k // (m + 1)
k = 0
return cnt <= numOps
n = len(s)
return bisect_left(range(n), True, lo=1, key=check)
|
3,399 |
Smallest Substring With Identical Characters II
|
Hard
|
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p>
<p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p>
<ul>
<li>Select any index <code>i</code> (where <code>0 <= i < n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == '1'</code>, change <code>s[i]</code> to <code>'0'</code> and vice versa.</li>
</ul>
<p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p>
<p>Return the <strong>minimum</strong> length after the operations.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "000001", numOps = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"001001"</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0000", numOps = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong> </p>
<p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>'1'</code>, <code>s</code> becomes <code>"1010"</code>.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "0101", numOps = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n == s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists only of <code>'0'</code> and <code>'1'</code>.</li>
<li><code>0 <= numOps <= n</code></li>
</ul>
|
String; Binary Search
|
TypeScript
|
function minLength(s: string, numOps: number): number {
const n = s.length;
const check = (m: number): boolean => {
let cnt = 0;
if (m === 1) {
const t = '01';
for (let i = 0; i < n; ++i) {
if (s[i] === t[i & 1]) {
++cnt;
}
}
cnt = Math.min(cnt, n - cnt);
} else {
let k = 0;
for (let i = 0; i < n; ++i) {
++k;
if (i === n - 1 || s[i] !== s[i + 1]) {
cnt += Math.floor(k / (m + 1));
k = 0;
}
}
}
return cnt <= numOps;
};
let [l, r] = [1, n];
while (l < r) {
const mid = (l + r) >> 1;
if (check(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
|
3,400 |
Maximum Number of Matching Indices After Right Shifts
|
Medium
|
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, of the same length.</p>
<p>An index <code>i</code> is considered <strong>matching</strong> if <code>nums1[i] == nums2[i]</code>.</p>
<p>Return the <strong>maximum</strong> number of <strong>matching</strong> indices after performing any number of <strong>right shifts</strong> on <code>nums1</code>.</p>
<p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [3,1,2,3,1,2], nums2 = [1,2,3,1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>If we right shift <code>nums1</code> 2 times, it becomes <code>[1, 2, 3, 1, 2, 3]</code>. Every index matches, so the output is 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,4,2,5,3,1], nums2 = [2,3,1,2,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>If we right shift <code>nums1</code> 3 times, it becomes <code>[5, 3, 1, 1, 4, 2]</code>. Indices 1, 2, and 4 match, so the output is 3.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums1.length == nums2.length</code></li>
<li><code>1 <= nums1.length, nums2.length <= 3000</code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers; Simulation
|
C++
|
class Solution {
public:
int maximumMatchingIndices(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size();
int ans = 0;
for (int k = 0; k < n; ++k) {
int t = 0;
for (int i = 0; i < n; ++i) {
if (nums1[(i + k) % n] == nums2[i]) {
++t;
}
}
ans = max(ans, t);
}
return ans;
}
};
|
3,400 |
Maximum Number of Matching Indices After Right Shifts
|
Medium
|
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, of the same length.</p>
<p>An index <code>i</code> is considered <strong>matching</strong> if <code>nums1[i] == nums2[i]</code>.</p>
<p>Return the <strong>maximum</strong> number of <strong>matching</strong> indices after performing any number of <strong>right shifts</strong> on <code>nums1</code>.</p>
<p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [3,1,2,3,1,2], nums2 = [1,2,3,1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>If we right shift <code>nums1</code> 2 times, it becomes <code>[1, 2, 3, 1, 2, 3]</code>. Every index matches, so the output is 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,4,2,5,3,1], nums2 = [2,3,1,2,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>If we right shift <code>nums1</code> 3 times, it becomes <code>[5, 3, 1, 1, 4, 2]</code>. Indices 1, 2, and 4 match, so the output is 3.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums1.length == nums2.length</code></li>
<li><code>1 <= nums1.length, nums2.length <= 3000</code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers; Simulation
|
Go
|
func maximumMatchingIndices(nums1 []int, nums2 []int) (ans int) {
n := len(nums1)
for k := range nums1 {
t := 0
for i, x := range nums2 {
if nums1[(i+k)%n] == x {
t++
}
}
ans = max(ans, t)
}
return
}
|
3,400 |
Maximum Number of Matching Indices After Right Shifts
|
Medium
|
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, of the same length.</p>
<p>An index <code>i</code> is considered <strong>matching</strong> if <code>nums1[i] == nums2[i]</code>.</p>
<p>Return the <strong>maximum</strong> number of <strong>matching</strong> indices after performing any number of <strong>right shifts</strong> on <code>nums1</code>.</p>
<p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [3,1,2,3,1,2], nums2 = [1,2,3,1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>If we right shift <code>nums1</code> 2 times, it becomes <code>[1, 2, 3, 1, 2, 3]</code>. Every index matches, so the output is 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,4,2,5,3,1], nums2 = [2,3,1,2,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>If we right shift <code>nums1</code> 3 times, it becomes <code>[5, 3, 1, 1, 4, 2]</code>. Indices 1, 2, and 4 match, so the output is 3.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums1.length == nums2.length</code></li>
<li><code>1 <= nums1.length, nums2.length <= 3000</code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers; Simulation
|
Java
|
class Solution {
public int maximumMatchingIndices(int[] nums1, int[] nums2) {
int n = nums1.length;
int ans = 0;
for (int k = 0; k < n; ++k) {
int t = 0;
for (int i = 0; i < n; ++i) {
if (nums1[(i + k) % n] == nums2[i]) {
++t;
}
}
ans = Math.max(ans, t);
}
return ans;
}
}
|
3,400 |
Maximum Number of Matching Indices After Right Shifts
|
Medium
|
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, of the same length.</p>
<p>An index <code>i</code> is considered <strong>matching</strong> if <code>nums1[i] == nums2[i]</code>.</p>
<p>Return the <strong>maximum</strong> number of <strong>matching</strong> indices after performing any number of <strong>right shifts</strong> on <code>nums1</code>.</p>
<p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [3,1,2,3,1,2], nums2 = [1,2,3,1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>If we right shift <code>nums1</code> 2 times, it becomes <code>[1, 2, 3, 1, 2, 3]</code>. Every index matches, so the output is 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,4,2,5,3,1], nums2 = [2,3,1,2,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>If we right shift <code>nums1</code> 3 times, it becomes <code>[5, 3, 1, 1, 4, 2]</code>. Indices 1, 2, and 4 match, so the output is 3.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums1.length == nums2.length</code></li>
<li><code>1 <= nums1.length, nums2.length <= 3000</code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers; Simulation
|
Python
|
class Solution:
def maximumMatchingIndices(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
ans = 0
for k in range(n):
t = sum(nums1[(i + k) % n] == x for i, x in enumerate(nums2))
ans = max(ans, t)
return ans
|
3,400 |
Maximum Number of Matching Indices After Right Shifts
|
Medium
|
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, of the same length.</p>
<p>An index <code>i</code> is considered <strong>matching</strong> if <code>nums1[i] == nums2[i]</code>.</p>
<p>Return the <strong>maximum</strong> number of <strong>matching</strong> indices after performing any number of <strong>right shifts</strong> on <code>nums1</code>.</p>
<p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [3,1,2,3,1,2], nums2 = [1,2,3,1,2,3]</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<p>If we right shift <code>nums1</code> 2 times, it becomes <code>[1, 2, 3, 1, 2, 3]</code>. Every index matches, so the output is 6.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums1 = [1,4,2,5,3,1], nums2 = [2,3,1,2,4,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>If we right shift <code>nums1</code> 3 times, it becomes <code>[5, 3, 1, 1, 4, 2]</code>. Indices 1, 2, and 4 match, so the output is 3.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>nums1.length == nums2.length</code></li>
<li><code>1 <= nums1.length, nums2.length <= 3000</code></li>
<li><code>1 <= nums1[i], nums2[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers; Simulation
|
TypeScript
|
function maximumMatchingIndices(nums1: number[], nums2: number[]): number {
const n = nums1.length;
let ans: number = 0;
for (let k = 0; k < n; ++k) {
let t: number = 0;
for (let i = 0; i < n; ++i) {
if (nums1[(i + k) % n] === nums2[i]) {
++t;
}
}
ans = Math.max(ans, t);
}
return ans;
}
|
3,402 |
Minimum Operations to Make Columns Strictly Increasing
|
Easy
|
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers.</p>
<p>In one operation, you can increment the value of any <code>grid[i][j]</code> by 1.</p>
<p>Return the <strong>minimum</strong> number of operations needed to make all columns of <code>grid</code> <strong>strictly increasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,2],[1,3],[3,4],[0,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 3 operations on <code>grid[1][0]</code>, 2 operations on <code>grid[2][0]</code>, and 6 operations on <code>grid[3][0]</code>.</li>
<li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 4 operations on <code>grid[3][1]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/firstexample.png" style="width: 200px; height: 347px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,2,1],[2,1,0],[1,2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][0]</code>, and 4 operations on <code>grid[2][0]</code>.</li>
<li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][1]</code>, and 2 operations on <code>grid[2][1]</code>.</li>
<li>To make the <code>2<sup>nd</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][2]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/secondexample.png" style="width: 300px; height: 257px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= grid[i][j] < 2500</code></li>
</ul>
<p> </p>
<div class="spoiler">
<div>
<pre>
</pre>
</div>
</div>
|
Greedy; Array; Matrix
|
C++
|
class Solution {
public:
int minimumOperations(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int ans = 0;
for (int j = 0; j < n; ++j) {
int pre = -1;
for (int i = 0; i < m; ++i) {
int cur = grid[i][j];
if (pre < cur) {
pre = cur;
} else {
++pre;
ans += pre - cur;
}
}
}
return ans;
}
};
|
3,402 |
Minimum Operations to Make Columns Strictly Increasing
|
Easy
|
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers.</p>
<p>In one operation, you can increment the value of any <code>grid[i][j]</code> by 1.</p>
<p>Return the <strong>minimum</strong> number of operations needed to make all columns of <code>grid</code> <strong>strictly increasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,2],[1,3],[3,4],[0,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 3 operations on <code>grid[1][0]</code>, 2 operations on <code>grid[2][0]</code>, and 6 operations on <code>grid[3][0]</code>.</li>
<li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 4 operations on <code>grid[3][1]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/firstexample.png" style="width: 200px; height: 347px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,2,1],[2,1,0],[1,2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][0]</code>, and 4 operations on <code>grid[2][0]</code>.</li>
<li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][1]</code>, and 2 operations on <code>grid[2][1]</code>.</li>
<li>To make the <code>2<sup>nd</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][2]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/secondexample.png" style="width: 300px; height: 257px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= grid[i][j] < 2500</code></li>
</ul>
<p> </p>
<div class="spoiler">
<div>
<pre>
</pre>
</div>
</div>
|
Greedy; Array; Matrix
|
Go
|
func minimumOperations(grid [][]int) (ans int) {
m, n := len(grid), len(grid[0])
for j := 0; j < n; j++ {
pre := -1
for i := 0; i < m; i++ {
cur := grid[i][j]
if pre < cur {
pre = cur
} else {
pre++
ans += pre - cur
}
}
}
return
}
|
3,402 |
Minimum Operations to Make Columns Strictly Increasing
|
Easy
|
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers.</p>
<p>In one operation, you can increment the value of any <code>grid[i][j]</code> by 1.</p>
<p>Return the <strong>minimum</strong> number of operations needed to make all columns of <code>grid</code> <strong>strictly increasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,2],[1,3],[3,4],[0,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 3 operations on <code>grid[1][0]</code>, 2 operations on <code>grid[2][0]</code>, and 6 operations on <code>grid[3][0]</code>.</li>
<li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 4 operations on <code>grid[3][1]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/firstexample.png" style="width: 200px; height: 347px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,2,1],[2,1,0],[1,2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][0]</code>, and 4 operations on <code>grid[2][0]</code>.</li>
<li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][1]</code>, and 2 operations on <code>grid[2][1]</code>.</li>
<li>To make the <code>2<sup>nd</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][2]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/secondexample.png" style="width: 300px; height: 257px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= grid[i][j] < 2500</code></li>
</ul>
<p> </p>
<div class="spoiler">
<div>
<pre>
</pre>
</div>
</div>
|
Greedy; Array; Matrix
|
Java
|
class Solution {
public int minimumOperations(int[][] grid) {
int m = grid.length, n = grid[0].length;
int ans = 0;
for (int j = 0; j < n; ++j) {
int pre = -1;
for (int i = 0; i < m; ++i) {
int cur = grid[i][j];
if (pre < cur) {
pre = cur;
} else {
++pre;
ans += pre - cur;
}
}
}
return ans;
}
}
|
3,402 |
Minimum Operations to Make Columns Strictly Increasing
|
Easy
|
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers.</p>
<p>In one operation, you can increment the value of any <code>grid[i][j]</code> by 1.</p>
<p>Return the <strong>minimum</strong> number of operations needed to make all columns of <code>grid</code> <strong>strictly increasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,2],[1,3],[3,4],[0,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 3 operations on <code>grid[1][0]</code>, 2 operations on <code>grid[2][0]</code>, and 6 operations on <code>grid[3][0]</code>.</li>
<li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 4 operations on <code>grid[3][1]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/firstexample.png" style="width: 200px; height: 347px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,2,1],[2,1,0],[1,2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][0]</code>, and 4 operations on <code>grid[2][0]</code>.</li>
<li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][1]</code>, and 2 operations on <code>grid[2][1]</code>.</li>
<li>To make the <code>2<sup>nd</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][2]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/secondexample.png" style="width: 300px; height: 257px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= grid[i][j] < 2500</code></li>
</ul>
<p> </p>
<div class="spoiler">
<div>
<pre>
</pre>
</div>
</div>
|
Greedy; Array; Matrix
|
Python
|
class Solution:
def minimumOperations(self, grid: List[List[int]]) -> int:
ans = 0
for col in zip(*grid):
pre = -1
for cur in col:
if pre < cur:
pre = cur
else:
pre += 1
ans += pre - cur
return ans
|
3,402 |
Minimum Operations to Make Columns Strictly Increasing
|
Easy
|
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers.</p>
<p>In one operation, you can increment the value of any <code>grid[i][j]</code> by 1.</p>
<p>Return the <strong>minimum</strong> number of operations needed to make all columns of <code>grid</code> <strong>strictly increasing</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,2],[1,3],[3,4],[0,1]]</span></p>
<p><strong>Output:</strong> <span class="example-io">15</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 3 operations on <code>grid[1][0]</code>, 2 operations on <code>grid[2][0]</code>, and 6 operations on <code>grid[3][0]</code>.</li>
<li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 4 operations on <code>grid[3][1]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/firstexample.png" style="width: 200px; height: 347px;" /></div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">grid = [[3,2,1],[2,1,0],[1,2,3]]</span></p>
<p><strong>Output:</strong> <span class="example-io">12</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][0]</code>, and 4 operations on <code>grid[2][0]</code>.</li>
<li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][1]</code>, and 2 operations on <code>grid[2][1]</code>.</li>
<li>To make the <code>2<sup>nd</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][2]</code>.</li>
</ul>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/secondexample.png" style="width: 300px; height: 257px;" /></div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>m == grid.length</code></li>
<li><code>n == grid[i].length</code></li>
<li><code>1 <= m, n <= 50</code></li>
<li><code>0 <= grid[i][j] < 2500</code></li>
</ul>
<p> </p>
<div class="spoiler">
<div>
<pre>
</pre>
</div>
</div>
|
Greedy; Array; Matrix
|
TypeScript
|
function minimumOperations(grid: number[][]): number {
const [m, n] = [grid.length, grid[0].length];
let ans: number = 0;
for (let j = 0; j < n; ++j) {
let pre: number = -1;
for (let i = 0; i < m; ++i) {
const cur = grid[i][j];
if (pre < cur) {
pre = cur;
} else {
++pre;
ans += pre - cur;
}
}
}
return ans;
}
|
3,403 |
Find the Lexicographically Largest String From the Box I
|
Medium
|
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p>
<p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p>
<ul>
<li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li>
<li>All the split words are put into a box.</li>
</ul>
<p>Find the <span data-keyword="lexicographically-smaller-string">lexicographically largest</span> string from the box after all the rounds are finished.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "dbca", numFriends = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"dbc"</span></p>
<p><strong>Explanation:</strong> </p>
<p>All possible splits are:</p>
<ul>
<li><code>"d"</code> and <code>"bca"</code>.</li>
<li><code>"db"</code> and <code>"ca"</code>.</li>
<li><code>"dbc"</code> and <code>"a"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "gggg", numFriends = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"g"</span></p>
<p><strong>Explanation:</strong> </p>
<p>The only possible split is: <code>"g"</code>, <code>"g"</code>, <code>"g"</code>, and <code>"g"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 5 * 10<sup>3</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>1 <= numFriends <= word.length</code></li>
</ul>
|
Two Pointers; String; Enumeration
|
C++
|
class Solution {
public:
string answerString(string word, int numFriends) {
if (numFriends == 1) {
return word;
}
int n = word.length();
string ans = "";
for (int i = 0; i < n; ++i) {
string t = word.substr(i, min(n - i, n - (numFriends - 1)));
if (ans < t) {
ans = t;
}
}
return ans;
}
};
|
3,403 |
Find the Lexicographically Largest String From the Box I
|
Medium
|
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p>
<p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p>
<ul>
<li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li>
<li>All the split words are put into a box.</li>
</ul>
<p>Find the <span data-keyword="lexicographically-smaller-string">lexicographically largest</span> string from the box after all the rounds are finished.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "dbca", numFriends = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"dbc"</span></p>
<p><strong>Explanation:</strong> </p>
<p>All possible splits are:</p>
<ul>
<li><code>"d"</code> and <code>"bca"</code>.</li>
<li><code>"db"</code> and <code>"ca"</code>.</li>
<li><code>"dbc"</code> and <code>"a"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "gggg", numFriends = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"g"</span></p>
<p><strong>Explanation:</strong> </p>
<p>The only possible split is: <code>"g"</code>, <code>"g"</code>, <code>"g"</code>, and <code>"g"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 5 * 10<sup>3</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>1 <= numFriends <= word.length</code></li>
</ul>
|
Two Pointers; String; Enumeration
|
Go
|
func answerString(word string, numFriends int) (ans string) {
if numFriends == 1 {
return word
}
n := len(word)
for i := 0; i < n; i++ {
t := word[i:min(n, i+n-(numFriends-1))]
ans = max(ans, t)
}
return
}
|
3,403 |
Find the Lexicographically Largest String From the Box I
|
Medium
|
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p>
<p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p>
<ul>
<li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li>
<li>All the split words are put into a box.</li>
</ul>
<p>Find the <span data-keyword="lexicographically-smaller-string">lexicographically largest</span> string from the box after all the rounds are finished.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "dbca", numFriends = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"dbc"</span></p>
<p><strong>Explanation:</strong> </p>
<p>All possible splits are:</p>
<ul>
<li><code>"d"</code> and <code>"bca"</code>.</li>
<li><code>"db"</code> and <code>"ca"</code>.</li>
<li><code>"dbc"</code> and <code>"a"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "gggg", numFriends = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"g"</span></p>
<p><strong>Explanation:</strong> </p>
<p>The only possible split is: <code>"g"</code>, <code>"g"</code>, <code>"g"</code>, and <code>"g"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 5 * 10<sup>3</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>1 <= numFriends <= word.length</code></li>
</ul>
|
Two Pointers; String; Enumeration
|
Java
|
class Solution {
public String answerString(String word, int numFriends) {
if (numFriends == 1) {
return word;
}
int n = word.length();
String ans = "";
for (int i = 0; i < n; ++i) {
String t = word.substring(i, Math.min(n, i + n - (numFriends - 1)));
if (ans.compareTo(t) < 0) {
ans = t;
}
}
return ans;
}
}
|
3,403 |
Find the Lexicographically Largest String From the Box I
|
Medium
|
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p>
<p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p>
<ul>
<li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li>
<li>All the split words are put into a box.</li>
</ul>
<p>Find the <span data-keyword="lexicographically-smaller-string">lexicographically largest</span> string from the box after all the rounds are finished.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "dbca", numFriends = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"dbc"</span></p>
<p><strong>Explanation:</strong> </p>
<p>All possible splits are:</p>
<ul>
<li><code>"d"</code> and <code>"bca"</code>.</li>
<li><code>"db"</code> and <code>"ca"</code>.</li>
<li><code>"dbc"</code> and <code>"a"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "gggg", numFriends = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"g"</span></p>
<p><strong>Explanation:</strong> </p>
<p>The only possible split is: <code>"g"</code>, <code>"g"</code>, <code>"g"</code>, and <code>"g"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 5 * 10<sup>3</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>1 <= numFriends <= word.length</code></li>
</ul>
|
Two Pointers; String; Enumeration
|
Python
|
class Solution:
def answerString(self, word: str, numFriends: int) -> str:
if numFriends == 1:
return word
n = len(word)
return max(word[i : i + n - (numFriends - 1)] for i in range(n))
|
3,403 |
Find the Lexicographically Largest String From the Box I
|
Medium
|
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p>
<p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p>
<ul>
<li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li>
<li>All the split words are put into a box.</li>
</ul>
<p>Find the <span data-keyword="lexicographically-smaller-string">lexicographically largest</span> string from the box after all the rounds are finished.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "dbca", numFriends = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"dbc"</span></p>
<p><strong>Explanation:</strong> </p>
<p>All possible splits are:</p>
<ul>
<li><code>"d"</code> and <code>"bca"</code>.</li>
<li><code>"db"</code> and <code>"ca"</code>.</li>
<li><code>"dbc"</code> and <code>"a"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "gggg", numFriends = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"g"</span></p>
<p><strong>Explanation:</strong> </p>
<p>The only possible split is: <code>"g"</code>, <code>"g"</code>, <code>"g"</code>, and <code>"g"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 5 * 10<sup>3</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>1 <= numFriends <= word.length</code></li>
</ul>
|
Two Pointers; String; Enumeration
|
TypeScript
|
function answerString(word: string, numFriends: number): string {
if (numFriends === 1) {
return word;
}
const n = word.length;
let ans = '';
for (let i = 0; i < n; i++) {
const t = word.slice(i, Math.min(n, i + n - (numFriends - 1)));
ans = t > ans ? t : ans;
}
return ans;
}
|
3,404 |
Count Special Subsequences
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>A <strong>special subsequence</strong> is defined as a <span data-keyword="subsequence-array">subsequence</span> of length 4, represented by indices <code>(p, q, r, s)</code>, where <code>p < q < r < s</code>. This subsequence <strong>must</strong> satisfy the following conditions:</p>
<ul>
<li><code>nums[p] * nums[r] == nums[q] * nums[s]</code></li>
<li>There must be <em>at least</em> <strong>one</strong> element between each pair of indices. In other words, <code>q - p > 1</code>, <code>r - q > 1</code> and <code>s - r > 1</code>.</li>
</ul>
<p>Return the <em>number</em> of different <strong>special</strong> <strong>subsequences</strong> in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,6,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is one special subsequence in <code>nums</code>.</p>
<ul>
<li><code>(p, q, r, s) = (0, 2, 4, 6)</code>:
<ul>
<li>This corresponds to elements <code>(1, 3, 3, 1)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[4] = 1 * 3 = 3</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 1 = 3</code></li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,3,4,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>There are three special subsequences in <code>nums</code>.</p>
<ul>
<li><code>(p, q, r, s) = (0, 2, 4, 6)</code>:
<ul>
<li>This corresponds to elements <code>(3, 3, 3, 3)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[4] = 3 * 3 = 9</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 3 = 9</code></li>
</ul>
</li>
<li><code>(p, q, r, s) = (1, 3, 5, 7)</code>:
<ul>
<li>This corresponds to elements <code>(4, 4, 4, 4)</code>.</li>
<li><code>nums[p] * nums[r] = nums[1] * nums[5] = 4 * 4 = 16</code></li>
<li><code>nums[q] * nums[s] = nums[3] * nums[7] = 4 * 4 = 16</code></li>
</ul>
</li>
<li><code>(p, q, r, s) = (0, 2, 5, 7)</code>:
<ul>
<li>This corresponds to elements <code>(3, 3, 4, 4)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[5] = 3 * 4 = 12</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[7] = 3 * 4 = 12</code></li>
</ul>
</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>7 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Hash Table; Math; Enumeration
|
C++
|
class Solution {
public:
long long numberOfSubsequences(vector<int>& nums) {
int n = nums.size();
unordered_map<int, int> cnt;
for (int r = 4; r < n - 2; ++r) {
int c = nums[r];
for (int s = r + 2; s < n; ++s) {
int d = nums[s];
int g = gcd(c, d);
cnt[((d / g) << 12) | (c / g)]++;
}
}
long long ans = 0;
for (int q = 2; q < n - 4; ++q) {
int b = nums[q];
for (int p = 0; p < q - 1; ++p) {
int a = nums[p];
int g = gcd(a, b);
ans += cnt[((a / g) << 12) | (b / g)];
}
int c = nums[q + 2];
for (int s = q + 4; s < n; ++s) {
int d = nums[s];
int g = gcd(c, d);
cnt[((d / g) << 12) | (c / g)]--;
}
}
return ans;
}
};
|
3,404 |
Count Special Subsequences
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>A <strong>special subsequence</strong> is defined as a <span data-keyword="subsequence-array">subsequence</span> of length 4, represented by indices <code>(p, q, r, s)</code>, where <code>p < q < r < s</code>. This subsequence <strong>must</strong> satisfy the following conditions:</p>
<ul>
<li><code>nums[p] * nums[r] == nums[q] * nums[s]</code></li>
<li>There must be <em>at least</em> <strong>one</strong> element between each pair of indices. In other words, <code>q - p > 1</code>, <code>r - q > 1</code> and <code>s - r > 1</code>.</li>
</ul>
<p>Return the <em>number</em> of different <strong>special</strong> <strong>subsequences</strong> in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,6,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is one special subsequence in <code>nums</code>.</p>
<ul>
<li><code>(p, q, r, s) = (0, 2, 4, 6)</code>:
<ul>
<li>This corresponds to elements <code>(1, 3, 3, 1)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[4] = 1 * 3 = 3</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 1 = 3</code></li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,3,4,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>There are three special subsequences in <code>nums</code>.</p>
<ul>
<li><code>(p, q, r, s) = (0, 2, 4, 6)</code>:
<ul>
<li>This corresponds to elements <code>(3, 3, 3, 3)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[4] = 3 * 3 = 9</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 3 = 9</code></li>
</ul>
</li>
<li><code>(p, q, r, s) = (1, 3, 5, 7)</code>:
<ul>
<li>This corresponds to elements <code>(4, 4, 4, 4)</code>.</li>
<li><code>nums[p] * nums[r] = nums[1] * nums[5] = 4 * 4 = 16</code></li>
<li><code>nums[q] * nums[s] = nums[3] * nums[7] = 4 * 4 = 16</code></li>
</ul>
</li>
<li><code>(p, q, r, s) = (0, 2, 5, 7)</code>:
<ul>
<li>This corresponds to elements <code>(3, 3, 4, 4)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[5] = 3 * 4 = 12</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[7] = 3 * 4 = 12</code></li>
</ul>
</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>7 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Hash Table; Math; Enumeration
|
Go
|
func numberOfSubsequences(nums []int) (ans int64) {
n := len(nums)
cnt := make(map[int]int)
gcd := func(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}
for r := 4; r < n-2; r++ {
c := nums[r]
for s := r + 2; s < n; s++ {
d := nums[s]
g := gcd(c, d)
key := ((d / g) << 12) | (c / g)
cnt[key]++
}
}
for q := 2; q < n-4; q++ {
b := nums[q]
for p := 0; p < q-1; p++ {
a := nums[p]
g := gcd(a, b)
key := ((a / g) << 12) | (b / g)
ans += int64(cnt[key])
}
c := nums[q+2]
for s := q + 4; s < n; s++ {
d := nums[s]
g := gcd(c, d)
key := ((d / g) << 12) | (c / g)
cnt[key]--
}
}
return
}
|
3,404 |
Count Special Subsequences
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>A <strong>special subsequence</strong> is defined as a <span data-keyword="subsequence-array">subsequence</span> of length 4, represented by indices <code>(p, q, r, s)</code>, where <code>p < q < r < s</code>. This subsequence <strong>must</strong> satisfy the following conditions:</p>
<ul>
<li><code>nums[p] * nums[r] == nums[q] * nums[s]</code></li>
<li>There must be <em>at least</em> <strong>one</strong> element between each pair of indices. In other words, <code>q - p > 1</code>, <code>r - q > 1</code> and <code>s - r > 1</code>.</li>
</ul>
<p>Return the <em>number</em> of different <strong>special</strong> <strong>subsequences</strong> in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,6,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is one special subsequence in <code>nums</code>.</p>
<ul>
<li><code>(p, q, r, s) = (0, 2, 4, 6)</code>:
<ul>
<li>This corresponds to elements <code>(1, 3, 3, 1)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[4] = 1 * 3 = 3</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 1 = 3</code></li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,3,4,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>There are three special subsequences in <code>nums</code>.</p>
<ul>
<li><code>(p, q, r, s) = (0, 2, 4, 6)</code>:
<ul>
<li>This corresponds to elements <code>(3, 3, 3, 3)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[4] = 3 * 3 = 9</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 3 = 9</code></li>
</ul>
</li>
<li><code>(p, q, r, s) = (1, 3, 5, 7)</code>:
<ul>
<li>This corresponds to elements <code>(4, 4, 4, 4)</code>.</li>
<li><code>nums[p] * nums[r] = nums[1] * nums[5] = 4 * 4 = 16</code></li>
<li><code>nums[q] * nums[s] = nums[3] * nums[7] = 4 * 4 = 16</code></li>
</ul>
</li>
<li><code>(p, q, r, s) = (0, 2, 5, 7)</code>:
<ul>
<li>This corresponds to elements <code>(3, 3, 4, 4)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[5] = 3 * 4 = 12</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[7] = 3 * 4 = 12</code></li>
</ul>
</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>7 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Hash Table; Math; Enumeration
|
Java
|
class Solution {
public long numberOfSubsequences(int[] nums) {
int n = nums.length;
Map<Integer, Integer> cnt = new HashMap<>();
for (int r = 4; r < n - 2; ++r) {
int c = nums[r];
for (int s = r + 2; s < n; ++s) {
int d = nums[s];
int g = gcd(c, d);
cnt.merge(((d / g) << 12) | (c / g), 1, Integer::sum);
}
}
long ans = 0;
for (int q = 2; q < n - 4; ++q) {
int b = nums[q];
for (int p = 0; p < q - 1; ++p) {
int a = nums[p];
int g = gcd(a, b);
ans += cnt.getOrDefault(((a / g) << 12) | (b / g), 0);
}
int c = nums[q + 2];
for (int s = q + 4; s < n; ++s) {
int d = nums[s];
int g = gcd(c, d);
cnt.merge(((d / g) << 12) | (c / g), -1, Integer::sum);
}
}
return ans;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
|
3,404 |
Count Special Subsequences
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>A <strong>special subsequence</strong> is defined as a <span data-keyword="subsequence-array">subsequence</span> of length 4, represented by indices <code>(p, q, r, s)</code>, where <code>p < q < r < s</code>. This subsequence <strong>must</strong> satisfy the following conditions:</p>
<ul>
<li><code>nums[p] * nums[r] == nums[q] * nums[s]</code></li>
<li>There must be <em>at least</em> <strong>one</strong> element between each pair of indices. In other words, <code>q - p > 1</code>, <code>r - q > 1</code> and <code>s - r > 1</code>.</li>
</ul>
<p>Return the <em>number</em> of different <strong>special</strong> <strong>subsequences</strong> in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,6,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is one special subsequence in <code>nums</code>.</p>
<ul>
<li><code>(p, q, r, s) = (0, 2, 4, 6)</code>:
<ul>
<li>This corresponds to elements <code>(1, 3, 3, 1)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[4] = 1 * 3 = 3</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 1 = 3</code></li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,3,4,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>There are three special subsequences in <code>nums</code>.</p>
<ul>
<li><code>(p, q, r, s) = (0, 2, 4, 6)</code>:
<ul>
<li>This corresponds to elements <code>(3, 3, 3, 3)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[4] = 3 * 3 = 9</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 3 = 9</code></li>
</ul>
</li>
<li><code>(p, q, r, s) = (1, 3, 5, 7)</code>:
<ul>
<li>This corresponds to elements <code>(4, 4, 4, 4)</code>.</li>
<li><code>nums[p] * nums[r] = nums[1] * nums[5] = 4 * 4 = 16</code></li>
<li><code>nums[q] * nums[s] = nums[3] * nums[7] = 4 * 4 = 16</code></li>
</ul>
</li>
<li><code>(p, q, r, s) = (0, 2, 5, 7)</code>:
<ul>
<li>This corresponds to elements <code>(3, 3, 4, 4)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[5] = 3 * 4 = 12</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[7] = 3 * 4 = 12</code></li>
</ul>
</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>7 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Hash Table; Math; Enumeration
|
Python
|
class Solution:
def numberOfSubsequences(self, nums: List[int]) -> int:
n = len(nums)
cnt = defaultdict(int)
for r in range(4, n - 2):
c = nums[r]
for s in range(r + 2, n):
d = nums[s]
g = gcd(c, d)
cnt[(d // g, c // g)] += 1
ans = 0
for q in range(2, n - 4):
b = nums[q]
for p in range(q - 1):
a = nums[p]
g = gcd(a, b)
ans += cnt[(a // g, b // g)]
c = nums[q + 2]
for s in range(q + 4, n):
d = nums[s]
g = gcd(c, d)
cnt[(d // g, c // g)] -= 1
return ans
|
3,404 |
Count Special Subsequences
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>A <strong>special subsequence</strong> is defined as a <span data-keyword="subsequence-array">subsequence</span> of length 4, represented by indices <code>(p, q, r, s)</code>, where <code>p < q < r < s</code>. This subsequence <strong>must</strong> satisfy the following conditions:</p>
<ul>
<li><code>nums[p] * nums[r] == nums[q] * nums[s]</code></li>
<li>There must be <em>at least</em> <strong>one</strong> element between each pair of indices. In other words, <code>q - p > 1</code>, <code>r - q > 1</code> and <code>s - r > 1</code>.</li>
</ul>
<p>Return the <em>number</em> of different <strong>special</strong> <strong>subsequences</strong> in <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,3,6,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">1</span></p>
<p><strong>Explanation:</strong></p>
<p>There is one special subsequence in <code>nums</code>.</p>
<ul>
<li><code>(p, q, r, s) = (0, 2, 4, 6)</code>:
<ul>
<li>This corresponds to elements <code>(1, 3, 3, 1)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[4] = 1 * 3 = 3</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 1 = 3</code></li>
</ul>
</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,3,4,3,4]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong></p>
<p>There are three special subsequences in <code>nums</code>.</p>
<ul>
<li><code>(p, q, r, s) = (0, 2, 4, 6)</code>:
<ul>
<li>This corresponds to elements <code>(3, 3, 3, 3)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[4] = 3 * 3 = 9</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 3 = 9</code></li>
</ul>
</li>
<li><code>(p, q, r, s) = (1, 3, 5, 7)</code>:
<ul>
<li>This corresponds to elements <code>(4, 4, 4, 4)</code>.</li>
<li><code>nums[p] * nums[r] = nums[1] * nums[5] = 4 * 4 = 16</code></li>
<li><code>nums[q] * nums[s] = nums[3] * nums[7] = 4 * 4 = 16</code></li>
</ul>
</li>
<li><code>(p, q, r, s) = (0, 2, 5, 7)</code>:
<ul>
<li>This corresponds to elements <code>(3, 3, 4, 4)</code>.</li>
<li><code>nums[p] * nums[r] = nums[0] * nums[5] = 3 * 4 = 12</code></li>
<li><code>nums[q] * nums[s] = nums[2] * nums[7] = 3 * 4 = 12</code></li>
</ul>
</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>7 <= nums.length <= 1000</code></li>
<li><code>1 <= nums[i] <= 1000</code></li>
</ul>
|
Array; Hash Table; Math; Enumeration
|
TypeScript
|
function numberOfSubsequences(nums: number[]): number {
const n = nums.length;
const cnt = new Map<number, number>();
function gcd(a: number, b: number): number {
while (b !== 0) {
[a, b] = [b, a % b];
}
return a;
}
for (let r = 4; r < n - 2; r++) {
const c = nums[r];
for (let s = r + 2; s < n; s++) {
const d = nums[s];
const g = gcd(c, d);
const key = ((d / g) << 12) | (c / g);
cnt.set(key, (cnt.get(key) || 0) + 1);
}
}
let ans = 0;
for (let q = 2; q < n - 4; q++) {
const b = nums[q];
for (let p = 0; p < q - 1; p++) {
const a = nums[p];
const g = gcd(a, b);
const key = ((a / g) << 12) | (b / g);
ans += cnt.get(key) || 0;
}
const c = nums[q + 2];
for (let s = q + 4; s < n; s++) {
const d = nums[s];
const g = gcd(c, d);
const key = ((d / g) << 12) | (c / g);
cnt.set(key, (cnt.get(key) || 0) - 1);
}
}
return ans;
}
|
3,405 |
Count the Number of Arrays with K Matching Adjacent Elements
|
Hard
|
<p>You are given three integers <code>n</code>, <code>m</code>, <code>k</code>. A <strong>good array</strong> <code>arr</code> of size <code>n</code> is defined as follows:</p>
<ul>
<li>Each element in <code>arr</code> is in the <strong>inclusive</strong> range <code>[1, m]</code>.</li>
<li><em>Exactly</em> <code>k</code> indices <code>i</code> (where <code>1 <= i < n</code>) satisfy the condition <code>arr[i - 1] == arr[i]</code>.</li>
</ul>
<p>Return the number of <strong>good arrays</strong> that can be formed.</p>
<p>Since the answer may be very large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, m = 2, k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>There are 4 good arrays. They are <code>[1, 1, 2]</code>, <code>[1, 2, 2]</code>, <code>[2, 1, 1]</code> and <code>[2, 2, 1]</code>.</li>
<li>Hence, the answer is 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, m = 2, k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The good arrays are <code>[1, 1, 1, 2]</code>, <code>[1, 1, 2, 2]</code>, <code>[1, 2, 2, 2]</code>, <code>[2, 1, 1, 1]</code>, <code>[2, 2, 1, 1]</code> and <code>[2, 2, 2, 1]</code>.</li>
<li>Hence, the answer is 6.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, m = 2, k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The good arrays are <code>[1, 2, 1, 2, 1]</code> and <code>[2, 1, 2, 1, 2]</code>. Hence, the answer is 2.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= m <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= n - 1</code></li>
</ul>
|
Math; Combinatorics
|
C++
|
const int MX = 1e5 + 10;
const int MOD = 1e9 + 7;
long long f[MX];
long long g[MX];
long long qpow(long a, int k) {
long res = 1;
while (k != 0) {
if ((k & 1) == 1) {
res = res * a % MOD;
}
k >>= 1;
a = a * a % MOD;
}
return res;
}
int init = []() {
f[0] = g[0] = 1;
for (int i = 1; i < MX; ++i) {
f[i] = f[i - 1] * i % MOD;
g[i] = qpow(f[i], MOD - 2);
}
return 0;
}();
long long comb(int m, int n) {
return f[m] * g[n] % MOD * g[m - n] % MOD;
}
class Solution {
public:
int countGoodArrays(int n, int m, int k) {
return comb(n - 1, k) * m % MOD * qpow(m - 1, n - k - 1) % MOD;
}
};
|
3,405 |
Count the Number of Arrays with K Matching Adjacent Elements
|
Hard
|
<p>You are given three integers <code>n</code>, <code>m</code>, <code>k</code>. A <strong>good array</strong> <code>arr</code> of size <code>n</code> is defined as follows:</p>
<ul>
<li>Each element in <code>arr</code> is in the <strong>inclusive</strong> range <code>[1, m]</code>.</li>
<li><em>Exactly</em> <code>k</code> indices <code>i</code> (where <code>1 <= i < n</code>) satisfy the condition <code>arr[i - 1] == arr[i]</code>.</li>
</ul>
<p>Return the number of <strong>good arrays</strong> that can be formed.</p>
<p>Since the answer may be very large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, m = 2, k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>There are 4 good arrays. They are <code>[1, 1, 2]</code>, <code>[1, 2, 2]</code>, <code>[2, 1, 1]</code> and <code>[2, 2, 1]</code>.</li>
<li>Hence, the answer is 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, m = 2, k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The good arrays are <code>[1, 1, 1, 2]</code>, <code>[1, 1, 2, 2]</code>, <code>[1, 2, 2, 2]</code>, <code>[2, 1, 1, 1]</code>, <code>[2, 2, 1, 1]</code> and <code>[2, 2, 2, 1]</code>.</li>
<li>Hence, the answer is 6.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, m = 2, k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The good arrays are <code>[1, 2, 1, 2, 1]</code> and <code>[2, 1, 2, 1, 2]</code>. Hence, the answer is 2.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= m <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= n - 1</code></li>
</ul>
|
Math; Combinatorics
|
Go
|
const MX = 1e5 + 10
const MOD = 1e9 + 7
var f [MX]int64
var g [MX]int64
func qpow(a int64, k int) int64 {
res := int64(1)
for k != 0 {
if k&1 == 1 {
res = res * a % MOD
}
a = a * a % MOD
k >>= 1
}
return res
}
func init() {
f[0], g[0] = 1, 1
for i := 1; i < MX; i++ {
f[i] = f[i-1] * int64(i) % MOD
g[i] = qpow(f[i], MOD-2)
}
}
func comb(m, n int) int64 {
return f[m] * g[n] % MOD * g[m-n] % MOD
}
func countGoodArrays(n int, m int, k int) int {
ans := comb(n-1, k) * int64(m) % MOD * qpow(int64(m-1), n-k-1) % MOD
return int(ans)
}
|
3,405 |
Count the Number of Arrays with K Matching Adjacent Elements
|
Hard
|
<p>You are given three integers <code>n</code>, <code>m</code>, <code>k</code>. A <strong>good array</strong> <code>arr</code> of size <code>n</code> is defined as follows:</p>
<ul>
<li>Each element in <code>arr</code> is in the <strong>inclusive</strong> range <code>[1, m]</code>.</li>
<li><em>Exactly</em> <code>k</code> indices <code>i</code> (where <code>1 <= i < n</code>) satisfy the condition <code>arr[i - 1] == arr[i]</code>.</li>
</ul>
<p>Return the number of <strong>good arrays</strong> that can be formed.</p>
<p>Since the answer may be very large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, m = 2, k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>There are 4 good arrays. They are <code>[1, 1, 2]</code>, <code>[1, 2, 2]</code>, <code>[2, 1, 1]</code> and <code>[2, 2, 1]</code>.</li>
<li>Hence, the answer is 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, m = 2, k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The good arrays are <code>[1, 1, 1, 2]</code>, <code>[1, 1, 2, 2]</code>, <code>[1, 2, 2, 2]</code>, <code>[2, 1, 1, 1]</code>, <code>[2, 2, 1, 1]</code> and <code>[2, 2, 2, 1]</code>.</li>
<li>Hence, the answer is 6.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, m = 2, k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The good arrays are <code>[1, 2, 1, 2, 1]</code> and <code>[2, 1, 2, 1, 2]</code>. Hence, the answer is 2.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= m <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= n - 1</code></li>
</ul>
|
Math; Combinatorics
|
Java
|
class Solution {
private static final int N = (int) 1e5 + 10;
private static final int MOD = (int) 1e9 + 7;
private static final long[] f = new long[N];
private static final long[] g = new long[N];
static {
f[0] = 1;
g[0] = 1;
for (int i = 1; i < N; ++i) {
f[i] = f[i - 1] * i % MOD;
g[i] = qpow(f[i], MOD - 2);
}
}
public static long qpow(long a, int k) {
long res = 1;
while (k != 0) {
if ((k & 1) == 1) {
res = res * a % MOD;
}
k >>= 1;
a = a * a % MOD;
}
return res;
}
public static long comb(int m, int n) {
return (int) f[m] * g[n] % MOD * g[m - n] % MOD;
}
public int countGoodArrays(int n, int m, int k) {
return (int) (comb(n - 1, k) * m % MOD * qpow(m - 1, n - k - 1) % MOD);
}
}
|
3,405 |
Count the Number of Arrays with K Matching Adjacent Elements
|
Hard
|
<p>You are given three integers <code>n</code>, <code>m</code>, <code>k</code>. A <strong>good array</strong> <code>arr</code> of size <code>n</code> is defined as follows:</p>
<ul>
<li>Each element in <code>arr</code> is in the <strong>inclusive</strong> range <code>[1, m]</code>.</li>
<li><em>Exactly</em> <code>k</code> indices <code>i</code> (where <code>1 <= i < n</code>) satisfy the condition <code>arr[i - 1] == arr[i]</code>.</li>
</ul>
<p>Return the number of <strong>good arrays</strong> that can be formed.</p>
<p>Since the answer may be very large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, m = 2, k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>There are 4 good arrays. They are <code>[1, 1, 2]</code>, <code>[1, 2, 2]</code>, <code>[2, 1, 1]</code> and <code>[2, 2, 1]</code>.</li>
<li>Hence, the answer is 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, m = 2, k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The good arrays are <code>[1, 1, 1, 2]</code>, <code>[1, 1, 2, 2]</code>, <code>[1, 2, 2, 2]</code>, <code>[2, 1, 1, 1]</code>, <code>[2, 2, 1, 1]</code> and <code>[2, 2, 2, 1]</code>.</li>
<li>Hence, the answer is 6.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, m = 2, k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The good arrays are <code>[1, 2, 1, 2, 1]</code> and <code>[2, 1, 2, 1, 2]</code>. Hence, the answer is 2.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= m <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= n - 1</code></li>
</ul>
|
Math; Combinatorics
|
Python
|
mx = 10**5 + 10
mod = 10**9 + 7
f = [1] + [0] * mx
g = [1] + [0] * mx
for i in range(1, mx):
f[i] = f[i - 1] * i % mod
g[i] = pow(f[i], mod - 2, mod)
def comb(m: int, n: int) -> int:
return f[m] * g[n] * g[m - n] % mod
class Solution:
def countGoodArrays(self, n: int, m: int, k: int) -> int:
return comb(n - 1, k) * m * pow(m - 1, n - k - 1, mod) % mod
|
3,405 |
Count the Number of Arrays with K Matching Adjacent Elements
|
Hard
|
<p>You are given three integers <code>n</code>, <code>m</code>, <code>k</code>. A <strong>good array</strong> <code>arr</code> of size <code>n</code> is defined as follows:</p>
<ul>
<li>Each element in <code>arr</code> is in the <strong>inclusive</strong> range <code>[1, m]</code>.</li>
<li><em>Exactly</em> <code>k</code> indices <code>i</code> (where <code>1 <= i < n</code>) satisfy the condition <code>arr[i - 1] == arr[i]</code>.</li>
</ul>
<p>Return the number of <strong>good arrays</strong> that can be formed.</p>
<p>Since the answer may be very large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, m = 2, k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>There are 4 good arrays. They are <code>[1, 1, 2]</code>, <code>[1, 2, 2]</code>, <code>[2, 1, 1]</code> and <code>[2, 2, 1]</code>.</li>
<li>Hence, the answer is 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, m = 2, k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The good arrays are <code>[1, 1, 1, 2]</code>, <code>[1, 1, 2, 2]</code>, <code>[1, 2, 2, 2]</code>, <code>[2, 1, 1, 1]</code>, <code>[2, 2, 1, 1]</code> and <code>[2, 2, 2, 1]</code>.</li>
<li>Hence, the answer is 6.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, m = 2, k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The good arrays are <code>[1, 2, 1, 2, 1]</code> and <code>[2, 1, 2, 1, 2]</code>. Hence, the answer is 2.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= m <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= n - 1</code></li>
</ul>
|
Math; Combinatorics
|
Rust
|
impl Solution {
pub fn count_good_arrays(n: i32, m: i32, k: i32) -> i32 {
const N: usize = 1e5 as usize + 10;
const MOD: i64 = 1_000_000_007;
use std::sync::OnceLock;
static F: OnceLock<Vec<i64>> = OnceLock::new();
static G: OnceLock<Vec<i64>> = OnceLock::new();
fn qpow(mut a: i64, mut k: i64, m: i64) -> i64 {
let mut res = 1;
while k != 0 {
if k & 1 == 1 {
res = res * a % m;
}
a = a * a % m;
k >>= 1;
}
res
}
fn init() -> (&'static Vec<i64>, &'static Vec<i64>) {
F.get_or_init(|| {
let mut f = vec![1i64; N];
for i in 1..N {
f[i] = f[i - 1] * i as i64 % MOD;
}
f
});
G.get_or_init(|| {
let f = F.get().unwrap();
let mut g = vec![1i64; N];
for i in 1..N {
g[i] = qpow(f[i], MOD - 2, MOD);
}
g
});
(F.get().unwrap(), G.get().unwrap())
}
fn comb(f: &[i64], g: &[i64], m: usize, n: usize) -> i64 {
f[m] * g[n] % MOD * g[m - n] % MOD
}
let (f, g) = init();
let n = n as usize;
let m = m as i64;
let k = k as usize;
let c = comb(f, g, n - 1, k);
let pow = qpow(m - 1, (n - 1 - k) as i64, MOD);
(c * m % MOD * pow % MOD) as i32
}
}
|
3,405 |
Count the Number of Arrays with K Matching Adjacent Elements
|
Hard
|
<p>You are given three integers <code>n</code>, <code>m</code>, <code>k</code>. A <strong>good array</strong> <code>arr</code> of size <code>n</code> is defined as follows:</p>
<ul>
<li>Each element in <code>arr</code> is in the <strong>inclusive</strong> range <code>[1, m]</code>.</li>
<li><em>Exactly</em> <code>k</code> indices <code>i</code> (where <code>1 <= i < n</code>) satisfy the condition <code>arr[i - 1] == arr[i]</code>.</li>
</ul>
<p>Return the number of <strong>good arrays</strong> that can be formed.</p>
<p>Since the answer may be very large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 3, m = 2, k = 1</span></p>
<p><strong>Output:</strong> <span class="example-io">4</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>There are 4 good arrays. They are <code>[1, 1, 2]</code>, <code>[1, 2, 2]</code>, <code>[2, 1, 1]</code> and <code>[2, 2, 1]</code>.</li>
<li>Hence, the answer is 4.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 4, m = 2, k = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">6</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The good arrays are <code>[1, 1, 1, 2]</code>, <code>[1, 1, 2, 2]</code>, <code>[1, 2, 2, 2]</code>, <code>[2, 1, 1, 1]</code>, <code>[2, 2, 1, 1]</code> and <code>[2, 2, 2, 1]</code>.</li>
<li>Hence, the answer is 6.</li>
</ul>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 5, m = 2, k = 0</span></p>
<p><strong>Output:</strong> <span class="example-io">2</span></p>
<p><strong>Explanation:</strong></p>
<ul>
<li>The good arrays are <code>[1, 2, 1, 2, 1]</code> and <code>[2, 1, 2, 1, 2]</code>. Hence, the answer is 2.</li>
</ul>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= m <= 10<sup>5</sup></code></li>
<li><code>0 <= k <= n - 1</code></li>
</ul>
|
Math; Combinatorics
|
TypeScript
|
const MX = 1e5 + 10;
const MOD = BigInt(1e9 + 7);
const f: bigint[] = Array(MX).fill(1n);
const g: bigint[] = Array(MX).fill(1n);
function qpow(a: bigint, k: number): bigint {
let res = 1n;
while (k !== 0) {
if ((k & 1) === 1) {
res = (res * a) % MOD;
}
a = (a * a) % MOD;
k >>= 1;
}
return res;
}
(function init() {
for (let i = 1; i < MX; ++i) {
f[i] = (f[i - 1] * BigInt(i)) % MOD;
g[i] = qpow(f[i], Number(MOD - 2n));
}
})();
function comb(m: number, n: number): bigint {
return (((f[m] * g[n]) % MOD) * g[m - n]) % MOD;
}
export function countGoodArrays(n: number, m: number, k: number): number {
const ans = (((comb(n - 1, k) * BigInt(m)) % MOD) * qpow(BigInt(m - 1), n - k - 1)) % MOD;
return Number(ans);
}
|
3,406 |
Find the Lexicographically Largest String From the Box II
|
Hard
|
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p>
<p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p>
<ul>
<li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li>
<li>All the split words are put into a box.</li>
</ul>
<p>Find the <strong>lexicographically largest</strong> string from the box after all the rounds are finished.</p>
<p>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.<br />
If the first <code>min(a.length, b.length)</code> characters do not differ, then the shorter string is the lexicographically smaller one.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "dbca", numFriends = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"dbc"</span></p>
<p><strong>Explanation:</strong></p>
<p>All possible splits are:</p>
<ul>
<li><code>"d"</code> and <code>"bca"</code>.</li>
<li><code>"db"</code> and <code>"ca"</code>.</li>
<li><code>"dbc"</code> and <code>"a"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "gggg", numFriends = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"g"</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible split is: <code>"g"</code>, <code>"g"</code>, <code>"g"</code>, and <code>"g"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>1 <= numFriends <= word.length</code></li>
</ul>
|
Two Pointers; String
|
C++
|
class Solution {
public:
string answerString(string word, int numFriends) {
if (numFriends == 1) {
return word;
}
string s = lastSubstring(word);
return s.substr(0, min(s.length(), word.length() - numFriends + 1));
}
string lastSubstring(string& s) {
int n = s.size();
int i = 0, j = 1, k = 0;
while (j + k < n) {
if (s[i + k] == s[j + k]) {
++k;
} else if (s[i + k] < s[j + k]) {
i += k + 1;
k = 0;
if (i >= j) {
j = i + 1;
}
} else {
j += k + 1;
k = 0;
}
}
return s.substr(i);
}
};
|
3,406 |
Find the Lexicographically Largest String From the Box II
|
Hard
|
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p>
<p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p>
<ul>
<li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li>
<li>All the split words are put into a box.</li>
</ul>
<p>Find the <strong>lexicographically largest</strong> string from the box after all the rounds are finished.</p>
<p>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.<br />
If the first <code>min(a.length, b.length)</code> characters do not differ, then the shorter string is the lexicographically smaller one.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "dbca", numFriends = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"dbc"</span></p>
<p><strong>Explanation:</strong></p>
<p>All possible splits are:</p>
<ul>
<li><code>"d"</code> and <code>"bca"</code>.</li>
<li><code>"db"</code> and <code>"ca"</code>.</li>
<li><code>"dbc"</code> and <code>"a"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "gggg", numFriends = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"g"</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible split is: <code>"g"</code>, <code>"g"</code>, <code>"g"</code>, and <code>"g"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>1 <= numFriends <= word.length</code></li>
</ul>
|
Two Pointers; String
|
Go
|
func answerString(word string, numFriends int) string {
if numFriends == 1 {
return word
}
s := lastSubstring(word)
return s[:min(len(s), len(word)-numFriends+1)]
}
func lastSubstring(s string) string {
n := len(s)
i, j, k := 0, 1, 0
for j+k < n {
if s[i+k] == s[j+k] {
k++
} else if s[i+k] < s[j+k] {
i += k + 1
k = 0
if i >= j {
j = i + 1
}
} else {
j += k + 1
k = 0
}
}
return s[i:]
}
|
3,406 |
Find the Lexicographically Largest String From the Box II
|
Hard
|
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p>
<p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p>
<ul>
<li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li>
<li>All the split words are put into a box.</li>
</ul>
<p>Find the <strong>lexicographically largest</strong> string from the box after all the rounds are finished.</p>
<p>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.<br />
If the first <code>min(a.length, b.length)</code> characters do not differ, then the shorter string is the lexicographically smaller one.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "dbca", numFriends = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"dbc"</span></p>
<p><strong>Explanation:</strong></p>
<p>All possible splits are:</p>
<ul>
<li><code>"d"</code> and <code>"bca"</code>.</li>
<li><code>"db"</code> and <code>"ca"</code>.</li>
<li><code>"dbc"</code> and <code>"a"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "gggg", numFriends = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"g"</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible split is: <code>"g"</code>, <code>"g"</code>, <code>"g"</code>, and <code>"g"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>1 <= numFriends <= word.length</code></li>
</ul>
|
Two Pointers; String
|
Java
|
class Solution {
public String answerString(String word, int numFriends) {
if (numFriends == 1) {
return word;
}
String s = lastSubstring(word);
return s.substring(0, Math.min(s.length(), word.length() - numFriends + 1));
}
public String lastSubstring(String s) {
int n = s.length();
int i = 0, j = 1, k = 0;
while (j + k < n) {
int d = s.charAt(i + k) - s.charAt(j + k);
if (d == 0) {
++k;
} else if (d < 0) {
i += k + 1;
k = 0;
if (i >= j) {
j = i + 1;
}
} else {
j += k + 1;
k = 0;
}
}
return s.substring(i);
}
}
|
3,406 |
Find the Lexicographically Largest String From the Box II
|
Hard
|
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p>
<p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p>
<ul>
<li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li>
<li>All the split words are put into a box.</li>
</ul>
<p>Find the <strong>lexicographically largest</strong> string from the box after all the rounds are finished.</p>
<p>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.<br />
If the first <code>min(a.length, b.length)</code> characters do not differ, then the shorter string is the lexicographically smaller one.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "dbca", numFriends = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"dbc"</span></p>
<p><strong>Explanation:</strong></p>
<p>All possible splits are:</p>
<ul>
<li><code>"d"</code> and <code>"bca"</code>.</li>
<li><code>"db"</code> and <code>"ca"</code>.</li>
<li><code>"dbc"</code> and <code>"a"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "gggg", numFriends = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"g"</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible split is: <code>"g"</code>, <code>"g"</code>, <code>"g"</code>, and <code>"g"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>1 <= numFriends <= word.length</code></li>
</ul>
|
Two Pointers; String
|
Python
|
class Solution:
def answerString(self, word: str, numFriends: int) -> str:
if numFriends == 1:
return word
s = self.lastSubstring(word)
return s[: len(word) - numFriends + 1]
def lastSubstring(self, s: str) -> str:
i, j, k = 0, 1, 0
while j + k < len(s):
if s[i + k] == s[j + k]:
k += 1
elif s[i + k] < s[j + k]:
i += k + 1
k = 0
if i >= j:
j = i + 1
else:
j += k + 1
k = 0
return s[i:]
|
3,406 |
Find the Lexicographically Largest String From the Box II
|
Hard
|
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p>
<p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p>
<ul>
<li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li>
<li>All the split words are put into a box.</li>
</ul>
<p>Find the <strong>lexicographically largest</strong> string from the box after all the rounds are finished.</p>
<p>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.<br />
If the first <code>min(a.length, b.length)</code> characters do not differ, then the shorter string is the lexicographically smaller one.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "dbca", numFriends = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">"dbc"</span></p>
<p><strong>Explanation:</strong></p>
<p>All possible splits are:</p>
<ul>
<li><code>"d"</code> and <code>"bca"</code>.</li>
<li><code>"db"</code> and <code>"ca"</code>.</li>
<li><code>"dbc"</code> and <code>"a"</code>.</li>
</ul>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">word = "gggg", numFriends = 4</span></p>
<p><strong>Output:</strong> <span class="example-io">"g"</span></p>
<p><strong>Explanation:</strong></p>
<p>The only possible split is: <code>"g"</code>, <code>"g"</code>, <code>"g"</code>, and <code>"g"</code>.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= word.length <= 2 * 10<sup>5</sup></code></li>
<li><code>word</code> consists only of lowercase English letters.</li>
<li><code>1 <= numFriends <= word.length</code></li>
</ul>
|
Two Pointers; String
|
TypeScript
|
function answerString(word: string, numFriends: number): string {
if (numFriends === 1) {
return word;
}
const s = lastSubstring(word);
return s.slice(0, word.length - numFriends + 1);
}
function lastSubstring(s: string): string {
const n = s.length;
let i = 0;
for (let j = 1, k = 0; j + k < n; ) {
if (s[i + k] === s[j + k]) {
++k;
} else if (s[i + k] < s[j + k]) {
i += k + 1;
k = 0;
if (i >= j) {
j = i + 1;
}
} else {
j += k + 1;
k = 0;
}
}
return s.slice(i);
}
|
3,407 |
Substring Matching Pattern
|
Easy
|
<p>You are given a string <code>s</code> and a pattern string <code>p</code>, where <code>p</code> contains <strong>exactly one</strong> <code>'*'</code> character.</p>
<p>The <code>'*'</code> in <code>p</code> can be replaced with any sequence of zero or more characters.</p>
<p>Return <code>true</code> if <code>p</code> can be made a <span data-keyword="substring-nonempty">substring</span> of <code>s</code>, and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode", p = "ee*e"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>By replacing the <code>'*'</code> with <code>"tcod"</code>, the substring <code>"eetcode"</code> matches the pattern.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "car", p = "c*v"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring matching the pattern.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "luck", p = "u*"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>The substrings <code>"u"</code>, <code>"uc"</code>, and <code>"uck"</code> match the pattern.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50</code></li>
<li><code>1 <= p.length <= 50 </code></li>
<li><code>s</code> contains only lowercase English letters.</li>
<li><code>p</code> contains only lowercase English letters and exactly one <code>'*'</code></li>
</ul>
|
String; String Matching
|
C++
|
class Solution {
public:
bool hasMatch(string s, string p) {
int i = 0;
int pos = 0;
int start = 0, end;
while ((end = p.find("*", start)) != string::npos) {
string t = p.substr(start, end - start);
pos = s.find(t, i);
if (pos == string::npos) {
return false;
}
i = pos + t.length();
start = end + 1;
}
string t = p.substr(start);
pos = s.find(t, i);
if (pos == string::npos) {
return false;
}
return true;
}
};
|
3,407 |
Substring Matching Pattern
|
Easy
|
<p>You are given a string <code>s</code> and a pattern string <code>p</code>, where <code>p</code> contains <strong>exactly one</strong> <code>'*'</code> character.</p>
<p>The <code>'*'</code> in <code>p</code> can be replaced with any sequence of zero or more characters.</p>
<p>Return <code>true</code> if <code>p</code> can be made a <span data-keyword="substring-nonempty">substring</span> of <code>s</code>, and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode", p = "ee*e"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>By replacing the <code>'*'</code> with <code>"tcod"</code>, the substring <code>"eetcode"</code> matches the pattern.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "car", p = "c*v"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring matching the pattern.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "luck", p = "u*"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>The substrings <code>"u"</code>, <code>"uc"</code>, and <code>"uck"</code> match the pattern.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50</code></li>
<li><code>1 <= p.length <= 50 </code></li>
<li><code>s</code> contains only lowercase English letters.</li>
<li><code>p</code> contains only lowercase English letters and exactly one <code>'*'</code></li>
</ul>
|
String; String Matching
|
Go
|
func hasMatch(s string, p string) bool {
i := 0
for _, t := range strings.Split(p, "*") {
j := strings.Index(s[i:], t)
if j == -1 {
return false
}
i += j + len(t)
}
return true
}
|
3,407 |
Substring Matching Pattern
|
Easy
|
<p>You are given a string <code>s</code> and a pattern string <code>p</code>, where <code>p</code> contains <strong>exactly one</strong> <code>'*'</code> character.</p>
<p>The <code>'*'</code> in <code>p</code> can be replaced with any sequence of zero or more characters.</p>
<p>Return <code>true</code> if <code>p</code> can be made a <span data-keyword="substring-nonempty">substring</span> of <code>s</code>, and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode", p = "ee*e"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>By replacing the <code>'*'</code> with <code>"tcod"</code>, the substring <code>"eetcode"</code> matches the pattern.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "car", p = "c*v"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring matching the pattern.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "luck", p = "u*"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>The substrings <code>"u"</code>, <code>"uc"</code>, and <code>"uck"</code> match the pattern.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50</code></li>
<li><code>1 <= p.length <= 50 </code></li>
<li><code>s</code> contains only lowercase English letters.</li>
<li><code>p</code> contains only lowercase English letters and exactly one <code>'*'</code></li>
</ul>
|
String; String Matching
|
Java
|
class Solution {
public boolean hasMatch(String s, String p) {
int i = 0;
for (String t : p.split("\\*")) {
int j = s.indexOf(t, i);
if (j == -1) {
return false;
}
i = j + t.length();
}
return true;
}
}
|
3,407 |
Substring Matching Pattern
|
Easy
|
<p>You are given a string <code>s</code> and a pattern string <code>p</code>, where <code>p</code> contains <strong>exactly one</strong> <code>'*'</code> character.</p>
<p>The <code>'*'</code> in <code>p</code> can be replaced with any sequence of zero or more characters.</p>
<p>Return <code>true</code> if <code>p</code> can be made a <span data-keyword="substring-nonempty">substring</span> of <code>s</code>, and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode", p = "ee*e"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>By replacing the <code>'*'</code> with <code>"tcod"</code>, the substring <code>"eetcode"</code> matches the pattern.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "car", p = "c*v"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring matching the pattern.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "luck", p = "u*"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>The substrings <code>"u"</code>, <code>"uc"</code>, and <code>"uck"</code> match the pattern.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50</code></li>
<li><code>1 <= p.length <= 50 </code></li>
<li><code>s</code> contains only lowercase English letters.</li>
<li><code>p</code> contains only lowercase English letters and exactly one <code>'*'</code></li>
</ul>
|
String; String Matching
|
Python
|
class Solution:
def hasMatch(self, s: str, p: str) -> bool:
i = 0
for t in p.split("*"):
j = s.find(t, i)
if j == -1:
return False
i = j + len(t)
return True
|
3,407 |
Substring Matching Pattern
|
Easy
|
<p>You are given a string <code>s</code> and a pattern string <code>p</code>, where <code>p</code> contains <strong>exactly one</strong> <code>'*'</code> character.</p>
<p>The <code>'*'</code> in <code>p</code> can be replaced with any sequence of zero or more characters.</p>
<p>Return <code>true</code> if <code>p</code> can be made a <span data-keyword="substring-nonempty">substring</span> of <code>s</code>, and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "leetcode", p = "ee*e"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>By replacing the <code>'*'</code> with <code>"tcod"</code>, the substring <code>"eetcode"</code> matches the pattern.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "car", p = "c*v"</span></p>
<p><strong>Output:</strong> <span class="example-io">false</span></p>
<p><strong>Explanation:</strong></p>
<p>There is no substring matching the pattern.</p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = "luck", p = "u*"</span></p>
<p><strong>Output:</strong> <span class="example-io">true</span></p>
<p><strong>Explanation:</strong></p>
<p>The substrings <code>"u"</code>, <code>"uc"</code>, and <code>"uck"</code> match the pattern.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 50</code></li>
<li><code>1 <= p.length <= 50 </code></li>
<li><code>s</code> contains only lowercase English letters.</li>
<li><code>p</code> contains only lowercase English letters and exactly one <code>'*'</code></li>
</ul>
|
String; String Matching
|
TypeScript
|
function hasMatch(s: string, p: string): boolean {
let i = 0;
for (const t of p.split('*')) {
const j = s.indexOf(t, i);
if (j === -1) {
return false;
}
i = j + t.length;
}
return true;
}
|
3,408 |
Design Task Manager
|
Medium
|
<p>There is a task management system that allows users to manage their tasks, each associated with a priority. The system should efficiently handle adding, modifying, executing, and removing tasks.</p>
<p>Implement the <code>TaskManager</code> class:</p>
<ul>
<li>
<p><code>TaskManager(vector<vector<int>>& tasks)</code> initializes the task manager with a list of user-task-priority triples. Each element in the input list is of the form <code>[userId, taskId, priority]</code>, which adds a task to the specified user with the given priority.</p>
</li>
<li>
<p><code>void add(int userId, int taskId, int priority)</code> adds a task with the specified <code>taskId</code> and <code>priority</code> to the user with <code>userId</code>. It is <strong>guaranteed</strong> that <code>taskId</code> does not <em>exist</em> in the system.</p>
</li>
<li>
<p><code>void edit(int taskId, int newPriority)</code> updates the priority of the existing <code>taskId</code> to <code>newPriority</code>. It is <strong>guaranteed</strong> that <code>taskId</code> <em>exists</em> in the system.</p>
</li>
<li>
<p><code>void rmv(int taskId)</code> removes the task identified by <code>taskId</code> from the system. It is <strong>guaranteed</strong> that <code>taskId</code> <em>exists</em> in the system.</p>
</li>
<li>
<p><code>int execTop()</code> executes the task with the <strong>highest</strong> priority across all users. If there are multiple tasks with the same <strong>highest</strong> priority, execute the one with the highest <code>taskId</code>. After executing, the<strong> </strong><code>taskId</code><strong> </strong>is <strong>removed</strong> from the system. Return the <code>userId</code> associated with the executed task. If no tasks are available, return -1.</p>
</li>
</ul>
<p><strong>Note</strong> that a user may be assigned multiple tasks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["TaskManager", "add", "edit", "execTop", "rmv", "add", "execTop"]<br />
[[[[1, 101, 10], [2, 102, 20], [3, 103, 15]]], [4, 104, 5], [102, 8], [], [101], [5, 105, 15], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, null, 3, null, null, 5] </span></p>
<p><strong>Explanation</strong></p>
TaskManager taskManager = new TaskManager([[1, 101, 10], [2, 102, 20], [3, 103, 15]]); // Initializes with three tasks for Users 1, 2, and 3.<br />
taskManager.add(4, 104, 5); // Adds task 104 with priority 5 for User 4.<br />
taskManager.edit(102, 8); // Updates priority of task 102 to 8.<br />
taskManager.execTop(); // return 3. Executes task 103 for User 3.<br />
taskManager.rmv(101); // Removes task 101 from the system.<br />
taskManager.add(5, 105, 15); // Adds task 105 with priority 15 for User 5.<br />
taskManager.execTop(); // return 5. Executes task 105 for User 5.</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= tasks.length <= 10<sup>5</sup></code></li>
<li><code>0 <= userId <= 10<sup>5</sup></code></li>
<li><code>0 <= taskId <= 10<sup>5</sup></code></li>
<li><code>0 <= priority <= 10<sup>9</sup></code></li>
<li><code>0 <= newPriority <= 10<sup>9</sup></code></li>
<li>At most <code>2 * 10<sup>5</sup></code> calls will be made in <strong>total</strong> to <code>add</code>, <code>edit</code>, <code>rmv</code>, and <code>execTop</code> methods.</li>
<li>The input is generated such that <code>taskId</code> will be valid.</li>
</ul>
|
Design; Hash Table; Ordered Set; Heap (Priority Queue)
|
C++
|
class TaskManager {
private:
unordered_map<int, pair<int, int>> d;
set<pair<int, int>> st;
public:
TaskManager(vector<vector<int>>& tasks) {
for (const auto& task : tasks) {
add(task[0], task[1], task[2]);
}
}
void add(int userId, int taskId, int priority) {
d[taskId] = {userId, priority};
st.insert({-priority, -taskId});
}
void edit(int taskId, int newPriority) {
auto [userId, priority] = d[taskId];
st.erase({-priority, -taskId});
st.insert({-newPriority, -taskId});
d[taskId] = {userId, newPriority};
}
void rmv(int taskId) {
auto [userId, priority] = d[taskId];
st.erase({-priority, -taskId});
d.erase(taskId);
}
int execTop() {
if (st.empty()) {
return -1;
}
auto e = *st.begin();
st.erase(st.begin());
int taskId = -e.second;
int userId = d[taskId].first;
d.erase(taskId);
return userId;
}
};
/**
* Your TaskManager object will be instantiated and called as such:
* TaskManager* obj = new TaskManager(tasks);
* obj->add(userId,taskId,priority);
* obj->edit(taskId,newPriority);
* obj->rmv(taskId);
* int param_4 = obj->execTop();
*/
|
3,408 |
Design Task Manager
|
Medium
|
<p>There is a task management system that allows users to manage their tasks, each associated with a priority. The system should efficiently handle adding, modifying, executing, and removing tasks.</p>
<p>Implement the <code>TaskManager</code> class:</p>
<ul>
<li>
<p><code>TaskManager(vector<vector<int>>& tasks)</code> initializes the task manager with a list of user-task-priority triples. Each element in the input list is of the form <code>[userId, taskId, priority]</code>, which adds a task to the specified user with the given priority.</p>
</li>
<li>
<p><code>void add(int userId, int taskId, int priority)</code> adds a task with the specified <code>taskId</code> and <code>priority</code> to the user with <code>userId</code>. It is <strong>guaranteed</strong> that <code>taskId</code> does not <em>exist</em> in the system.</p>
</li>
<li>
<p><code>void edit(int taskId, int newPriority)</code> updates the priority of the existing <code>taskId</code> to <code>newPriority</code>. It is <strong>guaranteed</strong> that <code>taskId</code> <em>exists</em> in the system.</p>
</li>
<li>
<p><code>void rmv(int taskId)</code> removes the task identified by <code>taskId</code> from the system. It is <strong>guaranteed</strong> that <code>taskId</code> <em>exists</em> in the system.</p>
</li>
<li>
<p><code>int execTop()</code> executes the task with the <strong>highest</strong> priority across all users. If there are multiple tasks with the same <strong>highest</strong> priority, execute the one with the highest <code>taskId</code>. After executing, the<strong> </strong><code>taskId</code><strong> </strong>is <strong>removed</strong> from the system. Return the <code>userId</code> associated with the executed task. If no tasks are available, return -1.</p>
</li>
</ul>
<p><strong>Note</strong> that a user may be assigned multiple tasks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["TaskManager", "add", "edit", "execTop", "rmv", "add", "execTop"]<br />
[[[[1, 101, 10], [2, 102, 20], [3, 103, 15]]], [4, 104, 5], [102, 8], [], [101], [5, 105, 15], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, null, 3, null, null, 5] </span></p>
<p><strong>Explanation</strong></p>
TaskManager taskManager = new TaskManager([[1, 101, 10], [2, 102, 20], [3, 103, 15]]); // Initializes with three tasks for Users 1, 2, and 3.<br />
taskManager.add(4, 104, 5); // Adds task 104 with priority 5 for User 4.<br />
taskManager.edit(102, 8); // Updates priority of task 102 to 8.<br />
taskManager.execTop(); // return 3. Executes task 103 for User 3.<br />
taskManager.rmv(101); // Removes task 101 from the system.<br />
taskManager.add(5, 105, 15); // Adds task 105 with priority 15 for User 5.<br />
taskManager.execTop(); // return 5. Executes task 105 for User 5.</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= tasks.length <= 10<sup>5</sup></code></li>
<li><code>0 <= userId <= 10<sup>5</sup></code></li>
<li><code>0 <= taskId <= 10<sup>5</sup></code></li>
<li><code>0 <= priority <= 10<sup>9</sup></code></li>
<li><code>0 <= newPriority <= 10<sup>9</sup></code></li>
<li>At most <code>2 * 10<sup>5</sup></code> calls will be made in <strong>total</strong> to <code>add</code>, <code>edit</code>, <code>rmv</code>, and <code>execTop</code> methods.</li>
<li>The input is generated such that <code>taskId</code> will be valid.</li>
</ul>
|
Design; Hash Table; Ordered Set; Heap (Priority Queue)
|
Java
|
class TaskManager {
private final Map<Integer, int[]> d = new HashMap<>();
private final TreeSet<int[]> st = new TreeSet<>((a, b) -> {
if (a[0] == b[0]) {
return b[1] - a[1];
}
return b[0] - a[0];
});
public TaskManager(List<List<Integer>> tasks) {
for (var task : tasks) {
add(task.get(0), task.get(1), task.get(2));
}
}
public void add(int userId, int taskId, int priority) {
d.put(taskId, new int[] {userId, priority});
st.add(new int[] {priority, taskId});
}
public void edit(int taskId, int newPriority) {
var e = d.get(taskId);
int userId = e[0], priority = e[1];
st.remove(new int[] {priority, taskId});
st.add(new int[] {newPriority, taskId});
d.put(taskId, new int[] {userId, newPriority});
}
public void rmv(int taskId) {
var e = d.remove(taskId);
int priority = e[1];
st.remove(new int[] {priority, taskId});
}
public int execTop() {
if (st.isEmpty()) {
return -1;
}
var e = st.pollFirst();
var t = d.remove(e[1]);
return t[0];
}
}
/**
* Your TaskManager object will be instantiated and called as such:
* TaskManager obj = new TaskManager(tasks);
* obj.add(userId,taskId,priority);
* obj.edit(taskId,newPriority);
* obj.rmv(taskId);
* int param_4 = obj.execTop();
*/
|
3,408 |
Design Task Manager
|
Medium
|
<p>There is a task management system that allows users to manage their tasks, each associated with a priority. The system should efficiently handle adding, modifying, executing, and removing tasks.</p>
<p>Implement the <code>TaskManager</code> class:</p>
<ul>
<li>
<p><code>TaskManager(vector<vector<int>>& tasks)</code> initializes the task manager with a list of user-task-priority triples. Each element in the input list is of the form <code>[userId, taskId, priority]</code>, which adds a task to the specified user with the given priority.</p>
</li>
<li>
<p><code>void add(int userId, int taskId, int priority)</code> adds a task with the specified <code>taskId</code> and <code>priority</code> to the user with <code>userId</code>. It is <strong>guaranteed</strong> that <code>taskId</code> does not <em>exist</em> in the system.</p>
</li>
<li>
<p><code>void edit(int taskId, int newPriority)</code> updates the priority of the existing <code>taskId</code> to <code>newPriority</code>. It is <strong>guaranteed</strong> that <code>taskId</code> <em>exists</em> in the system.</p>
</li>
<li>
<p><code>void rmv(int taskId)</code> removes the task identified by <code>taskId</code> from the system. It is <strong>guaranteed</strong> that <code>taskId</code> <em>exists</em> in the system.</p>
</li>
<li>
<p><code>int execTop()</code> executes the task with the <strong>highest</strong> priority across all users. If there are multiple tasks with the same <strong>highest</strong> priority, execute the one with the highest <code>taskId</code>. After executing, the<strong> </strong><code>taskId</code><strong> </strong>is <strong>removed</strong> from the system. Return the <code>userId</code> associated with the executed task. If no tasks are available, return -1.</p>
</li>
</ul>
<p><strong>Note</strong> that a user may be assigned multiple tasks.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong><br />
<span class="example-io">["TaskManager", "add", "edit", "execTop", "rmv", "add", "execTop"]<br />
[[[[1, 101, 10], [2, 102, 20], [3, 103, 15]]], [4, 104, 5], [102, 8], [], [101], [5, 105, 15], []]</span></p>
<p><strong>Output:</strong><br />
<span class="example-io">[null, null, null, 3, null, null, 5] </span></p>
<p><strong>Explanation</strong></p>
TaskManager taskManager = new TaskManager([[1, 101, 10], [2, 102, 20], [3, 103, 15]]); // Initializes with three tasks for Users 1, 2, and 3.<br />
taskManager.add(4, 104, 5); // Adds task 104 with priority 5 for User 4.<br />
taskManager.edit(102, 8); // Updates priority of task 102 to 8.<br />
taskManager.execTop(); // return 3. Executes task 103 for User 3.<br />
taskManager.rmv(101); // Removes task 101 from the system.<br />
taskManager.add(5, 105, 15); // Adds task 105 with priority 15 for User 5.<br />
taskManager.execTop(); // return 5. Executes task 105 for User 5.</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= tasks.length <= 10<sup>5</sup></code></li>
<li><code>0 <= userId <= 10<sup>5</sup></code></li>
<li><code>0 <= taskId <= 10<sup>5</sup></code></li>
<li><code>0 <= priority <= 10<sup>9</sup></code></li>
<li><code>0 <= newPriority <= 10<sup>9</sup></code></li>
<li>At most <code>2 * 10<sup>5</sup></code> calls will be made in <strong>total</strong> to <code>add</code>, <code>edit</code>, <code>rmv</code>, and <code>execTop</code> methods.</li>
<li>The input is generated such that <code>taskId</code> will be valid.</li>
</ul>
|
Design; Hash Table; Ordered Set; Heap (Priority Queue)
|
Python
|
class TaskManager:
def __init__(self, tasks: List[List[int]]):
self.d = {}
self.st = SortedList()
for task in tasks:
self.add(*task)
def add(self, userId: int, taskId: int, priority: int) -> None:
self.d[taskId] = (userId, priority)
self.st.add((-priority, -taskId))
def edit(self, taskId: int, newPriority: int) -> None:
userId, priority = self.d[taskId]
self.st.discard((-priority, -taskId))
self.d[taskId] = (userId, newPriority)
self.st.add((-newPriority, -taskId))
def rmv(self, taskId: int) -> None:
_, priority = self.d[taskId]
self.d.pop(taskId)
self.st.remove((-priority, -taskId))
def execTop(self) -> int:
if not self.st:
return -1
taskId = -self.st.pop(0)[1]
userId, _ = self.d[taskId]
self.d.pop(taskId)
return userId
# Your TaskManager object will be instantiated and called as such:
# obj = TaskManager(tasks)
# obj.add(userId,taskId,priority)
# obj.edit(taskId,newPriority)
# obj.rmv(taskId)
# param_4 = obj.execTop()
|
3,411 |
Maximum Subarray With Equal Products
|
Easy
|
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p>
<p>An array <code>arr</code> is called <strong>product equivalent</strong> if <code>prod(arr) == lcm(arr) * gcd(arr)</code>, where:</p>
<ul>
<li><code>prod(arr)</code> is the product of all elements of <code>arr</code>.</li>
<li><code>gcd(arr)</code> is the <span data-keyword="gcd-function">GCD</span> of all elements of <code>arr</code>.</li>
<li><code>lcm(arr)</code> is the <span data-keyword="lcm-function">LCM</span> of all elements of <code>arr</code>.</li>
</ul>
<p>Return the length of the <strong>longest</strong> <strong>product equivalent</strong> <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,2,1,1,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
<p><strong>Explanation:</strong> </p>
<p>The longest product equivalent subarray is <code>[1, 2, 1, 1, 1]</code>, where <code>prod([1, 2, 1, 1, 1]) = 2</code>, <code>gcd([1, 2, 1, 1, 1]) = 1</code>, and <code>lcm([1, 2, 1, 1, 1]) = 2</code>.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,5,6]</span></p>
<p><strong>Output:</strong> <span class="example-io">3</span></p>
<p><strong>Explanation:</strong> </p>
<p>The longest product equivalent subarray is <code>[3, 4, 5].</code></p>
</div>
<p><strong class="example">Example 3:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1,4,5,1]</span></p>
<p><strong>Output:</strong> <span class="example-io">5</span></p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= nums.length <= 100</code></li>
<li><code>1 <= nums[i] <= 10</code></li>
</ul>
|
Array; Math; Enumeration; Number Theory; Sliding Window
|
C++
|
class Solution {
public:
int maxLength(vector<int>& nums) {
int mx = 0, ml = 1;
for (int x : nums) {
mx = max(mx, x);
ml = lcm(ml, x);
}
long long maxP = (long long) ml * mx;
int n = nums.size();
int ans = 0;
for (int i = 0; i < n; ++i) {
long long p = 1, g = 0, l = 1;
for (int j = i; j < n; ++j) {
p *= nums[j];
g = gcd(g, nums[j]);
l = lcm(l, nums[j]);
if (p == g * l) {
ans = max(ans, j - i + 1);
}
if (p > maxP) {
break;
}
}
}
return ans;
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.