id
int64 1
3.71k
| 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
|
|---|---|---|---|---|---|---|
2,581
|
Count Number of Possible Root Nodes
|
Hard
|
<p>Alice has an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. The tree is represented as a 2D integer array <code>edges</code> of length <code>n - 1</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>Alice wants Bob to find the root of the tree. She allows Bob to make several <strong>guesses</strong> about her tree. In one guess, he does the following:</p>
<ul>
<li>Chooses two <strong>distinct</strong> integers <code>u</code> and <code>v</code> such that there exists an edge <code>[u, v]</code> in the tree.</li>
<li>He tells Alice that <code>u</code> is the <strong>parent</strong> of <code>v</code> in the tree.</li>
</ul>
<p>Bob's guesses are represented by a 2D integer array <code>guesses</code> where <code>guesses[j] = [u<sub>j</sub>, v<sub>j</sub>]</code> indicates Bob guessed <code>u<sub>j</sub></code> to be the parent of <code>v<sub>j</sub></code>.</p>
<p>Alice being lazy, does not reply to each of Bob's guesses, but just says that <strong>at least</strong> <code>k</code> of his guesses are <code>true</code>.</p>
<p>Given the 2D integer arrays <code>edges</code>, <code>guesses</code> and the integer <code>k</code>, return <em>the <strong>number of possible nodes</strong> that can be the root of Alice's tree</em>. If there is no such tree, return <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2581.Count%20Number%20of%20Possible%20Root%20Nodes/images/ex-1.png" style="width: 727px; height: 250px;" /></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[1,3],[4,2]], guesses = [[1,3],[0,1],[1,0],[2,4]], k = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Root = 0, correct guesses = [1,3], [0,1], [2,4]
Root = 1, correct guesses = [1,3], [1,0], [2,4]
Root = 2, correct guesses = [1,3], [1,0], [2,4]
Root = 3, correct guesses = [1,0], [2,4]
Root = 4, correct guesses = [1,3], [1,0]
Considering 0, 1, or 2 as root node leads to 3 correct guesses.
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2581.Count%20Number%20of%20Possible%20Root%20Nodes/images/ex-2.png" style="width: 600px; height: 303px;" /></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[2,3],[3,4]], guesses = [[1,0],[3,4],[2,1],[3,2]], k = 1
<strong>Output:</strong> 5
<strong>Explanation:</strong>
Root = 0, correct guesses = [3,4]
Root = 1, correct guesses = [1,0], [3,4]
Root = 2, correct guesses = [1,0], [2,1], [3,4]
Root = 3, correct guesses = [1,0], [2,1], [3,2], [3,4]
Root = 4, correct guesses = [1,0], [2,1], [3,2]
Considering any node as root will give at least 1 correct guess.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>edges.length == n - 1</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= guesses.length <= 10<sup>5</sup></code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub>, u<sub>j</sub>, v<sub>j</sub> <= n - 1</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li><code>u<sub>j</sub> != v<sub>j</sub></code></li>
<li><code>edges</code> represents a valid tree.</li>
<li><code>guesses[j]</code> is an edge of the tree.</li>
<li><code>guesses</code> is unique.</li>
<li><code>0 <= k <= guesses.length</code></li>
</ul>
|
Tree; Depth-First Search; Array; Hash Table; Dynamic Programming
|
C++
|
class Solution {
public:
int rootCount(vector<vector<int>>& edges, vector<vector<int>>& guesses, int k) {
int n = edges.size() + 1;
vector<int> g[n];
unordered_map<long long, int> gs;
auto f = [&](int i, int j) {
return 1LL * i * n + j;
};
for (auto& e : edges) {
int a = e[0], b = e[1];
g[a].push_back(b);
g[b].push_back(a);
}
for (auto& e : guesses) {
int a = e[0], b = e[1];
gs[f(a, b)]++;
}
int ans = 0;
int cnt = 0;
function<void(int, int)> dfs1 = [&](int i, int fa) {
for (int& j : g[i]) {
if (j != fa) {
cnt += gs[f(i, j)];
dfs1(j, i);
}
}
};
function<void(int, int)> dfs2 = [&](int i, int fa) {
ans += cnt >= k;
for (int& j : g[i]) {
if (j != fa) {
int a = gs[f(i, j)];
int b = gs[f(j, i)];
cnt -= a;
cnt += b;
dfs2(j, i);
cnt -= b;
cnt += a;
}
}
};
dfs1(0, -1);
dfs2(0, -1);
return ans;
}
};
|
2,581
|
Count Number of Possible Root Nodes
|
Hard
|
<p>Alice has an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. The tree is represented as a 2D integer array <code>edges</code> of length <code>n - 1</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>Alice wants Bob to find the root of the tree. She allows Bob to make several <strong>guesses</strong> about her tree. In one guess, he does the following:</p>
<ul>
<li>Chooses two <strong>distinct</strong> integers <code>u</code> and <code>v</code> such that there exists an edge <code>[u, v]</code> in the tree.</li>
<li>He tells Alice that <code>u</code> is the <strong>parent</strong> of <code>v</code> in the tree.</li>
</ul>
<p>Bob's guesses are represented by a 2D integer array <code>guesses</code> where <code>guesses[j] = [u<sub>j</sub>, v<sub>j</sub>]</code> indicates Bob guessed <code>u<sub>j</sub></code> to be the parent of <code>v<sub>j</sub></code>.</p>
<p>Alice being lazy, does not reply to each of Bob's guesses, but just says that <strong>at least</strong> <code>k</code> of his guesses are <code>true</code>.</p>
<p>Given the 2D integer arrays <code>edges</code>, <code>guesses</code> and the integer <code>k</code>, return <em>the <strong>number of possible nodes</strong> that can be the root of Alice's tree</em>. If there is no such tree, return <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2581.Count%20Number%20of%20Possible%20Root%20Nodes/images/ex-1.png" style="width: 727px; height: 250px;" /></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[1,3],[4,2]], guesses = [[1,3],[0,1],[1,0],[2,4]], k = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Root = 0, correct guesses = [1,3], [0,1], [2,4]
Root = 1, correct guesses = [1,3], [1,0], [2,4]
Root = 2, correct guesses = [1,3], [1,0], [2,4]
Root = 3, correct guesses = [1,0], [2,4]
Root = 4, correct guesses = [1,3], [1,0]
Considering 0, 1, or 2 as root node leads to 3 correct guesses.
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2581.Count%20Number%20of%20Possible%20Root%20Nodes/images/ex-2.png" style="width: 600px; height: 303px;" /></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[2,3],[3,4]], guesses = [[1,0],[3,4],[2,1],[3,2]], k = 1
<strong>Output:</strong> 5
<strong>Explanation:</strong>
Root = 0, correct guesses = [3,4]
Root = 1, correct guesses = [1,0], [3,4]
Root = 2, correct guesses = [1,0], [2,1], [3,4]
Root = 3, correct guesses = [1,0], [2,1], [3,2], [3,4]
Root = 4, correct guesses = [1,0], [2,1], [3,2]
Considering any node as root will give at least 1 correct guess.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>edges.length == n - 1</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= guesses.length <= 10<sup>5</sup></code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub>, u<sub>j</sub>, v<sub>j</sub> <= n - 1</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li><code>u<sub>j</sub> != v<sub>j</sub></code></li>
<li><code>edges</code> represents a valid tree.</li>
<li><code>guesses[j]</code> is an edge of the tree.</li>
<li><code>guesses</code> is unique.</li>
<li><code>0 <= k <= guesses.length</code></li>
</ul>
|
Tree; Depth-First Search; Array; Hash Table; Dynamic Programming
|
Go
|
func rootCount(edges [][]int, guesses [][]int, k int) (ans int) {
n := len(edges) + 1
g := make([][]int, n)
gs := map[int]int{}
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
f := func(i, j int) int {
return i*n + j
}
for _, e := range guesses {
a, b := e[0], e[1]
gs[f(a, b)]++
}
cnt := 0
var dfs1 func(i, fa int)
var dfs2 func(i, fa int)
dfs1 = func(i, fa int) {
for _, j := range g[i] {
if j != fa {
cnt += gs[f(i, j)]
dfs1(j, i)
}
}
}
dfs2 = func(i, fa int) {
if cnt >= k {
ans++
}
for _, j := range g[i] {
if j != fa {
a, b := gs[f(i, j)], gs[f(j, i)]
cnt -= a
cnt += b
dfs2(j, i)
cnt -= b
cnt += a
}
}
}
dfs1(0, -1)
dfs2(0, -1)
return
}
|
2,581
|
Count Number of Possible Root Nodes
|
Hard
|
<p>Alice has an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. The tree is represented as a 2D integer array <code>edges</code> of length <code>n - 1</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>Alice wants Bob to find the root of the tree. She allows Bob to make several <strong>guesses</strong> about her tree. In one guess, he does the following:</p>
<ul>
<li>Chooses two <strong>distinct</strong> integers <code>u</code> and <code>v</code> such that there exists an edge <code>[u, v]</code> in the tree.</li>
<li>He tells Alice that <code>u</code> is the <strong>parent</strong> of <code>v</code> in the tree.</li>
</ul>
<p>Bob's guesses are represented by a 2D integer array <code>guesses</code> where <code>guesses[j] = [u<sub>j</sub>, v<sub>j</sub>]</code> indicates Bob guessed <code>u<sub>j</sub></code> to be the parent of <code>v<sub>j</sub></code>.</p>
<p>Alice being lazy, does not reply to each of Bob's guesses, but just says that <strong>at least</strong> <code>k</code> of his guesses are <code>true</code>.</p>
<p>Given the 2D integer arrays <code>edges</code>, <code>guesses</code> and the integer <code>k</code>, return <em>the <strong>number of possible nodes</strong> that can be the root of Alice's tree</em>. If there is no such tree, return <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2581.Count%20Number%20of%20Possible%20Root%20Nodes/images/ex-1.png" style="width: 727px; height: 250px;" /></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[1,3],[4,2]], guesses = [[1,3],[0,1],[1,0],[2,4]], k = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Root = 0, correct guesses = [1,3], [0,1], [2,4]
Root = 1, correct guesses = [1,3], [1,0], [2,4]
Root = 2, correct guesses = [1,3], [1,0], [2,4]
Root = 3, correct guesses = [1,0], [2,4]
Root = 4, correct guesses = [1,3], [1,0]
Considering 0, 1, or 2 as root node leads to 3 correct guesses.
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2581.Count%20Number%20of%20Possible%20Root%20Nodes/images/ex-2.png" style="width: 600px; height: 303px;" /></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[2,3],[3,4]], guesses = [[1,0],[3,4],[2,1],[3,2]], k = 1
<strong>Output:</strong> 5
<strong>Explanation:</strong>
Root = 0, correct guesses = [3,4]
Root = 1, correct guesses = [1,0], [3,4]
Root = 2, correct guesses = [1,0], [2,1], [3,4]
Root = 3, correct guesses = [1,0], [2,1], [3,2], [3,4]
Root = 4, correct guesses = [1,0], [2,1], [3,2]
Considering any node as root will give at least 1 correct guess.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>edges.length == n - 1</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= guesses.length <= 10<sup>5</sup></code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub>, u<sub>j</sub>, v<sub>j</sub> <= n - 1</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li><code>u<sub>j</sub> != v<sub>j</sub></code></li>
<li><code>edges</code> represents a valid tree.</li>
<li><code>guesses[j]</code> is an edge of the tree.</li>
<li><code>guesses</code> is unique.</li>
<li><code>0 <= k <= guesses.length</code></li>
</ul>
|
Tree; Depth-First Search; Array; Hash Table; Dynamic Programming
|
Java
|
class Solution {
private List<Integer>[] g;
private Map<Long, Integer> gs = new HashMap<>();
private int ans;
private int k;
private int cnt;
private int n;
public int rootCount(int[][] edges, int[][] guesses, int k) {
this.k = k;
n = edges.length + 1;
g = new List[n];
Arrays.setAll(g, e -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
for (var e : guesses) {
int a = e[0], b = e[1];
gs.merge(f(a, b), 1, Integer::sum);
}
dfs1(0, -1);
dfs2(0, -1);
return ans;
}
private void dfs1(int i, int fa) {
for (int j : g[i]) {
if (j != fa) {
cnt += gs.getOrDefault(f(i, j), 0);
dfs1(j, i);
}
}
}
private void dfs2(int i, int fa) {
ans += cnt >= k ? 1 : 0;
for (int j : g[i]) {
if (j != fa) {
int a = gs.getOrDefault(f(i, j), 0);
int b = gs.getOrDefault(f(j, i), 0);
cnt -= a;
cnt += b;
dfs2(j, i);
cnt -= b;
cnt += a;
}
}
}
private long f(int i, int j) {
return 1L * i * n + j;
}
}
|
2,581
|
Count Number of Possible Root Nodes
|
Hard
|
<p>Alice has an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. The tree is represented as a 2D integer array <code>edges</code> of length <code>n - 1</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>Alice wants Bob to find the root of the tree. She allows Bob to make several <strong>guesses</strong> about her tree. In one guess, he does the following:</p>
<ul>
<li>Chooses two <strong>distinct</strong> integers <code>u</code> and <code>v</code> such that there exists an edge <code>[u, v]</code> in the tree.</li>
<li>He tells Alice that <code>u</code> is the <strong>parent</strong> of <code>v</code> in the tree.</li>
</ul>
<p>Bob's guesses are represented by a 2D integer array <code>guesses</code> where <code>guesses[j] = [u<sub>j</sub>, v<sub>j</sub>]</code> indicates Bob guessed <code>u<sub>j</sub></code> to be the parent of <code>v<sub>j</sub></code>.</p>
<p>Alice being lazy, does not reply to each of Bob's guesses, but just says that <strong>at least</strong> <code>k</code> of his guesses are <code>true</code>.</p>
<p>Given the 2D integer arrays <code>edges</code>, <code>guesses</code> and the integer <code>k</code>, return <em>the <strong>number of possible nodes</strong> that can be the root of Alice's tree</em>. If there is no such tree, return <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2581.Count%20Number%20of%20Possible%20Root%20Nodes/images/ex-1.png" style="width: 727px; height: 250px;" /></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[1,3],[4,2]], guesses = [[1,3],[0,1],[1,0],[2,4]], k = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Root = 0, correct guesses = [1,3], [0,1], [2,4]
Root = 1, correct guesses = [1,3], [1,0], [2,4]
Root = 2, correct guesses = [1,3], [1,0], [2,4]
Root = 3, correct guesses = [1,0], [2,4]
Root = 4, correct guesses = [1,3], [1,0]
Considering 0, 1, or 2 as root node leads to 3 correct guesses.
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2581.Count%20Number%20of%20Possible%20Root%20Nodes/images/ex-2.png" style="width: 600px; height: 303px;" /></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[2,3],[3,4]], guesses = [[1,0],[3,4],[2,1],[3,2]], k = 1
<strong>Output:</strong> 5
<strong>Explanation:</strong>
Root = 0, correct guesses = [3,4]
Root = 1, correct guesses = [1,0], [3,4]
Root = 2, correct guesses = [1,0], [2,1], [3,4]
Root = 3, correct guesses = [1,0], [2,1], [3,2], [3,4]
Root = 4, correct guesses = [1,0], [2,1], [3,2]
Considering any node as root will give at least 1 correct guess.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>edges.length == n - 1</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= guesses.length <= 10<sup>5</sup></code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub>, u<sub>j</sub>, v<sub>j</sub> <= n - 1</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li><code>u<sub>j</sub> != v<sub>j</sub></code></li>
<li><code>edges</code> represents a valid tree.</li>
<li><code>guesses[j]</code> is an edge of the tree.</li>
<li><code>guesses</code> is unique.</li>
<li><code>0 <= k <= guesses.length</code></li>
</ul>
|
Tree; Depth-First Search; Array; Hash Table; Dynamic Programming
|
Python
|
class Solution:
def rootCount(
self, edges: List[List[int]], guesses: List[List[int]], k: int
) -> int:
def dfs1(i, fa):
nonlocal cnt
for j in g[i]:
if j != fa:
cnt += gs[(i, j)]
dfs1(j, i)
def dfs2(i, fa):
nonlocal ans, cnt
ans += cnt >= k
for j in g[i]:
if j != fa:
cnt -= gs[(i, j)]
cnt += gs[(j, i)]
dfs2(j, i)
cnt -= gs[(j, i)]
cnt += gs[(i, j)]
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
gs = Counter((u, v) for u, v in guesses)
cnt = 0
dfs1(0, -1)
ans = 0
dfs2(0, -1)
return ans
|
2,581
|
Count Number of Possible Root Nodes
|
Hard
|
<p>Alice has an undirected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. The tree is represented as a 2D integer array <code>edges</code> of length <code>n - 1</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>
<p>Alice wants Bob to find the root of the tree. She allows Bob to make several <strong>guesses</strong> about her tree. In one guess, he does the following:</p>
<ul>
<li>Chooses two <strong>distinct</strong> integers <code>u</code> and <code>v</code> such that there exists an edge <code>[u, v]</code> in the tree.</li>
<li>He tells Alice that <code>u</code> is the <strong>parent</strong> of <code>v</code> in the tree.</li>
</ul>
<p>Bob's guesses are represented by a 2D integer array <code>guesses</code> where <code>guesses[j] = [u<sub>j</sub>, v<sub>j</sub>]</code> indicates Bob guessed <code>u<sub>j</sub></code> to be the parent of <code>v<sub>j</sub></code>.</p>
<p>Alice being lazy, does not reply to each of Bob's guesses, but just says that <strong>at least</strong> <code>k</code> of his guesses are <code>true</code>.</p>
<p>Given the 2D integer arrays <code>edges</code>, <code>guesses</code> and the integer <code>k</code>, return <em>the <strong>number of possible nodes</strong> that can be the root of Alice's tree</em>. If there is no such tree, return <code>0</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2581.Count%20Number%20of%20Possible%20Root%20Nodes/images/ex-1.png" style="width: 727px; height: 250px;" /></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[1,3],[4,2]], guesses = [[1,3],[0,1],[1,0],[2,4]], k = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong>
Root = 0, correct guesses = [1,3], [0,1], [2,4]
Root = 1, correct guesses = [1,3], [1,0], [2,4]
Root = 2, correct guesses = [1,3], [1,0], [2,4]
Root = 3, correct guesses = [1,0], [2,4]
Root = 4, correct guesses = [1,3], [1,0]
Considering 0, 1, or 2 as root node leads to 3 correct guesses.
</pre>
<p><strong class="example">Example 2:</strong></p>
<p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2581.Count%20Number%20of%20Possible%20Root%20Nodes/images/ex-2.png" style="width: 600px; height: 303px;" /></p>
<pre>
<strong>Input:</strong> edges = [[0,1],[1,2],[2,3],[3,4]], guesses = [[1,0],[3,4],[2,1],[3,2]], k = 1
<strong>Output:</strong> 5
<strong>Explanation:</strong>
Root = 0, correct guesses = [3,4]
Root = 1, correct guesses = [1,0], [3,4]
Root = 2, correct guesses = [1,0], [2,1], [3,4]
Root = 3, correct guesses = [1,0], [2,1], [3,2], [3,4]
Root = 4, correct guesses = [1,0], [2,1], [3,2]
Considering any node as root will give at least 1 correct guess.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>edges.length == n - 1</code></li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= guesses.length <= 10<sup>5</sup></code></li>
<li><code>0 <= a<sub>i</sub>, b<sub>i</sub>, u<sub>j</sub>, v<sub>j</sub> <= n - 1</code></li>
<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
<li><code>u<sub>j</sub> != v<sub>j</sub></code></li>
<li><code>edges</code> represents a valid tree.</li>
<li><code>guesses[j]</code> is an edge of the tree.</li>
<li><code>guesses</code> is unique.</li>
<li><code>0 <= k <= guesses.length</code></li>
</ul>
|
Tree; Depth-First Search; Array; Hash Table; Dynamic Programming
|
TypeScript
|
function rootCount(edges: number[][], guesses: number[][], k: number): number {
const n = edges.length + 1;
const g: number[][] = Array.from({ length: n }, () => []);
const gs: Map<number, number> = new Map();
const f = (i: number, j: number) => i * n + j;
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
}
for (const [a, b] of guesses) {
const x = f(a, b);
gs.set(x, gs.has(x) ? gs.get(x)! + 1 : 1);
}
let ans = 0;
let cnt = 0;
const dfs1 = (i: number, fa: number): void => {
for (const j of g[i]) {
if (j !== fa) {
cnt += gs.get(f(i, j)) || 0;
dfs1(j, i);
}
}
};
const dfs2 = (i: number, fa: number): void => {
ans += cnt >= k ? 1 : 0;
for (const j of g[i]) {
if (j !== fa) {
const a = gs.get(f(i, j)) || 0;
const b = gs.get(f(j, i)) || 0;
cnt -= a;
cnt += b;
dfs2(j, i);
cnt -= b;
cnt += a;
}
}
};
dfs1(0, -1);
dfs2(0, -1);
return ans;
}
|
2,582
|
Pass the Pillow
|
Easy
|
<p>There are <code>n</code> people standing in a line labeled from <code>1</code> to <code>n</code>. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction.</p>
<ul>
<li>For example, once the pillow reaches the <code>n<sup>th</sup></code> person they pass it to the <code>n - 1<sup>th</sup></code> person, then to the <code>n - 2<sup>th</sup></code> person and so on.</li>
</ul>
<p>Given the two positive integers <code>n</code> and <code>time</code>, return <em>the index of the person holding the pillow after </em><code>time</code><em> seconds</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4, time = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2.
After five seconds, the 2<sup>nd</sup> person is holding the pillow.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, time = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> People pass the pillow in the following way: 1 -> 2 -> 3.
After two seconds, the 3<sup>r</sup><sup>d</sup> person is holding the pillow.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>1 <= time <= 1000</code></li>
</ul>
<p> </p>
<p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/find-the-child-who-has-the-ball-after-k-seconds/description/" target="_blank"> 3178: Find the Child Who Has the Ball After K Seconds.</a></p>
|
Math; Simulation
|
C++
|
class Solution {
public:
int passThePillow(int n, int time) {
int ans = 1, k = 1;
while (time--) {
ans += k;
if (ans == 1 || ans == n) {
k *= -1;
}
}
return ans;
}
};
|
2,582
|
Pass the Pillow
|
Easy
|
<p>There are <code>n</code> people standing in a line labeled from <code>1</code> to <code>n</code>. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction.</p>
<ul>
<li>For example, once the pillow reaches the <code>n<sup>th</sup></code> person they pass it to the <code>n - 1<sup>th</sup></code> person, then to the <code>n - 2<sup>th</sup></code> person and so on.</li>
</ul>
<p>Given the two positive integers <code>n</code> and <code>time</code>, return <em>the index of the person holding the pillow after </em><code>time</code><em> seconds</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4, time = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2.
After five seconds, the 2<sup>nd</sup> person is holding the pillow.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, time = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> People pass the pillow in the following way: 1 -> 2 -> 3.
After two seconds, the 3<sup>r</sup><sup>d</sup> person is holding the pillow.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>1 <= time <= 1000</code></li>
</ul>
<p> </p>
<p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/find-the-child-who-has-the-ball-after-k-seconds/description/" target="_blank"> 3178: Find the Child Who Has the Ball After K Seconds.</a></p>
|
Math; Simulation
|
Go
|
func passThePillow(n int, time int) int {
ans, k := 1, 1
for ; time > 0; time-- {
ans += k
if ans == 1 || ans == n {
k *= -1
}
}
return ans
}
|
2,582
|
Pass the Pillow
|
Easy
|
<p>There are <code>n</code> people standing in a line labeled from <code>1</code> to <code>n</code>. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction.</p>
<ul>
<li>For example, once the pillow reaches the <code>n<sup>th</sup></code> person they pass it to the <code>n - 1<sup>th</sup></code> person, then to the <code>n - 2<sup>th</sup></code> person and so on.</li>
</ul>
<p>Given the two positive integers <code>n</code> and <code>time</code>, return <em>the index of the person holding the pillow after </em><code>time</code><em> seconds</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4, time = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2.
After five seconds, the 2<sup>nd</sup> person is holding the pillow.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, time = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> People pass the pillow in the following way: 1 -> 2 -> 3.
After two seconds, the 3<sup>r</sup><sup>d</sup> person is holding the pillow.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>1 <= time <= 1000</code></li>
</ul>
<p> </p>
<p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/find-the-child-who-has-the-ball-after-k-seconds/description/" target="_blank"> 3178: Find the Child Who Has the Ball After K Seconds.</a></p>
|
Math; Simulation
|
Java
|
class Solution {
public int passThePillow(int n, int time) {
int ans = 1, k = 1;
while (time-- > 0) {
ans += k;
if (ans == 1 || ans == n) {
k *= -1;
}
}
return ans;
}
}
|
2,582
|
Pass the Pillow
|
Easy
|
<p>There are <code>n</code> people standing in a line labeled from <code>1</code> to <code>n</code>. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction.</p>
<ul>
<li>For example, once the pillow reaches the <code>n<sup>th</sup></code> person they pass it to the <code>n - 1<sup>th</sup></code> person, then to the <code>n - 2<sup>th</sup></code> person and so on.</li>
</ul>
<p>Given the two positive integers <code>n</code> and <code>time</code>, return <em>the index of the person holding the pillow after </em><code>time</code><em> seconds</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4, time = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2.
After five seconds, the 2<sup>nd</sup> person is holding the pillow.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, time = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> People pass the pillow in the following way: 1 -> 2 -> 3.
After two seconds, the 3<sup>r</sup><sup>d</sup> person is holding the pillow.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>1 <= time <= 1000</code></li>
</ul>
<p> </p>
<p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/find-the-child-who-has-the-ball-after-k-seconds/description/" target="_blank"> 3178: Find the Child Who Has the Ball After K Seconds.</a></p>
|
Math; Simulation
|
Python
|
class Solution:
def passThePillow(self, n: int, time: int) -> int:
ans = k = 1
for _ in range(time):
ans += k
if ans == 1 or ans == n:
k *= -1
return ans
|
2,582
|
Pass the Pillow
|
Easy
|
<p>There are <code>n</code> people standing in a line labeled from <code>1</code> to <code>n</code>. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction.</p>
<ul>
<li>For example, once the pillow reaches the <code>n<sup>th</sup></code> person they pass it to the <code>n - 1<sup>th</sup></code> person, then to the <code>n - 2<sup>th</sup></code> person and so on.</li>
</ul>
<p>Given the two positive integers <code>n</code> and <code>time</code>, return <em>the index of the person holding the pillow after </em><code>time</code><em> seconds</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4, time = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2.
After five seconds, the 2<sup>nd</sup> person is holding the pillow.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, time = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> People pass the pillow in the following way: 1 -> 2 -> 3.
After two seconds, the 3<sup>r</sup><sup>d</sup> person is holding the pillow.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>1 <= time <= 1000</code></li>
</ul>
<p> </p>
<p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/find-the-child-who-has-the-ball-after-k-seconds/description/" target="_blank"> 3178: Find the Child Who Has the Ball After K Seconds.</a></p>
|
Math; Simulation
|
Rust
|
impl Solution {
pub fn pass_the_pillow(n: i32, time: i32) -> i32 {
let mut ans = 1;
let mut k = 1;
for i in 1..=time {
ans += k;
if ans == 1 || ans == n {
k *= -1;
}
}
ans
}
}
|
2,582
|
Pass the Pillow
|
Easy
|
<p>There are <code>n</code> people standing in a line labeled from <code>1</code> to <code>n</code>. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction.</p>
<ul>
<li>For example, once the pillow reaches the <code>n<sup>th</sup></code> person they pass it to the <code>n - 1<sup>th</sup></code> person, then to the <code>n - 2<sup>th</sup></code> person and so on.</li>
</ul>
<p>Given the two positive integers <code>n</code> and <code>time</code>, return <em>the index of the person holding the pillow after </em><code>time</code><em> seconds</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> n = 4, time = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2.
After five seconds, the 2<sup>nd</sup> person is holding the pillow.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> n = 3, time = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> People pass the pillow in the following way: 1 -> 2 -> 3.
After two seconds, the 3<sup>r</sup><sup>d</sup> person is holding the pillow.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>2 <= n <= 1000</code></li>
<li><code>1 <= time <= 1000</code></li>
</ul>
<p> </p>
<p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/find-the-child-who-has-the-ball-after-k-seconds/description/" target="_blank"> 3178: Find the Child Who Has the Ball After K Seconds.</a></p>
|
Math; Simulation
|
TypeScript
|
function passThePillow(n: number, time: number): number {
let ans = 1,
k = 1;
while (time-- > 0) {
ans += k;
if (ans === 1 || ans === n) {
k *= -1;
}
}
return ans;
}
|
2,583
|
Kth Largest Sum in a Binary Tree
|
Medium
|
<p>You are given the <code>root</code> of a binary tree and a positive integer <code>k</code>.</p>
<p>The <strong>level sum</strong> in the tree is the sum of the values of the nodes that are on the <strong>same</strong> level.</p>
<p>Return<em> the </em><code>k<sup>th</sup></code><em> <strong>largest</strong> level sum in the tree (not necessarily distinct)</em>. If there are fewer than <code>k</code> levels in the tree, return <code>-1</code>.</p>
<p><strong>Note</strong> that two nodes are on the same level if they have the same distance from the root.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2583.Kth%20Largest%20Sum%20in%20a%20Binary%20Tree/images/binaryytreeedrawio-2.png" style="width: 301px; height: 284px;" />
<pre>
<strong>Input:</strong> root = [5,8,9,2,1,3,7,4,6], k = 2
<strong>Output:</strong> 13
<strong>Explanation:</strong> The level sums are the following:
- Level 1: 5.
- Level 2: 8 + 9 = 17.
- Level 3: 2 + 1 + 3 + 7 = 13.
- Level 4: 4 + 6 = 10.
The 2<sup>nd</sup> largest level sum is 13.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2583.Kth%20Largest%20Sum%20in%20a%20Binary%20Tree/images/treedrawio-3.png" style="width: 181px; height: 181px;" />
<pre>
<strong>Input:</strong> root = [1,2,null,3], k = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> The largest level sum is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is <code>n</code>.</li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= Node.val <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Tree; Breadth-First Search; Binary Tree; Sorting
|
C++
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
long long kthLargestLevelSum(TreeNode* root, int k) {
vector<long long> arr;
queue<TreeNode*> q{{root}};
while (!q.empty()) {
long long t = 0;
for (int n = q.size(); n; --n) {
root = q.front();
q.pop();
t += root->val;
if (root->left) {
q.push(root->left);
}
if (root->right) {
q.push(root->right);
}
}
arr.push_back(t);
}
if (arr.size() < k) {
return -1;
}
sort(arr.rbegin(), arr.rend());
return arr[k - 1];
}
};
|
2,583
|
Kth Largest Sum in a Binary Tree
|
Medium
|
<p>You are given the <code>root</code> of a binary tree and a positive integer <code>k</code>.</p>
<p>The <strong>level sum</strong> in the tree is the sum of the values of the nodes that are on the <strong>same</strong> level.</p>
<p>Return<em> the </em><code>k<sup>th</sup></code><em> <strong>largest</strong> level sum in the tree (not necessarily distinct)</em>. If there are fewer than <code>k</code> levels in the tree, return <code>-1</code>.</p>
<p><strong>Note</strong> that two nodes are on the same level if they have the same distance from the root.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2583.Kth%20Largest%20Sum%20in%20a%20Binary%20Tree/images/binaryytreeedrawio-2.png" style="width: 301px; height: 284px;" />
<pre>
<strong>Input:</strong> root = [5,8,9,2,1,3,7,4,6], k = 2
<strong>Output:</strong> 13
<strong>Explanation:</strong> The level sums are the following:
- Level 1: 5.
- Level 2: 8 + 9 = 17.
- Level 3: 2 + 1 + 3 + 7 = 13.
- Level 4: 4 + 6 = 10.
The 2<sup>nd</sup> largest level sum is 13.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2583.Kth%20Largest%20Sum%20in%20a%20Binary%20Tree/images/treedrawio-3.png" style="width: 181px; height: 181px;" />
<pre>
<strong>Input:</strong> root = [1,2,null,3], k = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> The largest level sum is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is <code>n</code>.</li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= Node.val <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Tree; Breadth-First Search; Binary Tree; Sorting
|
Go
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func kthLargestLevelSum(root *TreeNode, k int) int64 {
arr := []int{}
q := []*TreeNode{root}
for len(q) > 0 {
t := 0
for n := len(q); n > 0; n-- {
root = q[0]
q = q[1:]
t += root.Val
if root.Left != nil {
q = append(q, root.Left)
}
if root.Right != nil {
q = append(q, root.Right)
}
}
arr = append(arr, t)
}
if n := len(arr); n >= k {
sort.Ints(arr)
return int64(arr[n-k])
}
return -1
}
|
2,583
|
Kth Largest Sum in a Binary Tree
|
Medium
|
<p>You are given the <code>root</code> of a binary tree and a positive integer <code>k</code>.</p>
<p>The <strong>level sum</strong> in the tree is the sum of the values of the nodes that are on the <strong>same</strong> level.</p>
<p>Return<em> the </em><code>k<sup>th</sup></code><em> <strong>largest</strong> level sum in the tree (not necessarily distinct)</em>. If there are fewer than <code>k</code> levels in the tree, return <code>-1</code>.</p>
<p><strong>Note</strong> that two nodes are on the same level if they have the same distance from the root.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2583.Kth%20Largest%20Sum%20in%20a%20Binary%20Tree/images/binaryytreeedrawio-2.png" style="width: 301px; height: 284px;" />
<pre>
<strong>Input:</strong> root = [5,8,9,2,1,3,7,4,6], k = 2
<strong>Output:</strong> 13
<strong>Explanation:</strong> The level sums are the following:
- Level 1: 5.
- Level 2: 8 + 9 = 17.
- Level 3: 2 + 1 + 3 + 7 = 13.
- Level 4: 4 + 6 = 10.
The 2<sup>nd</sup> largest level sum is 13.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2583.Kth%20Largest%20Sum%20in%20a%20Binary%20Tree/images/treedrawio-3.png" style="width: 181px; height: 181px;" />
<pre>
<strong>Input:</strong> root = [1,2,null,3], k = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> The largest level sum is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is <code>n</code>.</li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= Node.val <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Tree; Breadth-First Search; Binary Tree; Sorting
|
Java
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public long kthLargestLevelSum(TreeNode root, int k) {
List<Long> arr = new ArrayList<>();
Deque<TreeNode> q = new ArrayDeque<>();
q.offer(root);
while (!q.isEmpty()) {
long t = 0;
for (int n = q.size(); n > 0; --n) {
root = q.pollFirst();
t += root.val;
if (root.left != null) {
q.offer(root.left);
}
if (root.right != null) {
q.offer(root.right);
}
}
arr.add(t);
}
if (arr.size() < k) {
return -1;
}
Collections.sort(arr, Collections.reverseOrder());
return arr.get(k - 1);
}
}
|
2,583
|
Kth Largest Sum in a Binary Tree
|
Medium
|
<p>You are given the <code>root</code> of a binary tree and a positive integer <code>k</code>.</p>
<p>The <strong>level sum</strong> in the tree is the sum of the values of the nodes that are on the <strong>same</strong> level.</p>
<p>Return<em> the </em><code>k<sup>th</sup></code><em> <strong>largest</strong> level sum in the tree (not necessarily distinct)</em>. If there are fewer than <code>k</code> levels in the tree, return <code>-1</code>.</p>
<p><strong>Note</strong> that two nodes are on the same level if they have the same distance from the root.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2583.Kth%20Largest%20Sum%20in%20a%20Binary%20Tree/images/binaryytreeedrawio-2.png" style="width: 301px; height: 284px;" />
<pre>
<strong>Input:</strong> root = [5,8,9,2,1,3,7,4,6], k = 2
<strong>Output:</strong> 13
<strong>Explanation:</strong> The level sums are the following:
- Level 1: 5.
- Level 2: 8 + 9 = 17.
- Level 3: 2 + 1 + 3 + 7 = 13.
- Level 4: 4 + 6 = 10.
The 2<sup>nd</sup> largest level sum is 13.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2583.Kth%20Largest%20Sum%20in%20a%20Binary%20Tree/images/treedrawio-3.png" style="width: 181px; height: 181px;" />
<pre>
<strong>Input:</strong> root = [1,2,null,3], k = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> The largest level sum is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is <code>n</code>.</li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= Node.val <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Tree; Breadth-First Search; Binary Tree; Sorting
|
Python
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int:
arr = []
q = deque([root])
while q:
t = 0
for _ in range(len(q)):
root = q.popleft()
t += root.val
if root.left:
q.append(root.left)
if root.right:
q.append(root.right)
arr.append(t)
return -1 if len(arr) < k else nlargest(k, arr)[-1]
|
2,583
|
Kth Largest Sum in a Binary Tree
|
Medium
|
<p>You are given the <code>root</code> of a binary tree and a positive integer <code>k</code>.</p>
<p>The <strong>level sum</strong> in the tree is the sum of the values of the nodes that are on the <strong>same</strong> level.</p>
<p>Return<em> the </em><code>k<sup>th</sup></code><em> <strong>largest</strong> level sum in the tree (not necessarily distinct)</em>. If there are fewer than <code>k</code> levels in the tree, return <code>-1</code>.</p>
<p><strong>Note</strong> that two nodes are on the same level if they have the same distance from the root.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2583.Kth%20Largest%20Sum%20in%20a%20Binary%20Tree/images/binaryytreeedrawio-2.png" style="width: 301px; height: 284px;" />
<pre>
<strong>Input:</strong> root = [5,8,9,2,1,3,7,4,6], k = 2
<strong>Output:</strong> 13
<strong>Explanation:</strong> The level sums are the following:
- Level 1: 5.
- Level 2: 8 + 9 = 17.
- Level 3: 2 + 1 + 3 + 7 = 13.
- Level 4: 4 + 6 = 10.
The 2<sup>nd</sup> largest level sum is 13.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2583.Kth%20Largest%20Sum%20in%20a%20Binary%20Tree/images/treedrawio-3.png" style="width: 181px; height: 181px;" />
<pre>
<strong>Input:</strong> root = [1,2,null,3], k = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> The largest level sum is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li>The number of nodes in the tree is <code>n</code>.</li>
<li><code>2 <= n <= 10<sup>5</sup></code></li>
<li><code>1 <= Node.val <= 10<sup>6</sup></code></li>
<li><code>1 <= k <= n</code></li>
</ul>
|
Tree; Breadth-First Search; Binary Tree; Sorting
|
TypeScript
|
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function kthLargestLevelSum(root: TreeNode | null, k: number): number {
const arr: number[] = [];
const q = [root];
while (q.length) {
let t = 0;
for (let n = q.length; n > 0; --n) {
root = q.shift();
t += root.val;
if (root.left) {
q.push(root.left);
}
if (root.right) {
q.push(root.right);
}
}
arr.push(t);
}
if (arr.length < k) {
return -1;
}
arr.sort((a, b) => b - a);
return arr[k - 1];
}
|
2,584
|
Split the Array to Make Coprime Products
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p>
<p>A <strong>split</strong> at an index <code>i</code> where <code>0 <= i <= n - 2</code> is called <strong>valid</strong> if the product of the first <code>i + 1</code> elements and the product of the remaining elements are coprime.</p>
<ul>
<li>For example, if <code>nums = [2, 3, 3]</code>, then a split at the index <code>i = 0</code> is valid because <code>2</code> and <code>9</code> are coprime, while a split at the index <code>i = 1</code> is not valid because <code>6</code> and <code>3</code> are not coprime. A split at the index <code>i = 2</code> is not valid because <code>i == n - 1</code>.</li>
</ul>
<p>Return <em>the smallest index </em><code>i</code><em> at which the array can be split validly or </em><code>-1</code><em> if there is no such split</em>.</p>
<p>Two values <code>val1</code> and <code>val2</code> are coprime if <code>gcd(val1, val2) == 1</code> where <code>gcd(val1, val2)</code> is the greatest common divisor of <code>val1</code> and <code>val2</code>.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2584.Split%20the%20Array%20to%20Make%20Coprime%20Products/images/second.png" style="width: 450px; height: 211px;" />
<pre>
<strong>Input:</strong> nums = [4,7,8,15,3,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.
The only valid split is at index 2.
</pre>
<p><strong>Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2584.Split%20the%20Array%20to%20Make%20Coprime%20Products/images/capture.png" style="width: 450px; height: 215px;" />
<pre>
<strong>Input:</strong> nums = [4,7,15,8,3,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.
There is no valid split.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Math; Number Theory
|
C++
|
class Solution {
public:
int findValidSplit(vector<int>& nums) {
unordered_map<int, int> first;
int n = nums.size();
vector<int> last(n);
iota(last.begin(), last.end(), 0);
for (int i = 0; i < n; ++i) {
int x = nums[i];
for (int j = 2; j <= x / j; ++j) {
if (x % j == 0) {
if (first.count(j)) {
last[first[j]] = i;
} else {
first[j] = i;
}
while (x % j == 0) {
x /= j;
}
}
}
if (x > 1) {
if (first.count(x)) {
last[first[x]] = i;
} else {
first[x] = i;
}
}
}
int mx = last[0];
for (int i = 0; i < n; ++i) {
if (mx < i) {
return mx;
}
mx = max(mx, last[i]);
}
return -1;
}
};
|
2,584
|
Split the Array to Make Coprime Products
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p>
<p>A <strong>split</strong> at an index <code>i</code> where <code>0 <= i <= n - 2</code> is called <strong>valid</strong> if the product of the first <code>i + 1</code> elements and the product of the remaining elements are coprime.</p>
<ul>
<li>For example, if <code>nums = [2, 3, 3]</code>, then a split at the index <code>i = 0</code> is valid because <code>2</code> and <code>9</code> are coprime, while a split at the index <code>i = 1</code> is not valid because <code>6</code> and <code>3</code> are not coprime. A split at the index <code>i = 2</code> is not valid because <code>i == n - 1</code>.</li>
</ul>
<p>Return <em>the smallest index </em><code>i</code><em> at which the array can be split validly or </em><code>-1</code><em> if there is no such split</em>.</p>
<p>Two values <code>val1</code> and <code>val2</code> are coprime if <code>gcd(val1, val2) == 1</code> where <code>gcd(val1, val2)</code> is the greatest common divisor of <code>val1</code> and <code>val2</code>.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2584.Split%20the%20Array%20to%20Make%20Coprime%20Products/images/second.png" style="width: 450px; height: 211px;" />
<pre>
<strong>Input:</strong> nums = [4,7,8,15,3,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.
The only valid split is at index 2.
</pre>
<p><strong>Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2584.Split%20the%20Array%20to%20Make%20Coprime%20Products/images/capture.png" style="width: 450px; height: 215px;" />
<pre>
<strong>Input:</strong> nums = [4,7,15,8,3,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.
There is no valid split.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Math; Number Theory
|
Go
|
func findValidSplit(nums []int) int {
first := map[int]int{}
n := len(nums)
last := make([]int, n)
for i := range last {
last[i] = i
}
for i, x := range nums {
for j := 2; j <= x/j; j++ {
if x%j == 0 {
if k, ok := first[j]; ok {
last[k] = i
} else {
first[j] = i
}
for x%j == 0 {
x /= j
}
}
}
if x > 1 {
if k, ok := first[x]; ok {
last[k] = i
} else {
first[x] = i
}
}
}
mx := last[0]
for i, x := range last {
if mx < i {
return mx
}
mx = max(mx, x)
}
return -1
}
|
2,584
|
Split the Array to Make Coprime Products
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p>
<p>A <strong>split</strong> at an index <code>i</code> where <code>0 <= i <= n - 2</code> is called <strong>valid</strong> if the product of the first <code>i + 1</code> elements and the product of the remaining elements are coprime.</p>
<ul>
<li>For example, if <code>nums = [2, 3, 3]</code>, then a split at the index <code>i = 0</code> is valid because <code>2</code> and <code>9</code> are coprime, while a split at the index <code>i = 1</code> is not valid because <code>6</code> and <code>3</code> are not coprime. A split at the index <code>i = 2</code> is not valid because <code>i == n - 1</code>.</li>
</ul>
<p>Return <em>the smallest index </em><code>i</code><em> at which the array can be split validly or </em><code>-1</code><em> if there is no such split</em>.</p>
<p>Two values <code>val1</code> and <code>val2</code> are coprime if <code>gcd(val1, val2) == 1</code> where <code>gcd(val1, val2)</code> is the greatest common divisor of <code>val1</code> and <code>val2</code>.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2584.Split%20the%20Array%20to%20Make%20Coprime%20Products/images/second.png" style="width: 450px; height: 211px;" />
<pre>
<strong>Input:</strong> nums = [4,7,8,15,3,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.
The only valid split is at index 2.
</pre>
<p><strong>Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2584.Split%20the%20Array%20to%20Make%20Coprime%20Products/images/capture.png" style="width: 450px; height: 215px;" />
<pre>
<strong>Input:</strong> nums = [4,7,15,8,3,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.
There is no valid split.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Math; Number Theory
|
Java
|
class Solution {
public int findValidSplit(int[] nums) {
Map<Integer, Integer> first = new HashMap<>();
int n = nums.length;
int[] last = new int[n];
for (int i = 0; i < n; ++i) {
last[i] = i;
}
for (int i = 0; i < n; ++i) {
int x = nums[i];
for (int j = 2; j <= x / j; ++j) {
if (x % j == 0) {
if (first.containsKey(j)) {
last[first.get(j)] = i;
} else {
first.put(j, i);
}
while (x % j == 0) {
x /= j;
}
}
}
if (x > 1) {
if (first.containsKey(x)) {
last[first.get(x)] = i;
} else {
first.put(x, i);
}
}
}
int mx = last[0];
for (int i = 0; i < n; ++i) {
if (mx < i) {
return mx;
}
mx = Math.max(mx, last[i]);
}
return -1;
}
}
|
2,584
|
Split the Array to Make Coprime Products
|
Hard
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p>
<p>A <strong>split</strong> at an index <code>i</code> where <code>0 <= i <= n - 2</code> is called <strong>valid</strong> if the product of the first <code>i + 1</code> elements and the product of the remaining elements are coprime.</p>
<ul>
<li>For example, if <code>nums = [2, 3, 3]</code>, then a split at the index <code>i = 0</code> is valid because <code>2</code> and <code>9</code> are coprime, while a split at the index <code>i = 1</code> is not valid because <code>6</code> and <code>3</code> are not coprime. A split at the index <code>i = 2</code> is not valid because <code>i == n - 1</code>.</li>
</ul>
<p>Return <em>the smallest index </em><code>i</code><em> at which the array can be split validly or </em><code>-1</code><em> if there is no such split</em>.</p>
<p>Two values <code>val1</code> and <code>val2</code> are coprime if <code>gcd(val1, val2) == 1</code> where <code>gcd(val1, val2)</code> is the greatest common divisor of <code>val1</code> and <code>val2</code>.</p>
<p> </p>
<p><strong>Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2584.Split%20the%20Array%20to%20Make%20Coprime%20Products/images/second.png" style="width: 450px; height: 211px;" />
<pre>
<strong>Input:</strong> nums = [4,7,8,15,3,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.
The only valid split is at index 2.
</pre>
<p><strong>Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2584.Split%20the%20Array%20to%20Make%20Coprime%20Products/images/capture.png" style="width: 450px; height: 215px;" />
<pre>
<strong>Input:</strong> nums = [4,7,15,8,3,5]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.
There is no valid split.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>1 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Array; Hash Table; Math; Number Theory
|
Python
|
class Solution:
def findValidSplit(self, nums: List[int]) -> int:
first = {}
n = len(nums)
last = list(range(n))
for i, x in enumerate(nums):
j = 2
while j <= x // j:
if x % j == 0:
if j in first:
last[first[j]] = i
else:
first[j] = i
while x % j == 0:
x //= j
j += 1
if x > 1:
if x in first:
last[first[x]] = i
else:
first[x] = i
mx = last[0]
for i, x in enumerate(last):
if mx < i:
return mx
mx = max(mx, x)
return -1
|
2,585
|
Number of Ways to Earn Points
|
Hard
|
<p>There is a test that has <code>n</code> types of questions. You are given an integer <code>target</code> and a <strong>0-indexed</strong> 2D integer array <code>types</code> where <code>types[i] = [count<sub>i</sub>, marks<sub>i</sub>]</code> indicates that there are <code>count<sub>i</sub></code> questions of the <code>i<sup>th</sup></code> type, and each one of them is worth <code>marks<sub>i</sub></code> points.</p>
<ul>
</ul>
<p>Return <em>the number of ways you can earn <strong>exactly</strong> </em><code>target</code><em> points in the exam</em>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that questions of the same type are indistinguishable.</p>
<ul>
<li>For example, if there are <code>3</code> questions of the same type, then solving the <code>1<sup>st</sup></code> and <code>2<sup>nd</sup></code> questions is the same as solving the <code>1<sup>st</sup></code> and <code>3<sup>rd</sup></code> questions, or the <code>2<sup>nd</sup></code> and <code>3<sup>rd</sup></code> questions.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> target = 6, types = [[6,1],[3,2],[2,3]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> You can earn 6 points in one of the seven ways:
- Solve 6 questions of the 0<sup>th</sup> type: 1 + 1 + 1 + 1 + 1 + 1 = 6
- Solve 4 questions of the 0<sup>th</sup> type and 1 question of the 1<sup>st</sup> type: 1 + 1 + 1 + 1 + 2 = 6
- Solve 2 questions of the 0<sup>th</sup> type and 2 questions of the 1<sup>st</sup> type: 1 + 1 + 2 + 2 = 6
- Solve 3 questions of the 0<sup>th</sup> type and 1 question of the 2<sup>nd</sup> type: 1 + 1 + 1 + 3 = 6
- Solve 1 question of the 0<sup>th</sup> type, 1 question of the 1<sup>st</sup> type and 1 question of the 2<sup>nd</sup> type: 1 + 2 + 3 = 6
- Solve 3 questions of the 1<sup>st</sup> type: 2 + 2 + 2 = 6
- Solve 2 questions of the 2<sup>nd</sup> type: 3 + 3 = 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> target = 5, types = [[50,1],[50,2],[50,5]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can earn 5 points in one of the four ways:
- Solve 5 questions of the 0<sup>th</sup> type: 1 + 1 + 1 + 1 + 1 = 5
- Solve 3 questions of the 0<sup>th</sup> type and 1 question of the 1<sup>st</sup> type: 1 + 1 + 1 + 2 = 5
- Solve 1 questions of the 0<sup>th</sup> type and 2 questions of the 1<sup>st</sup> type: 1 + 2 + 2 = 5
- Solve 1 question of the 2<sup>nd</sup> type: 5
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> target = 18, types = [[6,1],[3,2],[2,3]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> You can only earn 18 points by answering all questions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target <= 1000</code></li>
<li><code>n == types.length</code></li>
<li><code>1 <= n <= 50</code></li>
<li><code>types[i].length == 2</code></li>
<li><code>1 <= count<sub>i</sub>, marks<sub>i</sub> <= 50</code></li>
</ul>
|
Array; Dynamic Programming
|
C++
|
class Solution {
public:
int waysToReachTarget(int target, vector<vector<int>>& types) {
int n = types.size();
const int mod = 1e9 + 7;
int f[n + 1][target + 1];
memset(f, 0, sizeof(f));
f[0][0] = 1;
for (int i = 1; i <= n; ++i) {
int count = types[i - 1][0], marks = types[i - 1][1];
for (int j = 0; j <= target; ++j) {
for (int k = 0; k <= count; ++k) {
if (j >= k * marks) {
f[i][j] = (f[i][j] + f[i - 1][j - k * marks]) % mod;
}
}
}
}
return f[n][target];
}
};
|
2,585
|
Number of Ways to Earn Points
|
Hard
|
<p>There is a test that has <code>n</code> types of questions. You are given an integer <code>target</code> and a <strong>0-indexed</strong> 2D integer array <code>types</code> where <code>types[i] = [count<sub>i</sub>, marks<sub>i</sub>]</code> indicates that there are <code>count<sub>i</sub></code> questions of the <code>i<sup>th</sup></code> type, and each one of them is worth <code>marks<sub>i</sub></code> points.</p>
<ul>
</ul>
<p>Return <em>the number of ways you can earn <strong>exactly</strong> </em><code>target</code><em> points in the exam</em>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that questions of the same type are indistinguishable.</p>
<ul>
<li>For example, if there are <code>3</code> questions of the same type, then solving the <code>1<sup>st</sup></code> and <code>2<sup>nd</sup></code> questions is the same as solving the <code>1<sup>st</sup></code> and <code>3<sup>rd</sup></code> questions, or the <code>2<sup>nd</sup></code> and <code>3<sup>rd</sup></code> questions.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> target = 6, types = [[6,1],[3,2],[2,3]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> You can earn 6 points in one of the seven ways:
- Solve 6 questions of the 0<sup>th</sup> type: 1 + 1 + 1 + 1 + 1 + 1 = 6
- Solve 4 questions of the 0<sup>th</sup> type and 1 question of the 1<sup>st</sup> type: 1 + 1 + 1 + 1 + 2 = 6
- Solve 2 questions of the 0<sup>th</sup> type and 2 questions of the 1<sup>st</sup> type: 1 + 1 + 2 + 2 = 6
- Solve 3 questions of the 0<sup>th</sup> type and 1 question of the 2<sup>nd</sup> type: 1 + 1 + 1 + 3 = 6
- Solve 1 question of the 0<sup>th</sup> type, 1 question of the 1<sup>st</sup> type and 1 question of the 2<sup>nd</sup> type: 1 + 2 + 3 = 6
- Solve 3 questions of the 1<sup>st</sup> type: 2 + 2 + 2 = 6
- Solve 2 questions of the 2<sup>nd</sup> type: 3 + 3 = 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> target = 5, types = [[50,1],[50,2],[50,5]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can earn 5 points in one of the four ways:
- Solve 5 questions of the 0<sup>th</sup> type: 1 + 1 + 1 + 1 + 1 = 5
- Solve 3 questions of the 0<sup>th</sup> type and 1 question of the 1<sup>st</sup> type: 1 + 1 + 1 + 2 = 5
- Solve 1 questions of the 0<sup>th</sup> type and 2 questions of the 1<sup>st</sup> type: 1 + 2 + 2 = 5
- Solve 1 question of the 2<sup>nd</sup> type: 5
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> target = 18, types = [[6,1],[3,2],[2,3]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> You can only earn 18 points by answering all questions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target <= 1000</code></li>
<li><code>n == types.length</code></li>
<li><code>1 <= n <= 50</code></li>
<li><code>types[i].length == 2</code></li>
<li><code>1 <= count<sub>i</sub>, marks<sub>i</sub> <= 50</code></li>
</ul>
|
Array; Dynamic Programming
|
Go
|
func waysToReachTarget(target int, types [][]int) int {
n := len(types)
f := make([][]int, n+1)
for i := range f {
f[i] = make([]int, target+1)
}
f[0][0] = 1
const mod = 1e9 + 7
for i := 1; i <= n; i++ {
count, marks := types[i-1][0], types[i-1][1]
for j := 0; j <= target; j++ {
for k := 0; k <= count; k++ {
if j >= k*marks {
f[i][j] = (f[i][j] + f[i-1][j-k*marks]) % mod
}
}
}
}
return f[n][target]
}
|
2,585
|
Number of Ways to Earn Points
|
Hard
|
<p>There is a test that has <code>n</code> types of questions. You are given an integer <code>target</code> and a <strong>0-indexed</strong> 2D integer array <code>types</code> where <code>types[i] = [count<sub>i</sub>, marks<sub>i</sub>]</code> indicates that there are <code>count<sub>i</sub></code> questions of the <code>i<sup>th</sup></code> type, and each one of them is worth <code>marks<sub>i</sub></code> points.</p>
<ul>
</ul>
<p>Return <em>the number of ways you can earn <strong>exactly</strong> </em><code>target</code><em> points in the exam</em>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that questions of the same type are indistinguishable.</p>
<ul>
<li>For example, if there are <code>3</code> questions of the same type, then solving the <code>1<sup>st</sup></code> and <code>2<sup>nd</sup></code> questions is the same as solving the <code>1<sup>st</sup></code> and <code>3<sup>rd</sup></code> questions, or the <code>2<sup>nd</sup></code> and <code>3<sup>rd</sup></code> questions.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> target = 6, types = [[6,1],[3,2],[2,3]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> You can earn 6 points in one of the seven ways:
- Solve 6 questions of the 0<sup>th</sup> type: 1 + 1 + 1 + 1 + 1 + 1 = 6
- Solve 4 questions of the 0<sup>th</sup> type and 1 question of the 1<sup>st</sup> type: 1 + 1 + 1 + 1 + 2 = 6
- Solve 2 questions of the 0<sup>th</sup> type and 2 questions of the 1<sup>st</sup> type: 1 + 1 + 2 + 2 = 6
- Solve 3 questions of the 0<sup>th</sup> type and 1 question of the 2<sup>nd</sup> type: 1 + 1 + 1 + 3 = 6
- Solve 1 question of the 0<sup>th</sup> type, 1 question of the 1<sup>st</sup> type and 1 question of the 2<sup>nd</sup> type: 1 + 2 + 3 = 6
- Solve 3 questions of the 1<sup>st</sup> type: 2 + 2 + 2 = 6
- Solve 2 questions of the 2<sup>nd</sup> type: 3 + 3 = 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> target = 5, types = [[50,1],[50,2],[50,5]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can earn 5 points in one of the four ways:
- Solve 5 questions of the 0<sup>th</sup> type: 1 + 1 + 1 + 1 + 1 = 5
- Solve 3 questions of the 0<sup>th</sup> type and 1 question of the 1<sup>st</sup> type: 1 + 1 + 1 + 2 = 5
- Solve 1 questions of the 0<sup>th</sup> type and 2 questions of the 1<sup>st</sup> type: 1 + 2 + 2 = 5
- Solve 1 question of the 2<sup>nd</sup> type: 5
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> target = 18, types = [[6,1],[3,2],[2,3]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> You can only earn 18 points by answering all questions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target <= 1000</code></li>
<li><code>n == types.length</code></li>
<li><code>1 <= n <= 50</code></li>
<li><code>types[i].length == 2</code></li>
<li><code>1 <= count<sub>i</sub>, marks<sub>i</sub> <= 50</code></li>
</ul>
|
Array; Dynamic Programming
|
Java
|
class Solution {
public int waysToReachTarget(int target, int[][] types) {
int n = types.length;
final int mod = (int) 1e9 + 7;
int[][] f = new int[n + 1][target + 1];
f[0][0] = 1;
for (int i = 1; i <= n; ++i) {
int count = types[i - 1][0], marks = types[i - 1][1];
for (int j = 0; j <= target; ++j) {
for (int k = 0; k <= count; ++k) {
if (j >= k * marks) {
f[i][j] = (f[i][j] + f[i - 1][j - k * marks]) % mod;
}
}
}
}
return f[n][target];
}
}
|
2,585
|
Number of Ways to Earn Points
|
Hard
|
<p>There is a test that has <code>n</code> types of questions. You are given an integer <code>target</code> and a <strong>0-indexed</strong> 2D integer array <code>types</code> where <code>types[i] = [count<sub>i</sub>, marks<sub>i</sub>]</code> indicates that there are <code>count<sub>i</sub></code> questions of the <code>i<sup>th</sup></code> type, and each one of them is worth <code>marks<sub>i</sub></code> points.</p>
<ul>
</ul>
<p>Return <em>the number of ways you can earn <strong>exactly</strong> </em><code>target</code><em> points in the exam</em>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that questions of the same type are indistinguishable.</p>
<ul>
<li>For example, if there are <code>3</code> questions of the same type, then solving the <code>1<sup>st</sup></code> and <code>2<sup>nd</sup></code> questions is the same as solving the <code>1<sup>st</sup></code> and <code>3<sup>rd</sup></code> questions, or the <code>2<sup>nd</sup></code> and <code>3<sup>rd</sup></code> questions.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> target = 6, types = [[6,1],[3,2],[2,3]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> You can earn 6 points in one of the seven ways:
- Solve 6 questions of the 0<sup>th</sup> type: 1 + 1 + 1 + 1 + 1 + 1 = 6
- Solve 4 questions of the 0<sup>th</sup> type and 1 question of the 1<sup>st</sup> type: 1 + 1 + 1 + 1 + 2 = 6
- Solve 2 questions of the 0<sup>th</sup> type and 2 questions of the 1<sup>st</sup> type: 1 + 1 + 2 + 2 = 6
- Solve 3 questions of the 0<sup>th</sup> type and 1 question of the 2<sup>nd</sup> type: 1 + 1 + 1 + 3 = 6
- Solve 1 question of the 0<sup>th</sup> type, 1 question of the 1<sup>st</sup> type and 1 question of the 2<sup>nd</sup> type: 1 + 2 + 3 = 6
- Solve 3 questions of the 1<sup>st</sup> type: 2 + 2 + 2 = 6
- Solve 2 questions of the 2<sup>nd</sup> type: 3 + 3 = 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> target = 5, types = [[50,1],[50,2],[50,5]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can earn 5 points in one of the four ways:
- Solve 5 questions of the 0<sup>th</sup> type: 1 + 1 + 1 + 1 + 1 = 5
- Solve 3 questions of the 0<sup>th</sup> type and 1 question of the 1<sup>st</sup> type: 1 + 1 + 1 + 2 = 5
- Solve 1 questions of the 0<sup>th</sup> type and 2 questions of the 1<sup>st</sup> type: 1 + 2 + 2 = 5
- Solve 1 question of the 2<sup>nd</sup> type: 5
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> target = 18, types = [[6,1],[3,2],[2,3]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> You can only earn 18 points by answering all questions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target <= 1000</code></li>
<li><code>n == types.length</code></li>
<li><code>1 <= n <= 50</code></li>
<li><code>types[i].length == 2</code></li>
<li><code>1 <= count<sub>i</sub>, marks<sub>i</sub> <= 50</code></li>
</ul>
|
Array; Dynamic Programming
|
Python
|
class Solution:
def waysToReachTarget(self, target: int, types: List[List[int]]) -> int:
n = len(types)
mod = 10**9 + 7
f = [[0] * (target + 1) for _ in range(n + 1)]
f[0][0] = 1
for i in range(1, n + 1):
count, marks = types[i - 1]
for j in range(target + 1):
for k in range(count + 1):
if j >= k * marks:
f[i][j] = (f[i][j] + f[i - 1][j - k * marks]) % mod
return f[n][target]
|
2,585
|
Number of Ways to Earn Points
|
Hard
|
<p>There is a test that has <code>n</code> types of questions. You are given an integer <code>target</code> and a <strong>0-indexed</strong> 2D integer array <code>types</code> where <code>types[i] = [count<sub>i</sub>, marks<sub>i</sub>]</code> indicates that there are <code>count<sub>i</sub></code> questions of the <code>i<sup>th</sup></code> type, and each one of them is worth <code>marks<sub>i</sub></code> points.</p>
<ul>
</ul>
<p>Return <em>the number of ways you can earn <strong>exactly</strong> </em><code>target</code><em> points in the exam</em>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
<p><strong>Note</strong> that questions of the same type are indistinguishable.</p>
<ul>
<li>For example, if there are <code>3</code> questions of the same type, then solving the <code>1<sup>st</sup></code> and <code>2<sup>nd</sup></code> questions is the same as solving the <code>1<sup>st</sup></code> and <code>3<sup>rd</sup></code> questions, or the <code>2<sup>nd</sup></code> and <code>3<sup>rd</sup></code> questions.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> target = 6, types = [[6,1],[3,2],[2,3]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> You can earn 6 points in one of the seven ways:
- Solve 6 questions of the 0<sup>th</sup> type: 1 + 1 + 1 + 1 + 1 + 1 = 6
- Solve 4 questions of the 0<sup>th</sup> type and 1 question of the 1<sup>st</sup> type: 1 + 1 + 1 + 1 + 2 = 6
- Solve 2 questions of the 0<sup>th</sup> type and 2 questions of the 1<sup>st</sup> type: 1 + 1 + 2 + 2 = 6
- Solve 3 questions of the 0<sup>th</sup> type and 1 question of the 2<sup>nd</sup> type: 1 + 1 + 1 + 3 = 6
- Solve 1 question of the 0<sup>th</sup> type, 1 question of the 1<sup>st</sup> type and 1 question of the 2<sup>nd</sup> type: 1 + 2 + 3 = 6
- Solve 3 questions of the 1<sup>st</sup> type: 2 + 2 + 2 = 6
- Solve 2 questions of the 2<sup>nd</sup> type: 3 + 3 = 6
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> target = 5, types = [[50,1],[50,2],[50,5]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can earn 5 points in one of the four ways:
- Solve 5 questions of the 0<sup>th</sup> type: 1 + 1 + 1 + 1 + 1 = 5
- Solve 3 questions of the 0<sup>th</sup> type and 1 question of the 1<sup>st</sup> type: 1 + 1 + 1 + 2 = 5
- Solve 1 questions of the 0<sup>th</sup> type and 2 questions of the 1<sup>st</sup> type: 1 + 2 + 2 = 5
- Solve 1 question of the 2<sup>nd</sup> type: 5
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> target = 18, types = [[6,1],[3,2],[2,3]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> You can only earn 18 points by answering all questions.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= target <= 1000</code></li>
<li><code>n == types.length</code></li>
<li><code>1 <= n <= 50</code></li>
<li><code>types[i].length == 2</code></li>
<li><code>1 <= count<sub>i</sub>, marks<sub>i</sub> <= 50</code></li>
</ul>
|
Array; Dynamic Programming
|
TypeScript
|
function waysToReachTarget(target: number, types: number[][]): number {
const n = types.length;
const mod = 10 ** 9 + 7;
const f: number[][] = Array.from({ length: n + 1 }, () => Array(target + 1).fill(0));
f[0][0] = 1;
for (let i = 1; i <= n; ++i) {
const [count, marks] = types[i - 1];
for (let j = 0; j <= target; ++j) {
for (let k = 0; k <= count; ++k) {
if (j >= k * marks) {
f[i][j] = (f[i][j] + f[i - 1][j - k * marks]) % mod;
}
}
}
}
return f[n][target];
}
|
2,586
|
Count the Number of Vowel Strings in Range
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of string <code>words</code> and two integers <code>left</code> and <code>right</code>.</p>
<p>A string is called a <strong>vowel string</strong> if it starts with a vowel character and ends with a vowel character where vowel characters are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>.</p>
<p>Return <em>the number of vowel strings </em><code>words[i]</code><em> where </em><code>i</code><em> belongs to the inclusive range </em><code>[left, right]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["are","amy","u"], left = 0, right = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong>
- "are" is a vowel string because it starts with 'a' and ends with 'e'.
- "amy" is not a vowel string because it does not end with a vowel.
- "u" is a vowel string because it starts with 'u' and ends with 'u'.
The number of vowel strings in the mentioned range is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong>
- "aeo" is a vowel string because it starts with 'a' and ends with 'o'.
- "mu" is not a vowel string because it does not start with a vowel.
- "ooo" is a vowel string because it starts with 'o' and ends with 'o'.
- "artro" is a vowel string because it starts with 'a' and ends with 'o'.
The number of vowel strings in the mentioned range is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>words[i]</code> consists of only lowercase English letters.</li>
<li><code>0 <= left <= right < words.length</code></li>
</ul>
|
Array; String; Counting
|
C++
|
class Solution {
public:
int vowelStrings(vector<string>& words, int left, int right) {
auto check = [](char c) -> bool {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
};
int ans = 0;
for (int i = left; i <= right; ++i) {
auto w = words[i];
ans += check(w[0]) && check(w[w.size() - 1]);
}
return ans;
}
};
|
2,586
|
Count the Number of Vowel Strings in Range
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of string <code>words</code> and two integers <code>left</code> and <code>right</code>.</p>
<p>A string is called a <strong>vowel string</strong> if it starts with a vowel character and ends with a vowel character where vowel characters are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>.</p>
<p>Return <em>the number of vowel strings </em><code>words[i]</code><em> where </em><code>i</code><em> belongs to the inclusive range </em><code>[left, right]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["are","amy","u"], left = 0, right = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong>
- "are" is a vowel string because it starts with 'a' and ends with 'e'.
- "amy" is not a vowel string because it does not end with a vowel.
- "u" is a vowel string because it starts with 'u' and ends with 'u'.
The number of vowel strings in the mentioned range is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong>
- "aeo" is a vowel string because it starts with 'a' and ends with 'o'.
- "mu" is not a vowel string because it does not start with a vowel.
- "ooo" is a vowel string because it starts with 'o' and ends with 'o'.
- "artro" is a vowel string because it starts with 'a' and ends with 'o'.
The number of vowel strings in the mentioned range is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>words[i]</code> consists of only lowercase English letters.</li>
<li><code>0 <= left <= right < words.length</code></li>
</ul>
|
Array; String; Counting
|
Go
|
func vowelStrings(words []string, left int, right int) (ans int) {
check := func(c byte) bool {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
}
for _, w := range words[left : right+1] {
if check(w[0]) && check(w[len(w)-1]) {
ans++
}
}
return
}
|
2,586
|
Count the Number of Vowel Strings in Range
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of string <code>words</code> and two integers <code>left</code> and <code>right</code>.</p>
<p>A string is called a <strong>vowel string</strong> if it starts with a vowel character and ends with a vowel character where vowel characters are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>.</p>
<p>Return <em>the number of vowel strings </em><code>words[i]</code><em> where </em><code>i</code><em> belongs to the inclusive range </em><code>[left, right]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["are","amy","u"], left = 0, right = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong>
- "are" is a vowel string because it starts with 'a' and ends with 'e'.
- "amy" is not a vowel string because it does not end with a vowel.
- "u" is a vowel string because it starts with 'u' and ends with 'u'.
The number of vowel strings in the mentioned range is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong>
- "aeo" is a vowel string because it starts with 'a' and ends with 'o'.
- "mu" is not a vowel string because it does not start with a vowel.
- "ooo" is a vowel string because it starts with 'o' and ends with 'o'.
- "artro" is a vowel string because it starts with 'a' and ends with 'o'.
The number of vowel strings in the mentioned range is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>words[i]</code> consists of only lowercase English letters.</li>
<li><code>0 <= left <= right < words.length</code></li>
</ul>
|
Array; String; Counting
|
Java
|
class Solution {
public int vowelStrings(String[] words, int left, int right) {
int ans = 0;
for (int i = left; i <= right; ++i) {
var w = words[i];
if (check(w.charAt(0)) && check(w.charAt(w.length() - 1))) {
++ans;
}
}
return ans;
}
private boolean check(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}
|
2,586
|
Count the Number of Vowel Strings in Range
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of string <code>words</code> and two integers <code>left</code> and <code>right</code>.</p>
<p>A string is called a <strong>vowel string</strong> if it starts with a vowel character and ends with a vowel character where vowel characters are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>.</p>
<p>Return <em>the number of vowel strings </em><code>words[i]</code><em> where </em><code>i</code><em> belongs to the inclusive range </em><code>[left, right]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["are","amy","u"], left = 0, right = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong>
- "are" is a vowel string because it starts with 'a' and ends with 'e'.
- "amy" is not a vowel string because it does not end with a vowel.
- "u" is a vowel string because it starts with 'u' and ends with 'u'.
The number of vowel strings in the mentioned range is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong>
- "aeo" is a vowel string because it starts with 'a' and ends with 'o'.
- "mu" is not a vowel string because it does not start with a vowel.
- "ooo" is a vowel string because it starts with 'o' and ends with 'o'.
- "artro" is a vowel string because it starts with 'a' and ends with 'o'.
The number of vowel strings in the mentioned range is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>words[i]</code> consists of only lowercase English letters.</li>
<li><code>0 <= left <= right < words.length</code></li>
</ul>
|
Array; String; Counting
|
Python
|
class Solution:
def vowelStrings(self, words: List[str], left: int, right: int) -> int:
return sum(
w[0] in 'aeiou' and w[-1] in 'aeiou' for w in words[left : right + 1]
)
|
2,586
|
Count the Number of Vowel Strings in Range
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of string <code>words</code> and two integers <code>left</code> and <code>right</code>.</p>
<p>A string is called a <strong>vowel string</strong> if it starts with a vowel character and ends with a vowel character where vowel characters are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>.</p>
<p>Return <em>the number of vowel strings </em><code>words[i]</code><em> where </em><code>i</code><em> belongs to the inclusive range </em><code>[left, right]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["are","amy","u"], left = 0, right = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong>
- "are" is a vowel string because it starts with 'a' and ends with 'e'.
- "amy" is not a vowel string because it does not end with a vowel.
- "u" is a vowel string because it starts with 'u' and ends with 'u'.
The number of vowel strings in the mentioned range is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong>
- "aeo" is a vowel string because it starts with 'a' and ends with 'o'.
- "mu" is not a vowel string because it does not start with a vowel.
- "ooo" is a vowel string because it starts with 'o' and ends with 'o'.
- "artro" is a vowel string because it starts with 'a' and ends with 'o'.
The number of vowel strings in the mentioned range is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>words[i]</code> consists of only lowercase English letters.</li>
<li><code>0 <= left <= right < words.length</code></li>
</ul>
|
Array; String; Counting
|
Rust
|
impl Solution {
pub fn vowel_strings(words: Vec<String>, left: i32, right: i32) -> i32 {
let check =
|c: u8| -> bool { c == b'a' || c == b'e' || c == b'i' || c == b'o' || c == b'u' };
let mut ans = 0;
for i in left..=right {
let w = words[i as usize].as_bytes();
if check(w[0]) && check(w[w.len() - 1]) {
ans += 1;
}
}
ans
}
}
|
2,586
|
Count the Number of Vowel Strings in Range
|
Easy
|
<p>You are given a <strong>0-indexed</strong> array of string <code>words</code> and two integers <code>left</code> and <code>right</code>.</p>
<p>A string is called a <strong>vowel string</strong> if it starts with a vowel character and ends with a vowel character where vowel characters are <code>'a'</code>, <code>'e'</code>, <code>'i'</code>, <code>'o'</code>, and <code>'u'</code>.</p>
<p>Return <em>the number of vowel strings </em><code>words[i]</code><em> where </em><code>i</code><em> belongs to the inclusive range </em><code>[left, right]</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["are","amy","u"], left = 0, right = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong>
- "are" is a vowel string because it starts with 'a' and ends with 'e'.
- "amy" is not a vowel string because it does not end with a vowel.
- "u" is a vowel string because it starts with 'u' and ends with 'u'.
The number of vowel strings in the mentioned range is 2.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong>
- "aeo" is a vowel string because it starts with 'a' and ends with 'o'.
- "mu" is not a vowel string because it does not start with a vowel.
- "ooo" is a vowel string because it starts with 'o' and ends with 'o'.
- "artro" is a vowel string because it starts with 'a' and ends with 'o'.
The number of vowel strings in the mentioned range is 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 1000</code></li>
<li><code>1 <= words[i].length <= 10</code></li>
<li><code>words[i]</code> consists of only lowercase English letters.</li>
<li><code>0 <= left <= right < words.length</code></li>
</ul>
|
Array; String; Counting
|
TypeScript
|
function vowelStrings(words: string[], left: number, right: number): number {
let ans = 0;
const check: string[] = ['a', 'e', 'i', 'o', 'u'];
for (let i = left; i <= right; ++i) {
const w = words[i];
if (check.includes(w[0]) && check.includes(w.at(-1))) {
++ans;
}
}
return ans;
}
|
2,587
|
Rearrange Array to Maximize Prefix Score
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. You can rearrange the elements of <code>nums</code> to <strong>any order</strong> (including the given order).</p>
<p>Let <code>prefix</code> be the array containing the prefix sums of <code>nums</code> after rearranging it. In other words, <code>prefix[i]</code> is the sum of the elements from <code>0</code> to <code>i</code> in <code>nums</code> after rearranging it. The <strong>score</strong> of <code>nums</code> is the number of positive integers in the array <code>prefix</code>.</p>
<p>Return <em>the maximum score you can achieve</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,-1,0,1,-3,3,-3]
<strong>Output:</strong> 6
<strong>Explanation:</strong> We can rearrange the array into nums = [2,3,1,-1,-3,0,-3].
prefix = [2,5,6,5,2,2,-1], so the score is 6.
It can be shown that 6 is the maximum score we can obtain.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-3,0]
<strong>Output:</strong> 0
<strong>Explanation:</strong> Any rearrangement of the array will result in a score of 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>6</sup> <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array; Prefix Sum; Sorting
|
C++
|
class Solution {
public:
int maxScore(vector<int>& nums) {
sort(nums.rbegin(), nums.rend());
long long s = 0;
int n = nums.size();
for (int i = 0; i < n; ++i) {
s += nums[i];
if (s <= 0) {
return i;
}
}
return n;
}
};
|
2,587
|
Rearrange Array to Maximize Prefix Score
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. You can rearrange the elements of <code>nums</code> to <strong>any order</strong> (including the given order).</p>
<p>Let <code>prefix</code> be the array containing the prefix sums of <code>nums</code> after rearranging it. In other words, <code>prefix[i]</code> is the sum of the elements from <code>0</code> to <code>i</code> in <code>nums</code> after rearranging it. The <strong>score</strong> of <code>nums</code> is the number of positive integers in the array <code>prefix</code>.</p>
<p>Return <em>the maximum score you can achieve</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,-1,0,1,-3,3,-3]
<strong>Output:</strong> 6
<strong>Explanation:</strong> We can rearrange the array into nums = [2,3,1,-1,-3,0,-3].
prefix = [2,5,6,5,2,2,-1], so the score is 6.
It can be shown that 6 is the maximum score we can obtain.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-3,0]
<strong>Output:</strong> 0
<strong>Explanation:</strong> Any rearrangement of the array will result in a score of 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>6</sup> <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array; Prefix Sum; Sorting
|
Go
|
func maxScore(nums []int) int {
sort.Ints(nums)
n := len(nums)
s := 0
for i := range nums {
s += nums[n-i-1]
if s <= 0 {
return i
}
}
return n
}
|
2,587
|
Rearrange Array to Maximize Prefix Score
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. You can rearrange the elements of <code>nums</code> to <strong>any order</strong> (including the given order).</p>
<p>Let <code>prefix</code> be the array containing the prefix sums of <code>nums</code> after rearranging it. In other words, <code>prefix[i]</code> is the sum of the elements from <code>0</code> to <code>i</code> in <code>nums</code> after rearranging it. The <strong>score</strong> of <code>nums</code> is the number of positive integers in the array <code>prefix</code>.</p>
<p>Return <em>the maximum score you can achieve</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,-1,0,1,-3,3,-3]
<strong>Output:</strong> 6
<strong>Explanation:</strong> We can rearrange the array into nums = [2,3,1,-1,-3,0,-3].
prefix = [2,5,6,5,2,2,-1], so the score is 6.
It can be shown that 6 is the maximum score we can obtain.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-3,0]
<strong>Output:</strong> 0
<strong>Explanation:</strong> Any rearrangement of the array will result in a score of 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>6</sup> <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array; Prefix Sum; Sorting
|
Java
|
class Solution {
public int maxScore(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
long s = 0;
for (int i = 0; i < n; ++i) {
s += nums[n - i - 1];
if (s <= 0) {
return i;
}
}
return n;
}
}
|
2,587
|
Rearrange Array to Maximize Prefix Score
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. You can rearrange the elements of <code>nums</code> to <strong>any order</strong> (including the given order).</p>
<p>Let <code>prefix</code> be the array containing the prefix sums of <code>nums</code> after rearranging it. In other words, <code>prefix[i]</code> is the sum of the elements from <code>0</code> to <code>i</code> in <code>nums</code> after rearranging it. The <strong>score</strong> of <code>nums</code> is the number of positive integers in the array <code>prefix</code>.</p>
<p>Return <em>the maximum score you can achieve</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,-1,0,1,-3,3,-3]
<strong>Output:</strong> 6
<strong>Explanation:</strong> We can rearrange the array into nums = [2,3,1,-1,-3,0,-3].
prefix = [2,5,6,5,2,2,-1], so the score is 6.
It can be shown that 6 is the maximum score we can obtain.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-3,0]
<strong>Output:</strong> 0
<strong>Explanation:</strong> Any rearrangement of the array will result in a score of 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>6</sup> <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array; Prefix Sum; Sorting
|
Python
|
class Solution:
def maxScore(self, nums: List[int]) -> int:
nums.sort(reverse=True)
s = 0
for i, x in enumerate(nums):
s += x
if s <= 0:
return i
return len(nums)
|
2,587
|
Rearrange Array to Maximize Prefix Score
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. You can rearrange the elements of <code>nums</code> to <strong>any order</strong> (including the given order).</p>
<p>Let <code>prefix</code> be the array containing the prefix sums of <code>nums</code> after rearranging it. In other words, <code>prefix[i]</code> is the sum of the elements from <code>0</code> to <code>i</code> in <code>nums</code> after rearranging it. The <strong>score</strong> of <code>nums</code> is the number of positive integers in the array <code>prefix</code>.</p>
<p>Return <em>the maximum score you can achieve</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,-1,0,1,-3,3,-3]
<strong>Output:</strong> 6
<strong>Explanation:</strong> We can rearrange the array into nums = [2,3,1,-1,-3,0,-3].
prefix = [2,5,6,5,2,2,-1], so the score is 6.
It can be shown that 6 is the maximum score we can obtain.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-3,0]
<strong>Output:</strong> 0
<strong>Explanation:</strong> Any rearrangement of the array will result in a score of 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>6</sup> <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array; Prefix Sum; Sorting
|
Rust
|
impl Solution {
pub fn max_score(mut nums: Vec<i32>) -> i32 {
nums.sort_by(|a, b| b.cmp(a));
let mut s: i64 = 0;
for (i, &x) in nums.iter().enumerate() {
s += x as i64;
if s <= 0 {
return i as i32;
}
}
nums.len() as i32
}
}
|
2,587
|
Rearrange Array to Maximize Prefix Score
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. You can rearrange the elements of <code>nums</code> to <strong>any order</strong> (including the given order).</p>
<p>Let <code>prefix</code> be the array containing the prefix sums of <code>nums</code> after rearranging it. In other words, <code>prefix[i]</code> is the sum of the elements from <code>0</code> to <code>i</code> in <code>nums</code> after rearranging it. The <strong>score</strong> of <code>nums</code> is the number of positive integers in the array <code>prefix</code>.</p>
<p>Return <em>the maximum score you can achieve</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,-1,0,1,-3,3,-3]
<strong>Output:</strong> 6
<strong>Explanation:</strong> We can rearrange the array into nums = [2,3,1,-1,-3,0,-3].
prefix = [2,5,6,5,2,2,-1], so the score is 6.
It can be shown that 6 is the maximum score we can obtain.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [-2,-3,0]
<strong>Output:</strong> 0
<strong>Explanation:</strong> Any rearrangement of the array will result in a score of 0.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>6</sup> <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Greedy; Array; Prefix Sum; Sorting
|
TypeScript
|
function maxScore(nums: number[]): number {
nums.sort((a, b) => a - b);
const n = nums.length;
let s = 0;
for (let i = 0; i < n; ++i) {
s += nums[n - i - 1];
if (s <= 0) {
return i;
}
}
return n;
}
|
2,588
|
Count the Number of Beautiful Subarrays
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. In one operation, you can:</p>
<ul>
<li>Choose two different indices <code>i</code> and <code>j</code> such that <code>0 <= i, j < nums.length</code>.</li>
<li>Choose a non-negative integer <code>k</code> such that the <code>k<sup>th</sup></code> bit (<strong>0-indexed</strong>) in the binary representation of <code>nums[i]</code> and <code>nums[j]</code> is <code>1</code>.</li>
<li>Subtract <code>2<sup>k</sup></code> from <code>nums[i]</code> and <code>nums[j]</code>.</li>
</ul>
<p>A subarray is <strong>beautiful</strong> if it is possible to make all of its elements equal to <code>0</code> after applying the above operation any number of times (including zero).</p>
<p>Return <em>the number of <strong>beautiful subarrays</strong> in the array</em> <code>nums</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p><strong>Note</strong>: Subarrays where all elements are initially 0 are considered beautiful, as no operation is needed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,3,1,2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful subarrays in nums: [4,<u>3,1,2</u>,4] and [<u>4,3,1,2,4</u>].
- We can make all elements in the subarray [3,1,2] equal to 0 in the following way:
- Choose [<u>3</u>, 1, <u>2</u>] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [1, 1, 0].
- Choose [<u>1</u>, <u>1</u>, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 0, 0].
- We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way:
- Choose [<u>4</u>, 3, 1, 2, <u>4</u>] and k = 2. Subtract 2<sup>2</sup> from both numbers. The subarray becomes [0, 3, 1, 2, 0].
- Choose [0, <u>3</u>, <u>1</u>, 2, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 2, 0, 2, 0].
- Choose [0, <u>2</u>, 0, <u>2</u>, 0] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [0, 0, 0, 0, 0].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no beautiful subarrays in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Array; Hash Table; Prefix Sum
|
C++
|
class Solution {
public:
long long beautifulSubarrays(vector<int>& nums) {
unordered_map<int, int> cnt{{0, 1}};
long long ans = 0;
int mask = 0;
for (int x : nums) {
mask ^= x;
ans += cnt[mask]++;
}
return ans;
}
};
|
2,588
|
Count the Number of Beautiful Subarrays
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. In one operation, you can:</p>
<ul>
<li>Choose two different indices <code>i</code> and <code>j</code> such that <code>0 <= i, j < nums.length</code>.</li>
<li>Choose a non-negative integer <code>k</code> such that the <code>k<sup>th</sup></code> bit (<strong>0-indexed</strong>) in the binary representation of <code>nums[i]</code> and <code>nums[j]</code> is <code>1</code>.</li>
<li>Subtract <code>2<sup>k</sup></code> from <code>nums[i]</code> and <code>nums[j]</code>.</li>
</ul>
<p>A subarray is <strong>beautiful</strong> if it is possible to make all of its elements equal to <code>0</code> after applying the above operation any number of times (including zero).</p>
<p>Return <em>the number of <strong>beautiful subarrays</strong> in the array</em> <code>nums</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p><strong>Note</strong>: Subarrays where all elements are initially 0 are considered beautiful, as no operation is needed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,3,1,2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful subarrays in nums: [4,<u>3,1,2</u>,4] and [<u>4,3,1,2,4</u>].
- We can make all elements in the subarray [3,1,2] equal to 0 in the following way:
- Choose [<u>3</u>, 1, <u>2</u>] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [1, 1, 0].
- Choose [<u>1</u>, <u>1</u>, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 0, 0].
- We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way:
- Choose [<u>4</u>, 3, 1, 2, <u>4</u>] and k = 2. Subtract 2<sup>2</sup> from both numbers. The subarray becomes [0, 3, 1, 2, 0].
- Choose [0, <u>3</u>, <u>1</u>, 2, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 2, 0, 2, 0].
- Choose [0, <u>2</u>, 0, <u>2</u>, 0] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [0, 0, 0, 0, 0].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no beautiful subarrays in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Array; Hash Table; Prefix Sum
|
Go
|
func beautifulSubarrays(nums []int) (ans int64) {
cnt := map[int]int{0: 1}
mask := 0
for _, x := range nums {
mask ^= x
ans += int64(cnt[mask])
cnt[mask]++
}
return
}
|
2,588
|
Count the Number of Beautiful Subarrays
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. In one operation, you can:</p>
<ul>
<li>Choose two different indices <code>i</code> and <code>j</code> such that <code>0 <= i, j < nums.length</code>.</li>
<li>Choose a non-negative integer <code>k</code> such that the <code>k<sup>th</sup></code> bit (<strong>0-indexed</strong>) in the binary representation of <code>nums[i]</code> and <code>nums[j]</code> is <code>1</code>.</li>
<li>Subtract <code>2<sup>k</sup></code> from <code>nums[i]</code> and <code>nums[j]</code>.</li>
</ul>
<p>A subarray is <strong>beautiful</strong> if it is possible to make all of its elements equal to <code>0</code> after applying the above operation any number of times (including zero).</p>
<p>Return <em>the number of <strong>beautiful subarrays</strong> in the array</em> <code>nums</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p><strong>Note</strong>: Subarrays where all elements are initially 0 are considered beautiful, as no operation is needed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,3,1,2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful subarrays in nums: [4,<u>3,1,2</u>,4] and [<u>4,3,1,2,4</u>].
- We can make all elements in the subarray [3,1,2] equal to 0 in the following way:
- Choose [<u>3</u>, 1, <u>2</u>] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [1, 1, 0].
- Choose [<u>1</u>, <u>1</u>, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 0, 0].
- We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way:
- Choose [<u>4</u>, 3, 1, 2, <u>4</u>] and k = 2. Subtract 2<sup>2</sup> from both numbers. The subarray becomes [0, 3, 1, 2, 0].
- Choose [0, <u>3</u>, <u>1</u>, 2, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 2, 0, 2, 0].
- Choose [0, <u>2</u>, 0, <u>2</u>, 0] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [0, 0, 0, 0, 0].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no beautiful subarrays in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Array; Hash Table; Prefix Sum
|
Java
|
class Solution {
public long beautifulSubarrays(int[] nums) {
Map<Integer, Integer> cnt = new HashMap<>();
cnt.put(0, 1);
long ans = 0;
int mask = 0;
for (int x : nums) {
mask ^= x;
ans += cnt.merge(mask, 1, Integer::sum) - 1;
}
return ans;
}
}
|
2,588
|
Count the Number of Beautiful Subarrays
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. In one operation, you can:</p>
<ul>
<li>Choose two different indices <code>i</code> and <code>j</code> such that <code>0 <= i, j < nums.length</code>.</li>
<li>Choose a non-negative integer <code>k</code> such that the <code>k<sup>th</sup></code> bit (<strong>0-indexed</strong>) in the binary representation of <code>nums[i]</code> and <code>nums[j]</code> is <code>1</code>.</li>
<li>Subtract <code>2<sup>k</sup></code> from <code>nums[i]</code> and <code>nums[j]</code>.</li>
</ul>
<p>A subarray is <strong>beautiful</strong> if it is possible to make all of its elements equal to <code>0</code> after applying the above operation any number of times (including zero).</p>
<p>Return <em>the number of <strong>beautiful subarrays</strong> in the array</em> <code>nums</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p><strong>Note</strong>: Subarrays where all elements are initially 0 are considered beautiful, as no operation is needed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,3,1,2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful subarrays in nums: [4,<u>3,1,2</u>,4] and [<u>4,3,1,2,4</u>].
- We can make all elements in the subarray [3,1,2] equal to 0 in the following way:
- Choose [<u>3</u>, 1, <u>2</u>] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [1, 1, 0].
- Choose [<u>1</u>, <u>1</u>, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 0, 0].
- We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way:
- Choose [<u>4</u>, 3, 1, 2, <u>4</u>] and k = 2. Subtract 2<sup>2</sup> from both numbers. The subarray becomes [0, 3, 1, 2, 0].
- Choose [0, <u>3</u>, <u>1</u>, 2, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 2, 0, 2, 0].
- Choose [0, <u>2</u>, 0, <u>2</u>, 0] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [0, 0, 0, 0, 0].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no beautiful subarrays in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Array; Hash Table; Prefix Sum
|
Python
|
class Solution:
def beautifulSubarrays(self, nums: List[int]) -> int:
cnt = Counter({0: 1})
ans = mask = 0
for x in nums:
mask ^= x
ans += cnt[mask]
cnt[mask] += 1
return ans
|
2,588
|
Count the Number of Beautiful Subarrays
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. In one operation, you can:</p>
<ul>
<li>Choose two different indices <code>i</code> and <code>j</code> such that <code>0 <= i, j < nums.length</code>.</li>
<li>Choose a non-negative integer <code>k</code> such that the <code>k<sup>th</sup></code> bit (<strong>0-indexed</strong>) in the binary representation of <code>nums[i]</code> and <code>nums[j]</code> is <code>1</code>.</li>
<li>Subtract <code>2<sup>k</sup></code> from <code>nums[i]</code> and <code>nums[j]</code>.</li>
</ul>
<p>A subarray is <strong>beautiful</strong> if it is possible to make all of its elements equal to <code>0</code> after applying the above operation any number of times (including zero).</p>
<p>Return <em>the number of <strong>beautiful subarrays</strong> in the array</em> <code>nums</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p><strong>Note</strong>: Subarrays where all elements are initially 0 are considered beautiful, as no operation is needed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,3,1,2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful subarrays in nums: [4,<u>3,1,2</u>,4] and [<u>4,3,1,2,4</u>].
- We can make all elements in the subarray [3,1,2] equal to 0 in the following way:
- Choose [<u>3</u>, 1, <u>2</u>] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [1, 1, 0].
- Choose [<u>1</u>, <u>1</u>, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 0, 0].
- We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way:
- Choose [<u>4</u>, 3, 1, 2, <u>4</u>] and k = 2. Subtract 2<sup>2</sup> from both numbers. The subarray becomes [0, 3, 1, 2, 0].
- Choose [0, <u>3</u>, <u>1</u>, 2, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 2, 0, 2, 0].
- Choose [0, <u>2</u>, 0, <u>2</u>, 0] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [0, 0, 0, 0, 0].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no beautiful subarrays in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Array; Hash Table; Prefix Sum
|
Rust
|
use std::collections::HashMap;
impl Solution {
pub fn beautiful_subarrays(nums: Vec<i32>) -> i64 {
let mut cnt = HashMap::new();
cnt.insert(0, 1);
let mut ans = 0;
let mut mask = 0;
for &x in nums.iter() {
mask ^= x;
ans += *cnt.get(&mask).unwrap_or(&0);
*cnt.entry(mask).or_insert(0) += 1;
}
ans
}
}
|
2,588
|
Count the Number of Beautiful Subarrays
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. In one operation, you can:</p>
<ul>
<li>Choose two different indices <code>i</code> and <code>j</code> such that <code>0 <= i, j < nums.length</code>.</li>
<li>Choose a non-negative integer <code>k</code> such that the <code>k<sup>th</sup></code> bit (<strong>0-indexed</strong>) in the binary representation of <code>nums[i]</code> and <code>nums[j]</code> is <code>1</code>.</li>
<li>Subtract <code>2<sup>k</sup></code> from <code>nums[i]</code> and <code>nums[j]</code>.</li>
</ul>
<p>A subarray is <strong>beautiful</strong> if it is possible to make all of its elements equal to <code>0</code> after applying the above operation any number of times (including zero).</p>
<p>Return <em>the number of <strong>beautiful subarrays</strong> in the array</em> <code>nums</code>.</p>
<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>
<p><strong>Note</strong>: Subarrays where all elements are initially 0 are considered beautiful, as no operation is needed.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,3,1,2,4]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 2 beautiful subarrays in nums: [4,<u>3,1,2</u>,4] and [<u>4,3,1,2,4</u>].
- We can make all elements in the subarray [3,1,2] equal to 0 in the following way:
- Choose [<u>3</u>, 1, <u>2</u>] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [1, 1, 0].
- Choose [<u>1</u>, <u>1</u>, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 0, 0].
- We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way:
- Choose [<u>4</u>, 3, 1, 2, <u>4</u>] and k = 2. Subtract 2<sup>2</sup> from both numbers. The subarray becomes [0, 3, 1, 2, 0].
- Choose [0, <u>3</u>, <u>1</u>, 2, 0] and k = 0. Subtract 2<sup>0</sup> from both numbers. The subarray becomes [0, 2, 0, 2, 0].
- Choose [0, <u>2</u>, 0, <u>2</u>, 0] and k = 1. Subtract 2<sup>1</sup> from both numbers. The subarray becomes [0, 0, 0, 0, 0].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no beautiful subarrays in nums.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>6</sup></code></li>
</ul>
|
Bit Manipulation; Array; Hash Table; Prefix Sum
|
TypeScript
|
function beautifulSubarrays(nums: number[]): number {
const cnt = new Map();
cnt.set(0, 1);
let ans = 0;
let mask = 0;
for (const x of nums) {
mask ^= x;
ans += cnt.get(mask) || 0;
cnt.set(mask, (cnt.get(mask) || 0) + 1);
}
return ans;
}
|
2,589
|
Minimum Time to Complete All Tasks
|
Hard
|
<p>There is a computer that can run an unlimited number of tasks <strong>at the same time</strong>. You are given a 2D integer array <code>tasks</code> where <code>tasks[i] = [start<sub>i</sub>, end<sub>i</sub>, duration<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> task should run for a total of <code>duration<sub>i</sub></code> seconds (not necessarily continuous) within the <strong>inclusive</strong> time range <code>[start<sub>i</sub>, end<sub>i</sub>]</code>.</p>
<p>You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle.</p>
<p>Return <em>the minimum time during which the computer should be turned on to complete all tasks</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> tasks = [[2,3,1],[4,5,1],[1,5,2]]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
- The first task can be run in the inclusive time range [2, 2].
- The second task can be run in the inclusive time range [5, 5].
- The third task can be run in the two inclusive time ranges [2, 2] and [5, 5].
The computer will be on for a total of 2 seconds.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> tasks = [[1,3,2],[2,5,3],[5,6,2]]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- The first task can be run in the inclusive time range [2, 3].
- The second task can be run in the inclusive time ranges [2, 3] and [5, 5].
- The third task can be run in the two inclusive time range [5, 6].
The computer will be on for a total of 4 seconds.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= tasks.length <= 2000</code></li>
<li><code>tasks[i].length == 3</code></li>
<li><code>1 <= start<sub>i</sub>, end<sub>i</sub> <= 2000</code></li>
<li><code>1 <= duration<sub>i</sub> <= end<sub>i</sub> - start<sub>i</sub> + 1 </code></li>
</ul>
|
Stack; Greedy; Array; Binary Search; Sorting
|
C++
|
class Solution {
public:
int findMinimumTime(vector<vector<int>>& tasks) {
sort(tasks.begin(), tasks.end(), [&](auto& a, auto& b) { return a[1] < b[1]; });
bitset<2010> vis;
int ans = 0;
for (auto& task : tasks) {
int start = task[0], end = task[1], duration = task[2];
for (int i = start; i <= end; ++i) {
duration -= vis[i];
}
for (int i = end; i >= start && duration > 0; --i) {
if (!vis[i]) {
--duration;
ans += vis[i] = 1;
}
}
}
return ans;
}
};
|
2,589
|
Minimum Time to Complete All Tasks
|
Hard
|
<p>There is a computer that can run an unlimited number of tasks <strong>at the same time</strong>. You are given a 2D integer array <code>tasks</code> where <code>tasks[i] = [start<sub>i</sub>, end<sub>i</sub>, duration<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> task should run for a total of <code>duration<sub>i</sub></code> seconds (not necessarily continuous) within the <strong>inclusive</strong> time range <code>[start<sub>i</sub>, end<sub>i</sub>]</code>.</p>
<p>You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle.</p>
<p>Return <em>the minimum time during which the computer should be turned on to complete all tasks</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> tasks = [[2,3,1],[4,5,1],[1,5,2]]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
- The first task can be run in the inclusive time range [2, 2].
- The second task can be run in the inclusive time range [5, 5].
- The third task can be run in the two inclusive time ranges [2, 2] and [5, 5].
The computer will be on for a total of 2 seconds.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> tasks = [[1,3,2],[2,5,3],[5,6,2]]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- The first task can be run in the inclusive time range [2, 3].
- The second task can be run in the inclusive time ranges [2, 3] and [5, 5].
- The third task can be run in the two inclusive time range [5, 6].
The computer will be on for a total of 4 seconds.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= tasks.length <= 2000</code></li>
<li><code>tasks[i].length == 3</code></li>
<li><code>1 <= start<sub>i</sub>, end<sub>i</sub> <= 2000</code></li>
<li><code>1 <= duration<sub>i</sub> <= end<sub>i</sub> - start<sub>i</sub> + 1 </code></li>
</ul>
|
Stack; Greedy; Array; Binary Search; Sorting
|
Go
|
func findMinimumTime(tasks [][]int) (ans int) {
sort.Slice(tasks, func(i, j int) bool { return tasks[i][1] < tasks[j][1] })
vis := [2010]int{}
for _, task := range tasks {
start, end, duration := task[0], task[1], task[2]
for _, x := range vis[start : end+1] {
duration -= x
}
for i := end; i >= start && duration > 0; i-- {
if vis[i] == 0 {
vis[i] = 1
duration--
ans++
}
}
}
return
}
|
2,589
|
Minimum Time to Complete All Tasks
|
Hard
|
<p>There is a computer that can run an unlimited number of tasks <strong>at the same time</strong>. You are given a 2D integer array <code>tasks</code> where <code>tasks[i] = [start<sub>i</sub>, end<sub>i</sub>, duration<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> task should run for a total of <code>duration<sub>i</sub></code> seconds (not necessarily continuous) within the <strong>inclusive</strong> time range <code>[start<sub>i</sub>, end<sub>i</sub>]</code>.</p>
<p>You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle.</p>
<p>Return <em>the minimum time during which the computer should be turned on to complete all tasks</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> tasks = [[2,3,1],[4,5,1],[1,5,2]]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
- The first task can be run in the inclusive time range [2, 2].
- The second task can be run in the inclusive time range [5, 5].
- The third task can be run in the two inclusive time ranges [2, 2] and [5, 5].
The computer will be on for a total of 2 seconds.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> tasks = [[1,3,2],[2,5,3],[5,6,2]]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- The first task can be run in the inclusive time range [2, 3].
- The second task can be run in the inclusive time ranges [2, 3] and [5, 5].
- The third task can be run in the two inclusive time range [5, 6].
The computer will be on for a total of 4 seconds.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= tasks.length <= 2000</code></li>
<li><code>tasks[i].length == 3</code></li>
<li><code>1 <= start<sub>i</sub>, end<sub>i</sub> <= 2000</code></li>
<li><code>1 <= duration<sub>i</sub> <= end<sub>i</sub> - start<sub>i</sub> + 1 </code></li>
</ul>
|
Stack; Greedy; Array; Binary Search; Sorting
|
Java
|
class Solution {
public int findMinimumTime(int[][] tasks) {
Arrays.sort(tasks, (a, b) -> a[1] - b[1]);
int[] vis = new int[2010];
int ans = 0;
for (var task : tasks) {
int start = task[0], end = task[1], duration = task[2];
for (int i = start; i <= end; ++i) {
duration -= vis[i];
}
for (int i = end; i >= start && duration > 0; --i) {
if (vis[i] == 0) {
--duration;
ans += vis[i] = 1;
}
}
}
return ans;
}
}
|
2,589
|
Minimum Time to Complete All Tasks
|
Hard
|
<p>There is a computer that can run an unlimited number of tasks <strong>at the same time</strong>. You are given a 2D integer array <code>tasks</code> where <code>tasks[i] = [start<sub>i</sub>, end<sub>i</sub>, duration<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> task should run for a total of <code>duration<sub>i</sub></code> seconds (not necessarily continuous) within the <strong>inclusive</strong> time range <code>[start<sub>i</sub>, end<sub>i</sub>]</code>.</p>
<p>You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle.</p>
<p>Return <em>the minimum time during which the computer should be turned on to complete all tasks</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> tasks = [[2,3,1],[4,5,1],[1,5,2]]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
- The first task can be run in the inclusive time range [2, 2].
- The second task can be run in the inclusive time range [5, 5].
- The third task can be run in the two inclusive time ranges [2, 2] and [5, 5].
The computer will be on for a total of 2 seconds.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> tasks = [[1,3,2],[2,5,3],[5,6,2]]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- The first task can be run in the inclusive time range [2, 3].
- The second task can be run in the inclusive time ranges [2, 3] and [5, 5].
- The third task can be run in the two inclusive time range [5, 6].
The computer will be on for a total of 4 seconds.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= tasks.length <= 2000</code></li>
<li><code>tasks[i].length == 3</code></li>
<li><code>1 <= start<sub>i</sub>, end<sub>i</sub> <= 2000</code></li>
<li><code>1 <= duration<sub>i</sub> <= end<sub>i</sub> - start<sub>i</sub> + 1 </code></li>
</ul>
|
Stack; Greedy; Array; Binary Search; Sorting
|
Python
|
class Solution:
def findMinimumTime(self, tasks: List[List[int]]) -> int:
tasks.sort(key=lambda x: x[1])
vis = [0] * 2010
ans = 0
for start, end, duration in tasks:
duration -= sum(vis[start : end + 1])
i = end
while i >= start and duration > 0:
if not vis[i]:
duration -= 1
vis[i] = 1
ans += 1
i -= 1
return ans
|
2,589
|
Minimum Time to Complete All Tasks
|
Hard
|
<p>There is a computer that can run an unlimited number of tasks <strong>at the same time</strong>. You are given a 2D integer array <code>tasks</code> where <code>tasks[i] = [start<sub>i</sub>, end<sub>i</sub>, duration<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> task should run for a total of <code>duration<sub>i</sub></code> seconds (not necessarily continuous) within the <strong>inclusive</strong> time range <code>[start<sub>i</sub>, end<sub>i</sub>]</code>.</p>
<p>You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle.</p>
<p>Return <em>the minimum time during which the computer should be turned on to complete all tasks</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> tasks = [[2,3,1],[4,5,1],[1,5,2]]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
- The first task can be run in the inclusive time range [2, 2].
- The second task can be run in the inclusive time range [5, 5].
- The third task can be run in the two inclusive time ranges [2, 2] and [5, 5].
The computer will be on for a total of 2 seconds.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> tasks = [[1,3,2],[2,5,3],[5,6,2]]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- The first task can be run in the inclusive time range [2, 3].
- The second task can be run in the inclusive time ranges [2, 3] and [5, 5].
- The third task can be run in the two inclusive time range [5, 6].
The computer will be on for a total of 4 seconds.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= tasks.length <= 2000</code></li>
<li><code>tasks[i].length == 3</code></li>
<li><code>1 <= start<sub>i</sub>, end<sub>i</sub> <= 2000</code></li>
<li><code>1 <= duration<sub>i</sub> <= end<sub>i</sub> - start<sub>i</sub> + 1 </code></li>
</ul>
|
Stack; Greedy; Array; Binary Search; Sorting
|
Rust
|
impl Solution {
pub fn find_minimum_time(tasks: Vec<Vec<i32>>) -> i32 {
let mut tasks = tasks;
tasks.sort_by(|a, b| a[1].cmp(&b[1]));
let mut vis = vec![0; 2010];
let mut ans = 0;
for task in tasks {
let start = task[0] as usize;
let end = task[1] as usize;
let mut duration = task[2] - vis[start..=end].iter().sum::<i32>();
let mut i = end;
while i >= start && duration > 0 {
if vis[i] == 0 {
duration -= 1;
vis[i] = 1;
ans += 1;
}
i -= 1;
}
}
ans
}
}
|
2,589
|
Minimum Time to Complete All Tasks
|
Hard
|
<p>There is a computer that can run an unlimited number of tasks <strong>at the same time</strong>. You are given a 2D integer array <code>tasks</code> where <code>tasks[i] = [start<sub>i</sub>, end<sub>i</sub>, duration<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> task should run for a total of <code>duration<sub>i</sub></code> seconds (not necessarily continuous) within the <strong>inclusive</strong> time range <code>[start<sub>i</sub>, end<sub>i</sub>]</code>.</p>
<p>You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle.</p>
<p>Return <em>the minimum time during which the computer should be turned on to complete all tasks</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> tasks = [[2,3,1],[4,5,1],[1,5,2]]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
- The first task can be run in the inclusive time range [2, 2].
- The second task can be run in the inclusive time range [5, 5].
- The third task can be run in the two inclusive time ranges [2, 2] and [5, 5].
The computer will be on for a total of 2 seconds.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> tasks = [[1,3,2],[2,5,3],[5,6,2]]
<strong>Output:</strong> 4
<strong>Explanation:</strong>
- The first task can be run in the inclusive time range [2, 3].
- The second task can be run in the inclusive time ranges [2, 3] and [5, 5].
- The third task can be run in the two inclusive time range [5, 6].
The computer will be on for a total of 4 seconds.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= tasks.length <= 2000</code></li>
<li><code>tasks[i].length == 3</code></li>
<li><code>1 <= start<sub>i</sub>, end<sub>i</sub> <= 2000</code></li>
<li><code>1 <= duration<sub>i</sub> <= end<sub>i</sub> - start<sub>i</sub> + 1 </code></li>
</ul>
|
Stack; Greedy; Array; Binary Search; Sorting
|
TypeScript
|
function findMinimumTime(tasks: number[][]): number {
tasks.sort((a, b) => a[1] - b[1]);
const vis: number[] = Array(2010).fill(0);
let ans = 0;
for (let [start, end, duration] of tasks) {
for (let i = start; i <= end; ++i) {
duration -= vis[i];
}
for (let i = end; i >= start && duration > 0; --i) {
if (vis[i] === 0) {
--duration;
ans += vis[i] = 1;
}
}
}
return ans;
}
|
2,590
|
Design a Todo List
|
Medium
|
<p>Design a Todo List Where users can add <strong>tasks</strong>, mark them as <strong>complete</strong>, or get a list of pending tasks. Users can also add <strong>tags</strong> to tasks and can filter the tasks by certain tags.</p>
<p>Implement the <code>TodoList</code> class:</p>
<ul>
<li><code>TodoList()</code> Initializes the object.</li>
<li><code>int addTask(int userId, String taskDescription, int dueDate, List<String> tags)</code> Adds a task for the user with the ID <code>userId</code> with a due date equal to <code>dueDate</code> and a list of tags attached to the task. The return value is the ID of the task. This ID starts at <code>1</code> and is <strong>sequentially</strong> increasing. That is, the first task's id should be <code>1</code>, the second task's id should be <code>2</code>, and so on.</li>
<li><code>List<String> getAllTasks(int userId)</code> Returns a list of all the tasks not marked as complete for the user with ID <code>userId</code>, ordered by the due date. You should return an empty list if the user has no uncompleted tasks.</li>
<li><code>List<String> getTasksForTag(int userId, String tag)</code> Returns a list of all the tasks that are not marked as complete for the user with the ID <code>userId</code> and have <code>tag</code> as one of their tags, ordered by their due date. Return an empty list if no such task exists.</li>
<li><code>void completeTask(int userId, int taskId)</code> Marks the task with the ID <code>taskId</code> as completed only if the task exists and the user with the ID <code>userId</code> has this task, and it is uncompleted.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["TodoList", "addTask", "addTask", "getAllTasks", "getAllTasks", "addTask", "getTasksForTag", "completeTask", "completeTask", "getTasksForTag", "getAllTasks"]
[[], [1, "Task1", 50, []], [1, "Task2", 100, ["P1"]], [1], [5], [1, "Task3", 30, ["P1"]], [1, "P1"], [5, 1], [1, 2], [1, "P1"], [1]]
<strong>Output</strong>
[null, 1, 2, ["Task1", "Task2"], [], 3, ["Task3", "Task2"], null, null, ["Task3"], ["Task3", "Task1"]]
<strong>Explanation</strong>
TodoList todoList = new TodoList();
todoList.addTask(1, "Task1", 50, []); // return 1. This adds a new task for the user with id 1.
todoList.addTask(1, "Task2", 100, ["P1"]); // return 2. This adds another task for the user with id 1.
todoList.getAllTasks(1); // return ["Task1", "Task2"]. User 1 has two uncompleted tasks so far.
todoList.getAllTasks(5); // return []. User 5 does not have any tasks so far.
todoList.addTask(1, "Task3", 30, ["P1"]); // return 3. This adds another task for the user with id 1.
todoList.getTasksForTag(1, "P1"); // return ["Task3", "Task2"]. This returns the uncompleted tasks that have the tag "P1" for the user with id 1.
todoList.completeTask(5, 1); // This does nothing, since task 1 does not belong to user 5.
todoList.completeTask(1, 2); // This marks task 2 as completed.
todoList.getTasksForTag(1, "P1"); // return ["Task3"]. This returns the uncompleted tasks that have the tag "P1" for the user with id 1.
// Notice that we did not include "Task2" because it is completed now.
todoList.getAllTasks(1); // return ["Task3", "Task1"]. User 1 now has 2 uncompleted tasks.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= userId, taskId, dueDate <= 100</code></li>
<li><code>0 <= tags.length <= 100</code></li>
<li><code>1 <= taskDescription.length <= 50</code></li>
<li><code>1 <= tags[i].length, tag.length <= 20</code></li>
<li>All <code>dueDate</code> values are unique.</li>
<li>All the strings consist of lowercase and uppercase English letters and digits.</li>
<li>At most <code>100</code> calls will be made for each method.</li>
</ul>
|
Design; Array; Hash Table; String; Sorting
|
Java
|
class Task {
int taskId;
String taskName;
int dueDate;
Set<String> tags;
boolean finish;
public Task(int taskId, String taskName, int dueDate, Set<String> tags) {
this.taskId = taskId;
this.taskName = taskName;
this.dueDate = dueDate;
this.tags = tags;
}
}
class TodoList {
private int i = 1;
private Map<Integer, TreeSet<Task>> tasks = new HashMap<>();
public TodoList() {
}
public int addTask(int userId, String taskDescription, int dueDate, List<String> tags) {
Task task = new Task(i++, taskDescription, dueDate, new HashSet<>(tags));
tasks.computeIfAbsent(userId, k -> new TreeSet<>(Comparator.comparingInt(a -> a.dueDate)))
.add(task);
return task.taskId;
}
public List<String> getAllTasks(int userId) {
List<String> ans = new ArrayList<>();
if (tasks.containsKey(userId)) {
for (Task task : tasks.get(userId)) {
if (!task.finish) {
ans.add(task.taskName);
}
}
}
return ans;
}
public List<String> getTasksForTag(int userId, String tag) {
List<String> ans = new ArrayList<>();
if (tasks.containsKey(userId)) {
for (Task task : tasks.get(userId)) {
if (task.tags.contains(tag) && !task.finish) {
ans.add(task.taskName);
}
}
}
return ans;
}
public void completeTask(int userId, int taskId) {
if (tasks.containsKey(userId)) {
for (Task task : tasks.get(userId)) {
if (task.taskId == taskId) {
task.finish = true;
break;
}
}
}
}
}
/**
* Your TodoList object will be instantiated and called as such:
* TodoList obj = new TodoList();
* int param_1 = obj.addTask(userId,taskDescription,dueDate,tags);
* List<String> param_2 = obj.getAllTasks(userId);
* List<String> param_3 = obj.getTasksForTag(userId,tag);
* obj.completeTask(userId,taskId);
*/
|
2,590
|
Design a Todo List
|
Medium
|
<p>Design a Todo List Where users can add <strong>tasks</strong>, mark them as <strong>complete</strong>, or get a list of pending tasks. Users can also add <strong>tags</strong> to tasks and can filter the tasks by certain tags.</p>
<p>Implement the <code>TodoList</code> class:</p>
<ul>
<li><code>TodoList()</code> Initializes the object.</li>
<li><code>int addTask(int userId, String taskDescription, int dueDate, List<String> tags)</code> Adds a task for the user with the ID <code>userId</code> with a due date equal to <code>dueDate</code> and a list of tags attached to the task. The return value is the ID of the task. This ID starts at <code>1</code> and is <strong>sequentially</strong> increasing. That is, the first task's id should be <code>1</code>, the second task's id should be <code>2</code>, and so on.</li>
<li><code>List<String> getAllTasks(int userId)</code> Returns a list of all the tasks not marked as complete for the user with ID <code>userId</code>, ordered by the due date. You should return an empty list if the user has no uncompleted tasks.</li>
<li><code>List<String> getTasksForTag(int userId, String tag)</code> Returns a list of all the tasks that are not marked as complete for the user with the ID <code>userId</code> and have <code>tag</code> as one of their tags, ordered by their due date. Return an empty list if no such task exists.</li>
<li><code>void completeTask(int userId, int taskId)</code> Marks the task with the ID <code>taskId</code> as completed only if the task exists and the user with the ID <code>userId</code> has this task, and it is uncompleted.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["TodoList", "addTask", "addTask", "getAllTasks", "getAllTasks", "addTask", "getTasksForTag", "completeTask", "completeTask", "getTasksForTag", "getAllTasks"]
[[], [1, "Task1", 50, []], [1, "Task2", 100, ["P1"]], [1], [5], [1, "Task3", 30, ["P1"]], [1, "P1"], [5, 1], [1, 2], [1, "P1"], [1]]
<strong>Output</strong>
[null, 1, 2, ["Task1", "Task2"], [], 3, ["Task3", "Task2"], null, null, ["Task3"], ["Task3", "Task1"]]
<strong>Explanation</strong>
TodoList todoList = new TodoList();
todoList.addTask(1, "Task1", 50, []); // return 1. This adds a new task for the user with id 1.
todoList.addTask(1, "Task2", 100, ["P1"]); // return 2. This adds another task for the user with id 1.
todoList.getAllTasks(1); // return ["Task1", "Task2"]. User 1 has two uncompleted tasks so far.
todoList.getAllTasks(5); // return []. User 5 does not have any tasks so far.
todoList.addTask(1, "Task3", 30, ["P1"]); // return 3. This adds another task for the user with id 1.
todoList.getTasksForTag(1, "P1"); // return ["Task3", "Task2"]. This returns the uncompleted tasks that have the tag "P1" for the user with id 1.
todoList.completeTask(5, 1); // This does nothing, since task 1 does not belong to user 5.
todoList.completeTask(1, 2); // This marks task 2 as completed.
todoList.getTasksForTag(1, "P1"); // return ["Task3"]. This returns the uncompleted tasks that have the tag "P1" for the user with id 1.
// Notice that we did not include "Task2" because it is completed now.
todoList.getAllTasks(1); // return ["Task3", "Task1"]. User 1 now has 2 uncompleted tasks.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= userId, taskId, dueDate <= 100</code></li>
<li><code>0 <= tags.length <= 100</code></li>
<li><code>1 <= taskDescription.length <= 50</code></li>
<li><code>1 <= tags[i].length, tag.length <= 20</code></li>
<li>All <code>dueDate</code> values are unique.</li>
<li>All the strings consist of lowercase and uppercase English letters and digits.</li>
<li>At most <code>100</code> calls will be made for each method.</li>
</ul>
|
Design; Array; Hash Table; String; Sorting
|
Python
|
class TodoList:
def __init__(self):
self.i = 1
self.tasks = defaultdict(SortedList)
def addTask(
self, userId: int, taskDescription: str, dueDate: int, tags: List[str]
) -> int:
taskId = self.i
self.i += 1
self.tasks[userId].add([dueDate, taskDescription, set(tags), taskId, False])
return taskId
def getAllTasks(self, userId: int) -> List[str]:
return [x[1] for x in self.tasks[userId] if not x[4]]
def getTasksForTag(self, userId: int, tag: str) -> List[str]:
return [x[1] for x in self.tasks[userId] if not x[4] and tag in x[2]]
def completeTask(self, userId: int, taskId: int) -> None:
for task in self.tasks[userId]:
if task[3] == taskId:
task[4] = True
break
# Your TodoList object will be instantiated and called as such:
# obj = TodoList()
# param_1 = obj.addTask(userId,taskDescription,dueDate,tags)
# param_2 = obj.getAllTasks(userId)
# param_3 = obj.getTasksForTag(userId,tag)
# obj.completeTask(userId,taskId)
|
2,590
|
Design a Todo List
|
Medium
|
<p>Design a Todo List Where users can add <strong>tasks</strong>, mark them as <strong>complete</strong>, or get a list of pending tasks. Users can also add <strong>tags</strong> to tasks and can filter the tasks by certain tags.</p>
<p>Implement the <code>TodoList</code> class:</p>
<ul>
<li><code>TodoList()</code> Initializes the object.</li>
<li><code>int addTask(int userId, String taskDescription, int dueDate, List<String> tags)</code> Adds a task for the user with the ID <code>userId</code> with a due date equal to <code>dueDate</code> and a list of tags attached to the task. The return value is the ID of the task. This ID starts at <code>1</code> and is <strong>sequentially</strong> increasing. That is, the first task's id should be <code>1</code>, the second task's id should be <code>2</code>, and so on.</li>
<li><code>List<String> getAllTasks(int userId)</code> Returns a list of all the tasks not marked as complete for the user with ID <code>userId</code>, ordered by the due date. You should return an empty list if the user has no uncompleted tasks.</li>
<li><code>List<String> getTasksForTag(int userId, String tag)</code> Returns a list of all the tasks that are not marked as complete for the user with the ID <code>userId</code> and have <code>tag</code> as one of their tags, ordered by their due date. Return an empty list if no such task exists.</li>
<li><code>void completeTask(int userId, int taskId)</code> Marks the task with the ID <code>taskId</code> as completed only if the task exists and the user with the ID <code>userId</code> has this task, and it is uncompleted.</li>
</ul>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["TodoList", "addTask", "addTask", "getAllTasks", "getAllTasks", "addTask", "getTasksForTag", "completeTask", "completeTask", "getTasksForTag", "getAllTasks"]
[[], [1, "Task1", 50, []], [1, "Task2", 100, ["P1"]], [1], [5], [1, "Task3", 30, ["P1"]], [1, "P1"], [5, 1], [1, 2], [1, "P1"], [1]]
<strong>Output</strong>
[null, 1, 2, ["Task1", "Task2"], [], 3, ["Task3", "Task2"], null, null, ["Task3"], ["Task3", "Task1"]]
<strong>Explanation</strong>
TodoList todoList = new TodoList();
todoList.addTask(1, "Task1", 50, []); // return 1. This adds a new task for the user with id 1.
todoList.addTask(1, "Task2", 100, ["P1"]); // return 2. This adds another task for the user with id 1.
todoList.getAllTasks(1); // return ["Task1", "Task2"]. User 1 has two uncompleted tasks so far.
todoList.getAllTasks(5); // return []. User 5 does not have any tasks so far.
todoList.addTask(1, "Task3", 30, ["P1"]); // return 3. This adds another task for the user with id 1.
todoList.getTasksForTag(1, "P1"); // return ["Task3", "Task2"]. This returns the uncompleted tasks that have the tag "P1" for the user with id 1.
todoList.completeTask(5, 1); // This does nothing, since task 1 does not belong to user 5.
todoList.completeTask(1, 2); // This marks task 2 as completed.
todoList.getTasksForTag(1, "P1"); // return ["Task3"]. This returns the uncompleted tasks that have the tag "P1" for the user with id 1.
// Notice that we did not include "Task2" because it is completed now.
todoList.getAllTasks(1); // return ["Task3", "Task1"]. User 1 now has 2 uncompleted tasks.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= userId, taskId, dueDate <= 100</code></li>
<li><code>0 <= tags.length <= 100</code></li>
<li><code>1 <= taskDescription.length <= 50</code></li>
<li><code>1 <= tags[i].length, tag.length <= 20</code></li>
<li>All <code>dueDate</code> values are unique.</li>
<li>All the strings consist of lowercase and uppercase English letters and digits.</li>
<li>At most <code>100</code> calls will be made for each method.</li>
</ul>
|
Design; Array; Hash Table; String; Sorting
|
Rust
|
use std::collections::{HashMap, HashSet};
#[derive(Clone)]
struct Task {
task_id: i32,
description: String,
tags: HashSet<String>,
due_date: i32,
}
struct TodoList {
/// The global task id
id: i32,
/// The mapping from `user_id` to `task`
user_map: HashMap<i32, Vec<Task>>,
}
impl TodoList {
fn new() -> Self {
Self {
id: 1,
user_map: HashMap::new(),
}
}
fn add_task(
&mut self,
user_id: i32,
task_description: String,
due_date: i32,
tags: Vec<String>,
) -> i32 {
if self.user_map.contains_key(&user_id) {
// Just add the task
self.user_map.get_mut(&user_id).unwrap().push(Task {
task_id: self.id,
description: task_description,
tags: tags.into_iter().collect::<HashSet<String>>(),
due_date,
});
// Increase the global id
self.id += 1;
return self.id - 1;
}
// Otherwise, create a new user
self.user_map.insert(
user_id,
vec![Task {
task_id: self.id,
description: task_description,
tags: tags.into_iter().collect::<HashSet<String>>(),
due_date,
}],
);
self.id += 1;
self.id - 1
}
fn get_all_tasks(&self, user_id: i32) -> Vec<String> {
if !self.user_map.contains_key(&user_id) || self.user_map.get(&user_id).unwrap().is_empty()
{
return vec![];
}
// Get the task vector
let mut ret_vec = (*self.user_map.get(&user_id).unwrap()).clone();
// Sort by due date
ret_vec.sort_by(|lhs, rhs| lhs.due_date.cmp(&rhs.due_date));
// Return the description vector
ret_vec.into_iter().map(|x| x.description).collect()
}
fn get_tasks_for_tag(&self, user_id: i32, tag: String) -> Vec<String> {
if !self.user_map.contains_key(&user_id) || self.user_map.get(&user_id).unwrap().is_empty()
{
return vec![];
}
// Get the task vector
let mut ret_vec = (*self.user_map.get(&user_id).unwrap()).clone();
// Sort by due date
ret_vec.sort_by(|lhs, rhs| lhs.due_date.cmp(&rhs.due_date));
// Return the description vector
ret_vec
.into_iter()
.filter(|x| x.tags.contains(&tag))
.map(|x| x.description)
.collect()
}
fn complete_task(&mut self, user_id: i32, task_id: i32) {
if !self.user_map.contains_key(&user_id) || self.user_map.get(&user_id).unwrap().is_empty()
{
return;
}
self.user_map
.get_mut(&user_id)
.unwrap()
.retain(|x| (*x).task_id != task_id);
}
}
|
2,591
|
Distribute Money to Maximum Children
|
Easy
|
<p>You are given an integer <code>money</code> denoting the amount of money (in dollars) that you have and another integer <code>children</code> denoting the number of children that you must distribute the money to.</p>
<p>You have to distribute the money according to the following rules:</p>
<ul>
<li>All money must be distributed.</li>
<li>Everyone must receive at least <code>1</code> dollar.</li>
<li>Nobody receives <code>4</code> dollars.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> number of children who may receive <strong>exactly</strong> </em><code>8</code> <em>dollars if you distribute the money according to the aforementioned rules</em>. If there is no way to distribute the money, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> money = 20, children = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong>
The maximum number of children with 8 dollars will be 1. One of the ways to distribute the money is:
- 8 dollars to the first child.
- 9 dollars to the second child.
- 3 dollars to the third child.
It can be proven that no distribution exists such that number of children getting 8 dollars is greater than 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> money = 16, children = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> Each child can be given 8 dollars.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= money <= 200</code></li>
<li><code>2 <= children <= 30</code></li>
</ul>
|
Greedy; Math
|
C++
|
class Solution {
public:
int distMoney(int money, int children) {
if (money < children) {
return -1;
}
if (money > 8 * children) {
return children - 1;
}
if (money == 8 * children - 4) {
return children - 2;
}
// money-8x >= children-x, x <= (money-children)/7
return (money - children) / 7;
}
};
|
2,591
|
Distribute Money to Maximum Children
|
Easy
|
<p>You are given an integer <code>money</code> denoting the amount of money (in dollars) that you have and another integer <code>children</code> denoting the number of children that you must distribute the money to.</p>
<p>You have to distribute the money according to the following rules:</p>
<ul>
<li>All money must be distributed.</li>
<li>Everyone must receive at least <code>1</code> dollar.</li>
<li>Nobody receives <code>4</code> dollars.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> number of children who may receive <strong>exactly</strong> </em><code>8</code> <em>dollars if you distribute the money according to the aforementioned rules</em>. If there is no way to distribute the money, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> money = 20, children = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong>
The maximum number of children with 8 dollars will be 1. One of the ways to distribute the money is:
- 8 dollars to the first child.
- 9 dollars to the second child.
- 3 dollars to the third child.
It can be proven that no distribution exists such that number of children getting 8 dollars is greater than 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> money = 16, children = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> Each child can be given 8 dollars.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= money <= 200</code></li>
<li><code>2 <= children <= 30</code></li>
</ul>
|
Greedy; Math
|
Go
|
func distMoney(money int, children int) int {
if money < children {
return -1
}
if money > 8*children {
return children - 1
}
if money == 8*children-4 {
return children - 2
}
// money-8x >= children-x, x <= (money-children)/7
return (money - children) / 7
}
|
2,591
|
Distribute Money to Maximum Children
|
Easy
|
<p>You are given an integer <code>money</code> denoting the amount of money (in dollars) that you have and another integer <code>children</code> denoting the number of children that you must distribute the money to.</p>
<p>You have to distribute the money according to the following rules:</p>
<ul>
<li>All money must be distributed.</li>
<li>Everyone must receive at least <code>1</code> dollar.</li>
<li>Nobody receives <code>4</code> dollars.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> number of children who may receive <strong>exactly</strong> </em><code>8</code> <em>dollars if you distribute the money according to the aforementioned rules</em>. If there is no way to distribute the money, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> money = 20, children = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong>
The maximum number of children with 8 dollars will be 1. One of the ways to distribute the money is:
- 8 dollars to the first child.
- 9 dollars to the second child.
- 3 dollars to the third child.
It can be proven that no distribution exists such that number of children getting 8 dollars is greater than 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> money = 16, children = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> Each child can be given 8 dollars.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= money <= 200</code></li>
<li><code>2 <= children <= 30</code></li>
</ul>
|
Greedy; Math
|
Java
|
class Solution {
public int distMoney(int money, int children) {
if (money < children) {
return -1;
}
if (money > 8 * children) {
return children - 1;
}
if (money == 8 * children - 4) {
return children - 2;
}
// money-8x >= children-x, x <= (money-children)/7
return (money - children) / 7;
}
}
|
2,591
|
Distribute Money to Maximum Children
|
Easy
|
<p>You are given an integer <code>money</code> denoting the amount of money (in dollars) that you have and another integer <code>children</code> denoting the number of children that you must distribute the money to.</p>
<p>You have to distribute the money according to the following rules:</p>
<ul>
<li>All money must be distributed.</li>
<li>Everyone must receive at least <code>1</code> dollar.</li>
<li>Nobody receives <code>4</code> dollars.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> number of children who may receive <strong>exactly</strong> </em><code>8</code> <em>dollars if you distribute the money according to the aforementioned rules</em>. If there is no way to distribute the money, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> money = 20, children = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong>
The maximum number of children with 8 dollars will be 1. One of the ways to distribute the money is:
- 8 dollars to the first child.
- 9 dollars to the second child.
- 3 dollars to the third child.
It can be proven that no distribution exists such that number of children getting 8 dollars is greater than 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> money = 16, children = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> Each child can be given 8 dollars.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= money <= 200</code></li>
<li><code>2 <= children <= 30</code></li>
</ul>
|
Greedy; Math
|
Python
|
class Solution:
def distMoney(self, money: int, children: int) -> int:
if money < children:
return -1
if money > 8 * children:
return children - 1
if money == 8 * children - 4:
return children - 2
# money-8x >= children-x, x <= (money-children)/7
return (money - children) // 7
|
2,591
|
Distribute Money to Maximum Children
|
Easy
|
<p>You are given an integer <code>money</code> denoting the amount of money (in dollars) that you have and another integer <code>children</code> denoting the number of children that you must distribute the money to.</p>
<p>You have to distribute the money according to the following rules:</p>
<ul>
<li>All money must be distributed.</li>
<li>Everyone must receive at least <code>1</code> dollar.</li>
<li>Nobody receives <code>4</code> dollars.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> number of children who may receive <strong>exactly</strong> </em><code>8</code> <em>dollars if you distribute the money according to the aforementioned rules</em>. If there is no way to distribute the money, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> money = 20, children = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong>
The maximum number of children with 8 dollars will be 1. One of the ways to distribute the money is:
- 8 dollars to the first child.
- 9 dollars to the second child.
- 3 dollars to the third child.
It can be proven that no distribution exists such that number of children getting 8 dollars is greater than 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> money = 16, children = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> Each child can be given 8 dollars.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= money <= 200</code></li>
<li><code>2 <= children <= 30</code></li>
</ul>
|
Greedy; Math
|
Rust
|
impl Solution {
pub fn dist_money(money: i32, children: i32) -> i32 {
if money < children {
return -1;
}
if money > children * 8 {
return children - 1;
}
if money == children * 8 - 4 {
return children - 2;
}
(money - children) / 7
}
}
|
2,591
|
Distribute Money to Maximum Children
|
Easy
|
<p>You are given an integer <code>money</code> denoting the amount of money (in dollars) that you have and another integer <code>children</code> denoting the number of children that you must distribute the money to.</p>
<p>You have to distribute the money according to the following rules:</p>
<ul>
<li>All money must be distributed.</li>
<li>Everyone must receive at least <code>1</code> dollar.</li>
<li>Nobody receives <code>4</code> dollars.</li>
</ul>
<p>Return <em>the <strong>maximum</strong> number of children who may receive <strong>exactly</strong> </em><code>8</code> <em>dollars if you distribute the money according to the aforementioned rules</em>. If there is no way to distribute the money, return <code>-1</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> money = 20, children = 3
<strong>Output:</strong> 1
<strong>Explanation:</strong>
The maximum number of children with 8 dollars will be 1. One of the ways to distribute the money is:
- 8 dollars to the first child.
- 9 dollars to the second child.
- 3 dollars to the third child.
It can be proven that no distribution exists such that number of children getting 8 dollars is greater than 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> money = 16, children = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> Each child can be given 8 dollars.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= money <= 200</code></li>
<li><code>2 <= children <= 30</code></li>
</ul>
|
Greedy; Math
|
TypeScript
|
function distMoney(money: number, children: number): number {
if (money < children) {
return -1;
}
if (money > 8 * children) {
return children - 1;
}
if (money === 8 * children - 4) {
return children - 2;
}
return Math.floor((money - children) / 7);
}
|
2,592
|
Maximize Greatness of an Array
|
Medium
|
<p>You are given a 0-indexed integer array <code>nums</code>. You are allowed to permute <code>nums</code> into a new array <code>perm</code> of your choosing.</p>
<p>We define the <strong>greatness</strong> of <code>nums</code> be the number of indices <code>0 <= i < nums.length</code> for which <code>perm[i] > nums[i]</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible greatness you can achieve after permuting</em> <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,2,1,3,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> One of the optimal rearrangements is perm = [2,5,1,3,3,1,1].
At indices = 0, 1, 3, and 4, perm[i] > nums[i]. Hence, we return 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can prove the optimal perm is [2,3,4,1].
At indices = 0, 1, and 2, perm[i] > nums[i]. Hence, we return 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Two Pointers; Sorting
|
C++
|
class Solution {
public:
int maximizeGreatness(vector<int>& nums) {
sort(nums.begin(), nums.end());
int i = 0;
for (int x : nums) {
i += x > nums[i];
}
return i;
}
};
|
2,592
|
Maximize Greatness of an Array
|
Medium
|
<p>You are given a 0-indexed integer array <code>nums</code>. You are allowed to permute <code>nums</code> into a new array <code>perm</code> of your choosing.</p>
<p>We define the <strong>greatness</strong> of <code>nums</code> be the number of indices <code>0 <= i < nums.length</code> for which <code>perm[i] > nums[i]</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible greatness you can achieve after permuting</em> <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,2,1,3,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> One of the optimal rearrangements is perm = [2,5,1,3,3,1,1].
At indices = 0, 1, 3, and 4, perm[i] > nums[i]. Hence, we return 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can prove the optimal perm is [2,3,4,1].
At indices = 0, 1, and 2, perm[i] > nums[i]. Hence, we return 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Two Pointers; Sorting
|
Go
|
func maximizeGreatness(nums []int) int {
sort.Ints(nums)
i := 0
for _, x := range nums {
if x > nums[i] {
i++
}
}
return i
}
|
2,592
|
Maximize Greatness of an Array
|
Medium
|
<p>You are given a 0-indexed integer array <code>nums</code>. You are allowed to permute <code>nums</code> into a new array <code>perm</code> of your choosing.</p>
<p>We define the <strong>greatness</strong> of <code>nums</code> be the number of indices <code>0 <= i < nums.length</code> for which <code>perm[i] > nums[i]</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible greatness you can achieve after permuting</em> <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,2,1,3,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> One of the optimal rearrangements is perm = [2,5,1,3,3,1,1].
At indices = 0, 1, 3, and 4, perm[i] > nums[i]. Hence, we return 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can prove the optimal perm is [2,3,4,1].
At indices = 0, 1, and 2, perm[i] > nums[i]. Hence, we return 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Two Pointers; Sorting
|
Java
|
class Solution {
public int maximizeGreatness(int[] nums) {
Arrays.sort(nums);
int i = 0;
for (int x : nums) {
if (x > nums[i]) {
++i;
}
}
return i;
}
}
|
2,592
|
Maximize Greatness of an Array
|
Medium
|
<p>You are given a 0-indexed integer array <code>nums</code>. You are allowed to permute <code>nums</code> into a new array <code>perm</code> of your choosing.</p>
<p>We define the <strong>greatness</strong> of <code>nums</code> be the number of indices <code>0 <= i < nums.length</code> for which <code>perm[i] > nums[i]</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible greatness you can achieve after permuting</em> <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,2,1,3,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> One of the optimal rearrangements is perm = [2,5,1,3,3,1,1].
At indices = 0, 1, 3, and 4, perm[i] > nums[i]. Hence, we return 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can prove the optimal perm is [2,3,4,1].
At indices = 0, 1, and 2, perm[i] > nums[i]. Hence, we return 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Two Pointers; Sorting
|
Python
|
class Solution:
def maximizeGreatness(self, nums: List[int]) -> int:
nums.sort()
i = 0
for x in nums:
i += x > nums[i]
return i
|
2,592
|
Maximize Greatness of an Array
|
Medium
|
<p>You are given a 0-indexed integer array <code>nums</code>. You are allowed to permute <code>nums</code> into a new array <code>perm</code> of your choosing.</p>
<p>We define the <strong>greatness</strong> of <code>nums</code> be the number of indices <code>0 <= i < nums.length</code> for which <code>perm[i] > nums[i]</code>.</p>
<p>Return <em>the <strong>maximum</strong> possible greatness you can achieve after permuting</em> <code>nums</code>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,3,5,2,1,3,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> One of the optimal rearrangements is perm = [2,5,1,3,3,1,1].
At indices = 0, 1, 3, and 4, perm[i] > nums[i]. Hence, we return 4.</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can prove the optimal perm is [2,3,4,1].
At indices = 0, 1, and 2, perm[i] > nums[i]. Hence, we return 3.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Two Pointers; Sorting
|
TypeScript
|
function maximizeGreatness(nums: number[]): number {
nums.sort((a, b) => a - b);
let i = 0;
for (const x of nums) {
if (x > nums[i]) {
i += 1;
}
}
return i;
}
|
2,593
|
Find Score of an Array After Marking All Elements
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>Starting with <code>score = 0</code>, apply the following algorithm:</p>
<ul>
<li>Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index.</li>
<li>Add the value of the chosen integer to <code>score</code>.</li>
<li>Mark <strong>the chosen element and its two adjacent elements if they exist</strong>.</li>
<li>Repeat until all the array elements are marked.</li>
</ul>
<p>Return <em>the score you get after applying the above algorithm</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,4,5,2]
<strong>Output:</strong> 7
<strong>Explanation:</strong> We mark the elements as follows:
- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [<u>2</u>,<u>1</u>,<u>3</u>,4,5,2].
- 2 is the smallest unmarked element, so we mark it and its left adjacent element: [<u>2</u>,<u>1</u>,<u>3</u>,4,<u>5</u>,<u>2</u>].
- 4 is the only remaining unmarked element, so we mark it: [<u>2</u>,<u>1</u>,<u>3</u>,<u>4</u>,<u>5</u>,<u>2</u>].
Our score is 1 + 2 + 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,5,1,3,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> We mark the elements as follows:
- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,3,<u>5</u>,<u>1</u>,<u>3</u>,2].
- 2 is the smallest unmarked element, since there are two of them, we choose the left-most one, so we mark the one at index 0 and its right adjacent element: [<u>2</u>,<u>3</u>,<u>5</u>,<u>1</u>,<u>3</u>,2].
- 2 is the only remaining unmarked element, so we mark it: [<u>2</u>,<u>3</u>,<u>5</u>,<u>1</u>,<u>3</u>,<u>2</u>].
Our score is 1 + 2 + 2 = 5.
</pre>
<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>6</sup></code></li>
</ul>
|
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
|
C++
|
class Solution {
public:
long long findScore(vector<int>& nums) {
int n = nums.size();
vector<bool> vis(n);
using pii = pair<int, int>;
priority_queue<pii, vector<pii>, greater<pii>> q;
for (int i = 0; i < n; ++i) {
q.emplace(nums[i], i);
}
long long ans = 0;
while (!q.empty()) {
auto [x, i] = q.top();
q.pop();
ans += x;
vis[i] = true;
if (i + 1 < n) {
vis[i + 1] = true;
}
if (i - 1 >= 0) {
vis[i - 1] = true;
}
while (!q.empty() && vis[q.top().second]) {
q.pop();
}
}
return ans;
}
};
|
2,593
|
Find Score of an Array After Marking All Elements
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>Starting with <code>score = 0</code>, apply the following algorithm:</p>
<ul>
<li>Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index.</li>
<li>Add the value of the chosen integer to <code>score</code>.</li>
<li>Mark <strong>the chosen element and its two adjacent elements if they exist</strong>.</li>
<li>Repeat until all the array elements are marked.</li>
</ul>
<p>Return <em>the score you get after applying the above algorithm</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,4,5,2]
<strong>Output:</strong> 7
<strong>Explanation:</strong> We mark the elements as follows:
- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [<u>2</u>,<u>1</u>,<u>3</u>,4,5,2].
- 2 is the smallest unmarked element, so we mark it and its left adjacent element: [<u>2</u>,<u>1</u>,<u>3</u>,4,<u>5</u>,<u>2</u>].
- 4 is the only remaining unmarked element, so we mark it: [<u>2</u>,<u>1</u>,<u>3</u>,<u>4</u>,<u>5</u>,<u>2</u>].
Our score is 1 + 2 + 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,5,1,3,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> We mark the elements as follows:
- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,3,<u>5</u>,<u>1</u>,<u>3</u>,2].
- 2 is the smallest unmarked element, since there are two of them, we choose the left-most one, so we mark the one at index 0 and its right adjacent element: [<u>2</u>,<u>3</u>,<u>5</u>,<u>1</u>,<u>3</u>,2].
- 2 is the only remaining unmarked element, so we mark it: [<u>2</u>,<u>3</u>,<u>5</u>,<u>1</u>,<u>3</u>,<u>2</u>].
Our score is 1 + 2 + 2 = 5.
</pre>
<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>6</sup></code></li>
</ul>
|
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
|
Go
|
func findScore(nums []int) (ans int64) {
h := hp{}
for i, x := range nums {
heap.Push(&h, pair{x, i})
}
n := len(nums)
vis := make([]bool, n)
for len(h) > 0 {
p := heap.Pop(&h).(pair)
x, i := p.x, p.i
ans += int64(x)
vis[i] = true
for _, j := range []int{i - 1, i + 1} {
if j >= 0 && j < n {
vis[j] = true
}
}
for len(h) > 0 && vis[h[0].i] {
heap.Pop(&h)
}
}
return
}
type pair struct{ x, i int }
type hp []pair
func (h hp) Len() int { return len(h) }
func (h hp) Less(i, j int) bool { return h[i].x < h[j].x || (h[i].x == h[j].x && h[i].i < h[j].i) }
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v any) { *h = append(*h, v.(pair)) }
func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
|
2,593
|
Find Score of an Array After Marking All Elements
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>Starting with <code>score = 0</code>, apply the following algorithm:</p>
<ul>
<li>Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index.</li>
<li>Add the value of the chosen integer to <code>score</code>.</li>
<li>Mark <strong>the chosen element and its two adjacent elements if they exist</strong>.</li>
<li>Repeat until all the array elements are marked.</li>
</ul>
<p>Return <em>the score you get after applying the above algorithm</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,4,5,2]
<strong>Output:</strong> 7
<strong>Explanation:</strong> We mark the elements as follows:
- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [<u>2</u>,<u>1</u>,<u>3</u>,4,5,2].
- 2 is the smallest unmarked element, so we mark it and its left adjacent element: [<u>2</u>,<u>1</u>,<u>3</u>,4,<u>5</u>,<u>2</u>].
- 4 is the only remaining unmarked element, so we mark it: [<u>2</u>,<u>1</u>,<u>3</u>,<u>4</u>,<u>5</u>,<u>2</u>].
Our score is 1 + 2 + 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,5,1,3,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> We mark the elements as follows:
- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,3,<u>5</u>,<u>1</u>,<u>3</u>,2].
- 2 is the smallest unmarked element, since there are two of them, we choose the left-most one, so we mark the one at index 0 and its right adjacent element: [<u>2</u>,<u>3</u>,<u>5</u>,<u>1</u>,<u>3</u>,2].
- 2 is the only remaining unmarked element, so we mark it: [<u>2</u>,<u>3</u>,<u>5</u>,<u>1</u>,<u>3</u>,<u>2</u>].
Our score is 1 + 2 + 2 = 5.
</pre>
<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>6</sup></code></li>
</ul>
|
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
|
Java
|
class Solution {
public long findScore(int[] nums) {
int n = nums.length;
boolean[] vis = new boolean[n];
PriorityQueue<int[]> q
= new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
for (int i = 0; i < n; ++i) {
q.offer(new int[] {nums[i], i});
}
long ans = 0;
while (!q.isEmpty()) {
var p = q.poll();
ans += p[0];
vis[p[1]] = true;
for (int j : List.of(p[1] - 1, p[1] + 1)) {
if (j >= 0 && j < n) {
vis[j] = true;
}
}
while (!q.isEmpty() && vis[q.peek()[1]]) {
q.poll();
}
}
return ans;
}
}
|
2,593
|
Find Score of an Array After Marking All Elements
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>Starting with <code>score = 0</code>, apply the following algorithm:</p>
<ul>
<li>Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index.</li>
<li>Add the value of the chosen integer to <code>score</code>.</li>
<li>Mark <strong>the chosen element and its two adjacent elements if they exist</strong>.</li>
<li>Repeat until all the array elements are marked.</li>
</ul>
<p>Return <em>the score you get after applying the above algorithm</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,4,5,2]
<strong>Output:</strong> 7
<strong>Explanation:</strong> We mark the elements as follows:
- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [<u>2</u>,<u>1</u>,<u>3</u>,4,5,2].
- 2 is the smallest unmarked element, so we mark it and its left adjacent element: [<u>2</u>,<u>1</u>,<u>3</u>,4,<u>5</u>,<u>2</u>].
- 4 is the only remaining unmarked element, so we mark it: [<u>2</u>,<u>1</u>,<u>3</u>,<u>4</u>,<u>5</u>,<u>2</u>].
Our score is 1 + 2 + 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,5,1,3,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> We mark the elements as follows:
- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,3,<u>5</u>,<u>1</u>,<u>3</u>,2].
- 2 is the smallest unmarked element, since there are two of them, we choose the left-most one, so we mark the one at index 0 and its right adjacent element: [<u>2</u>,<u>3</u>,<u>5</u>,<u>1</u>,<u>3</u>,2].
- 2 is the only remaining unmarked element, so we mark it: [<u>2</u>,<u>3</u>,<u>5</u>,<u>1</u>,<u>3</u>,<u>2</u>].
Our score is 1 + 2 + 2 = 5.
</pre>
<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>6</sup></code></li>
</ul>
|
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
|
Python
|
class Solution:
def findScore(self, nums: List[int]) -> int:
n = len(nums)
vis = [False] * n
q = [(x, i) for i, x in enumerate(nums)]
heapify(q)
ans = 0
while q:
x, i = heappop(q)
ans += x
vis[i] = True
for j in (i - 1, i + 1):
if 0 <= j < n:
vis[j] = True
while q and vis[q[0][1]]:
heappop(q)
return ans
|
2,593
|
Find Score of an Array After Marking All Elements
|
Medium
|
<p>You are given an array <code>nums</code> consisting of positive integers.</p>
<p>Starting with <code>score = 0</code>, apply the following algorithm:</p>
<ul>
<li>Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index.</li>
<li>Add the value of the chosen integer to <code>score</code>.</li>
<li>Mark <strong>the chosen element and its two adjacent elements if they exist</strong>.</li>
<li>Repeat until all the array elements are marked.</li>
</ul>
<p>Return <em>the score you get after applying the above algorithm</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,1,3,4,5,2]
<strong>Output:</strong> 7
<strong>Explanation:</strong> We mark the elements as follows:
- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [<u>2</u>,<u>1</u>,<u>3</u>,4,5,2].
- 2 is the smallest unmarked element, so we mark it and its left adjacent element: [<u>2</u>,<u>1</u>,<u>3</u>,4,<u>5</u>,<u>2</u>].
- 4 is the only remaining unmarked element, so we mark it: [<u>2</u>,<u>1</u>,<u>3</u>,<u>4</u>,<u>5</u>,<u>2</u>].
Our score is 1 + 2 + 4 = 7.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,5,1,3,2]
<strong>Output:</strong> 5
<strong>Explanation:</strong> We mark the elements as follows:
- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,3,<u>5</u>,<u>1</u>,<u>3</u>,2].
- 2 is the smallest unmarked element, since there are two of them, we choose the left-most one, so we mark the one at index 0 and its right adjacent element: [<u>2</u>,<u>3</u>,<u>5</u>,<u>1</u>,<u>3</u>,2].
- 2 is the only remaining unmarked element, so we mark it: [<u>2</u>,<u>3</u>,<u>5</u>,<u>1</u>,<u>3</u>,<u>2</u>].
Our score is 1 + 2 + 2 = 5.
</pre>
<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>6</sup></code></li>
</ul>
|
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
|
TypeScript
|
interface pair {
x: number;
i: number;
}
function findScore(nums: number[]): number {
const q = new PriorityQueue({
compare: (a: pair, b: pair) => (a.x === b.x ? a.i - b.i : a.x - b.x),
});
const n = nums.length;
const vis: boolean[] = new Array(n).fill(false);
for (let i = 0; i < n; ++i) {
q.enqueue({ x: nums[i], i });
}
let ans = 0;
while (!q.isEmpty()) {
const { x, i } = q.dequeue()!;
if (vis[i]) {
continue;
}
ans += x;
vis[i] = true;
if (i - 1 >= 0) {
vis[i - 1] = true;
}
if (i + 1 < n) {
vis[i + 1] = true;
}
while (!q.isEmpty() && vis[q.front()!.i]) {
q.dequeue();
}
}
return ans;
}
|
2,594
|
Minimum Time to Repair Cars
|
Medium
|
<p>You are given an integer array <code>ranks</code> representing the <strong>ranks</strong> of some mechanics. <font face="monospace">ranks<sub>i</sub></font> is the rank of the <font face="monospace">i<sup>th</sup></font> mechanic<font face="monospace">.</font> A mechanic with a rank <code>r</code> can repair <font face="monospace">n</font> cars in <code>r * n<sup>2</sup></code> minutes.</p>
<p>You are also given an integer <code>cars</code> representing the total number of cars waiting in the garage to be repaired.</p>
<p>Return <em>the <strong>minimum</strong> time taken to repair all the cars.</em></p>
<p><strong>Note:</strong> All the mechanics can repair the cars simultaneously.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> ranks = [4,2,3,1], cars = 10
<strong>Output:</strong> 16
<strong>Explanation:</strong>
- The first mechanic will repair two cars. The time required is 4 * 2 * 2 = 16 minutes.
- The second mechanic will repair two cars. The time required is 2 * 2 * 2 = 8 minutes.
- The third mechanic will repair two cars. The time required is 3 * 2 * 2 = 12 minutes.
- The fourth mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.
It can be proved that the cars cannot be repaired in less than 16 minutes.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ranks = [5,1,8], cars = 6
<strong>Output:</strong> 16
<strong>Explanation:</strong>
- The first mechanic will repair one car. The time required is 5 * 1 * 1 = 5 minutes.
- The second mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.
- The third mechanic will repair one car. The time required is 8 * 1 * 1 = 8 minutes.
It can be proved that the cars cannot be repaired in less than 16 minutes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= ranks.length <= 10<sup>5</sup></code></li>
<li><code>1 <= ranks[i] <= 100</code></li>
<li><code>1 <= cars <= 10<sup>6</sup></code></li>
</ul>
|
Array; Binary Search
|
C++
|
class Solution {
public:
long long repairCars(vector<int>& ranks, int cars) {
long long left = 0, right = 1LL * ranks[0] * cars * cars;
while (left < right) {
long long mid = (left + right) >> 1;
long long cnt = 0;
for (int r : ranks) {
cnt += sqrt(mid / r);
}
if (cnt >= cars) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
};
|
2,594
|
Minimum Time to Repair Cars
|
Medium
|
<p>You are given an integer array <code>ranks</code> representing the <strong>ranks</strong> of some mechanics. <font face="monospace">ranks<sub>i</sub></font> is the rank of the <font face="monospace">i<sup>th</sup></font> mechanic<font face="monospace">.</font> A mechanic with a rank <code>r</code> can repair <font face="monospace">n</font> cars in <code>r * n<sup>2</sup></code> minutes.</p>
<p>You are also given an integer <code>cars</code> representing the total number of cars waiting in the garage to be repaired.</p>
<p>Return <em>the <strong>minimum</strong> time taken to repair all the cars.</em></p>
<p><strong>Note:</strong> All the mechanics can repair the cars simultaneously.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> ranks = [4,2,3,1], cars = 10
<strong>Output:</strong> 16
<strong>Explanation:</strong>
- The first mechanic will repair two cars. The time required is 4 * 2 * 2 = 16 minutes.
- The second mechanic will repair two cars. The time required is 2 * 2 * 2 = 8 minutes.
- The third mechanic will repair two cars. The time required is 3 * 2 * 2 = 12 minutes.
- The fourth mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.
It can be proved that the cars cannot be repaired in less than 16 minutes.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ranks = [5,1,8], cars = 6
<strong>Output:</strong> 16
<strong>Explanation:</strong>
- The first mechanic will repair one car. The time required is 5 * 1 * 1 = 5 minutes.
- The second mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.
- The third mechanic will repair one car. The time required is 8 * 1 * 1 = 8 minutes.
It can be proved that the cars cannot be repaired in less than 16 minutes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= ranks.length <= 10<sup>5</sup></code></li>
<li><code>1 <= ranks[i] <= 100</code></li>
<li><code>1 <= cars <= 10<sup>6</sup></code></li>
</ul>
|
Array; Binary Search
|
Go
|
func repairCars(ranks []int, cars int) int64 {
return int64(sort.Search(ranks[0]*cars*cars, func(t int) bool {
cnt := 0
for _, r := range ranks {
cnt += int(math.Sqrt(float64(t / r)))
}
return cnt >= cars
}))
}
|
2,594
|
Minimum Time to Repair Cars
|
Medium
|
<p>You are given an integer array <code>ranks</code> representing the <strong>ranks</strong> of some mechanics. <font face="monospace">ranks<sub>i</sub></font> is the rank of the <font face="monospace">i<sup>th</sup></font> mechanic<font face="monospace">.</font> A mechanic with a rank <code>r</code> can repair <font face="monospace">n</font> cars in <code>r * n<sup>2</sup></code> minutes.</p>
<p>You are also given an integer <code>cars</code> representing the total number of cars waiting in the garage to be repaired.</p>
<p>Return <em>the <strong>minimum</strong> time taken to repair all the cars.</em></p>
<p><strong>Note:</strong> All the mechanics can repair the cars simultaneously.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> ranks = [4,2,3,1], cars = 10
<strong>Output:</strong> 16
<strong>Explanation:</strong>
- The first mechanic will repair two cars. The time required is 4 * 2 * 2 = 16 minutes.
- The second mechanic will repair two cars. The time required is 2 * 2 * 2 = 8 minutes.
- The third mechanic will repair two cars. The time required is 3 * 2 * 2 = 12 minutes.
- The fourth mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.
It can be proved that the cars cannot be repaired in less than 16 minutes.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ranks = [5,1,8], cars = 6
<strong>Output:</strong> 16
<strong>Explanation:</strong>
- The first mechanic will repair one car. The time required is 5 * 1 * 1 = 5 minutes.
- The second mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.
- The third mechanic will repair one car. The time required is 8 * 1 * 1 = 8 minutes.
It can be proved that the cars cannot be repaired in less than 16 minutes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= ranks.length <= 10<sup>5</sup></code></li>
<li><code>1 <= ranks[i] <= 100</code></li>
<li><code>1 <= cars <= 10<sup>6</sup></code></li>
</ul>
|
Array; Binary Search
|
Java
|
class Solution {
public long repairCars(int[] ranks, int cars) {
long left = 0, right = 1L * ranks[0] * cars * cars;
while (left < right) {
long mid = (left + right) >> 1;
long cnt = 0;
for (int r : ranks) {
cnt += Math.sqrt(mid / r);
}
if (cnt >= cars) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
|
2,594
|
Minimum Time to Repair Cars
|
Medium
|
<p>You are given an integer array <code>ranks</code> representing the <strong>ranks</strong> of some mechanics. <font face="monospace">ranks<sub>i</sub></font> is the rank of the <font face="monospace">i<sup>th</sup></font> mechanic<font face="monospace">.</font> A mechanic with a rank <code>r</code> can repair <font face="monospace">n</font> cars in <code>r * n<sup>2</sup></code> minutes.</p>
<p>You are also given an integer <code>cars</code> representing the total number of cars waiting in the garage to be repaired.</p>
<p>Return <em>the <strong>minimum</strong> time taken to repair all the cars.</em></p>
<p><strong>Note:</strong> All the mechanics can repair the cars simultaneously.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> ranks = [4,2,3,1], cars = 10
<strong>Output:</strong> 16
<strong>Explanation:</strong>
- The first mechanic will repair two cars. The time required is 4 * 2 * 2 = 16 minutes.
- The second mechanic will repair two cars. The time required is 2 * 2 * 2 = 8 minutes.
- The third mechanic will repair two cars. The time required is 3 * 2 * 2 = 12 minutes.
- The fourth mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.
It can be proved that the cars cannot be repaired in less than 16 minutes.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ranks = [5,1,8], cars = 6
<strong>Output:</strong> 16
<strong>Explanation:</strong>
- The first mechanic will repair one car. The time required is 5 * 1 * 1 = 5 minutes.
- The second mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.
- The third mechanic will repair one car. The time required is 8 * 1 * 1 = 8 minutes.
It can be proved that the cars cannot be repaired in less than 16 minutes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= ranks.length <= 10<sup>5</sup></code></li>
<li><code>1 <= ranks[i] <= 100</code></li>
<li><code>1 <= cars <= 10<sup>6</sup></code></li>
</ul>
|
Array; Binary Search
|
Python
|
class Solution:
def repairCars(self, ranks: List[int], cars: int) -> int:
def check(t: int) -> bool:
return sum(int(sqrt(t // r)) for r in ranks) >= cars
return bisect_left(range(ranks[0] * cars * cars), True, key=check)
|
2,594
|
Minimum Time to Repair Cars
|
Medium
|
<p>You are given an integer array <code>ranks</code> representing the <strong>ranks</strong> of some mechanics. <font face="monospace">ranks<sub>i</sub></font> is the rank of the <font face="monospace">i<sup>th</sup></font> mechanic<font face="monospace">.</font> A mechanic with a rank <code>r</code> can repair <font face="monospace">n</font> cars in <code>r * n<sup>2</sup></code> minutes.</p>
<p>You are also given an integer <code>cars</code> representing the total number of cars waiting in the garage to be repaired.</p>
<p>Return <em>the <strong>minimum</strong> time taken to repair all the cars.</em></p>
<p><strong>Note:</strong> All the mechanics can repair the cars simultaneously.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> ranks = [4,2,3,1], cars = 10
<strong>Output:</strong> 16
<strong>Explanation:</strong>
- The first mechanic will repair two cars. The time required is 4 * 2 * 2 = 16 minutes.
- The second mechanic will repair two cars. The time required is 2 * 2 * 2 = 8 minutes.
- The third mechanic will repair two cars. The time required is 3 * 2 * 2 = 12 minutes.
- The fourth mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.
It can be proved that the cars cannot be repaired in less than 16 minutes.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> ranks = [5,1,8], cars = 6
<strong>Output:</strong> 16
<strong>Explanation:</strong>
- The first mechanic will repair one car. The time required is 5 * 1 * 1 = 5 minutes.
- The second mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.
- The third mechanic will repair one car. The time required is 8 * 1 * 1 = 8 minutes.
It can be proved that the cars cannot be repaired in less than 16 minutes.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= ranks.length <= 10<sup>5</sup></code></li>
<li><code>1 <= ranks[i] <= 100</code></li>
<li><code>1 <= cars <= 10<sup>6</sup></code></li>
</ul>
|
Array; Binary Search
|
TypeScript
|
function repairCars(ranks: number[], cars: number): number {
let left = 0;
let right = ranks[0] * cars * cars;
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
let cnt = 0;
for (const r of ranks) {
cnt += Math.floor(Math.sqrt(mid / r));
}
if (cnt >= cars) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
|
2,595
|
Number of Even and Odd Bits
|
Easy
|
<p>You are given a <strong>positive</strong> integer <code>n</code>.</p>
<p>Let <code>even</code> denote the number of even indices in the binary representation of <code>n</code> with value 1.</p>
<p>Let <code>odd</code> denote the number of odd indices in the binary representation of <code>n</code> with value 1.</p>
<p>Note that bits are indexed from <strong>right to left</strong> in the binary representation of a number.</p>
<p>Return the array <code>[even, odd]</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 = 50</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 50 is <code>110010</code>.</p>
<p>It contains 1 on indices 1, 4, and 5.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 2 is <code>10</code>.</p>
<p>It contains 1 only on index 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
</ul>
|
Bit Manipulation
|
C++
|
class Solution {
public:
vector<int> evenOddBit(int n) {
vector<int> ans(2);
for (int i = 0; n > 0; n >>= 1, i ^= 1) {
ans[i] += n & 1;
}
return ans;
}
};
|
2,595
|
Number of Even and Odd Bits
|
Easy
|
<p>You are given a <strong>positive</strong> integer <code>n</code>.</p>
<p>Let <code>even</code> denote the number of even indices in the binary representation of <code>n</code> with value 1.</p>
<p>Let <code>odd</code> denote the number of odd indices in the binary representation of <code>n</code> with value 1.</p>
<p>Note that bits are indexed from <strong>right to left</strong> in the binary representation of a number.</p>
<p>Return the array <code>[even, odd]</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 = 50</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 50 is <code>110010</code>.</p>
<p>It contains 1 on indices 1, 4, and 5.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 2 is <code>10</code>.</p>
<p>It contains 1 only on index 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
</ul>
|
Bit Manipulation
|
Go
|
func evenOddBit(n int) []int {
ans := make([]int, 2)
for i := 0; n != 0; n, i = n>>1, i^1 {
ans[i] += n & 1
}
return ans
}
|
2,595
|
Number of Even and Odd Bits
|
Easy
|
<p>You are given a <strong>positive</strong> integer <code>n</code>.</p>
<p>Let <code>even</code> denote the number of even indices in the binary representation of <code>n</code> with value 1.</p>
<p>Let <code>odd</code> denote the number of odd indices in the binary representation of <code>n</code> with value 1.</p>
<p>Note that bits are indexed from <strong>right to left</strong> in the binary representation of a number.</p>
<p>Return the array <code>[even, odd]</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 = 50</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 50 is <code>110010</code>.</p>
<p>It contains 1 on indices 1, 4, and 5.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 2 is <code>10</code>.</p>
<p>It contains 1 only on index 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
</ul>
|
Bit Manipulation
|
Java
|
class Solution {
public int[] evenOddBit(int n) {
int[] ans = new int[2];
for (int i = 0; n > 0; n >>= 1, i ^= 1) {
ans[i] += n & 1;
}
return ans;
}
}
|
2,595
|
Number of Even and Odd Bits
|
Easy
|
<p>You are given a <strong>positive</strong> integer <code>n</code>.</p>
<p>Let <code>even</code> denote the number of even indices in the binary representation of <code>n</code> with value 1.</p>
<p>Let <code>odd</code> denote the number of odd indices in the binary representation of <code>n</code> with value 1.</p>
<p>Note that bits are indexed from <strong>right to left</strong> in the binary representation of a number.</p>
<p>Return the array <code>[even, odd]</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 = 50</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 50 is <code>110010</code>.</p>
<p>It contains 1 on indices 1, 4, and 5.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 2 is <code>10</code>.</p>
<p>It contains 1 only on index 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
</ul>
|
Bit Manipulation
|
Python
|
class Solution:
def evenOddBit(self, n: int) -> List[int]:
ans = [0, 0]
i = 0
while n:
ans[i] += n & 1
i ^= 1
n >>= 1
return ans
|
2,595
|
Number of Even and Odd Bits
|
Easy
|
<p>You are given a <strong>positive</strong> integer <code>n</code>.</p>
<p>Let <code>even</code> denote the number of even indices in the binary representation of <code>n</code> with value 1.</p>
<p>Let <code>odd</code> denote the number of odd indices in the binary representation of <code>n</code> with value 1.</p>
<p>Note that bits are indexed from <strong>right to left</strong> in the binary representation of a number.</p>
<p>Return the array <code>[even, odd]</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 = 50</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 50 is <code>110010</code>.</p>
<p>It contains 1 on indices 1, 4, and 5.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 2 is <code>10</code>.</p>
<p>It contains 1 only on index 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
</ul>
|
Bit Manipulation
|
Rust
|
impl Solution {
pub fn even_odd_bit(mut n: i32) -> Vec<i32> {
let mut ans = vec![0; 2];
let mut i = 0;
while n != 0 {
ans[i] += n & 1;
n >>= 1;
i ^= 1;
}
ans
}
}
|
2,595
|
Number of Even and Odd Bits
|
Easy
|
<p>You are given a <strong>positive</strong> integer <code>n</code>.</p>
<p>Let <code>even</code> denote the number of even indices in the binary representation of <code>n</code> with value 1.</p>
<p>Let <code>odd</code> denote the number of odd indices in the binary representation of <code>n</code> with value 1.</p>
<p>Note that bits are indexed from <strong>right to left</strong> in the binary representation of a number.</p>
<p>Return the array <code>[even, odd]</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 = 50</span></p>
<p><strong>Output:</strong> <span class="example-io">[1,2]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 50 is <code>110010</code>.</p>
<p>It contains 1 on indices 1, 4, and 5.</p>
</div>
<p><strong class="example">Example 2:</strong></p>
<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">n = 2</span></p>
<p><strong>Output:</strong> <span class="example-io">[0,1]</span></p>
<p><strong>Explanation:</strong></p>
<p>The binary representation of 2 is <code>10</code>.</p>
<p>It contains 1 only on index 1.</p>
</div>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
</ul>
|
Bit Manipulation
|
TypeScript
|
function evenOddBit(n: number): number[] {
const ans = Array(2).fill(0);
for (let i = 0; n > 0; n >>= 1, i ^= 1) {
ans[i] += n & 1;
}
return ans;
}
|
2,596
|
Check Knight Tour Configuration
|
Medium
|
<p>There is a knight on an <code>n x n</code> chessboard. In a valid configuration, the knight starts <strong>at the top-left cell</strong> of the board and visits every cell on the board <strong>exactly once</strong>.</p>
<p>You are given an <code>n x n</code> integer matrix <code>grid</code> consisting of distinct integers from the range <code>[0, n * n - 1]</code> where <code>grid[row][col]</code> indicates that the cell <code>(row, col)</code> is the <code>grid[row][col]<sup>th</sup></code> cell that the knight visited. The moves are <strong>0-indexed</strong>.</p>
<p>Return <code>true</code> <em>if</em> <code>grid</code> <em>represents a valid configuration of the knight's movements or</em> <code>false</code> <em>otherwise</em>.</p>
<p><strong>Note</strong> that a valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The figure below illustrates all the possible eight moves of a knight from some cell.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/knight.png" style="width: 300px; height: 300px;" />
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/yetgriddrawio-5.png" style="width: 251px; height: 251px;" />
<pre>
<strong>Input:</strong> grid = [[0,11,16,5,20],[17,4,19,10,15],[12,1,8,21,6],[3,18,23,14,9],[24,13,2,7,22]]
<strong>Output:</strong> true
<strong>Explanation:</strong> The above diagram represents the grid. It can be shown that it is a valid configuration.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/yetgriddrawio-6.png" style="width: 151px; height: 151px;" />
<pre>
<strong>Input:</strong> grid = [[0,3,6],[5,8,1],[2,7,4]]
<strong>Output:</strong> false
<strong>Explanation:</strong> The above diagram represents the grid. The 8<sup>th</sup> move of the knight is not valid considering its position after the 7<sup>th</sup> move.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length == grid[i].length</code></li>
<li><code>3 <= n <= 7</code></li>
<li><code>0 <= grid[row][col] < n * n</code></li>
<li>All integers in <code>grid</code> are <strong>unique</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix; Simulation
|
C++
|
class Solution {
public:
bool checkValidGrid(vector<vector<int>>& grid) {
if (grid[0][0] != 0) {
return false;
}
int n = grid.size();
vector<pair<int, int>> pos(n * n);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
pos[grid[i][j]] = {i, j};
}
}
for (int i = 1; i < n * n; ++i) {
auto [x1, y1] = pos[i - 1];
auto [x2, y2] = pos[i];
int dx = abs(x1 - x2);
int dy = abs(y1 - y2);
bool ok = (dx == 1 && dy == 2) || (dx == 2 && dy == 1);
if (!ok) {
return false;
}
}
return true;
}
};
|
2,596
|
Check Knight Tour Configuration
|
Medium
|
<p>There is a knight on an <code>n x n</code> chessboard. In a valid configuration, the knight starts <strong>at the top-left cell</strong> of the board and visits every cell on the board <strong>exactly once</strong>.</p>
<p>You are given an <code>n x n</code> integer matrix <code>grid</code> consisting of distinct integers from the range <code>[0, n * n - 1]</code> where <code>grid[row][col]</code> indicates that the cell <code>(row, col)</code> is the <code>grid[row][col]<sup>th</sup></code> cell that the knight visited. The moves are <strong>0-indexed</strong>.</p>
<p>Return <code>true</code> <em>if</em> <code>grid</code> <em>represents a valid configuration of the knight's movements or</em> <code>false</code> <em>otherwise</em>.</p>
<p><strong>Note</strong> that a valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The figure below illustrates all the possible eight moves of a knight from some cell.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/knight.png" style="width: 300px; height: 300px;" />
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/yetgriddrawio-5.png" style="width: 251px; height: 251px;" />
<pre>
<strong>Input:</strong> grid = [[0,11,16,5,20],[17,4,19,10,15],[12,1,8,21,6],[3,18,23,14,9],[24,13,2,7,22]]
<strong>Output:</strong> true
<strong>Explanation:</strong> The above diagram represents the grid. It can be shown that it is a valid configuration.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/yetgriddrawio-6.png" style="width: 151px; height: 151px;" />
<pre>
<strong>Input:</strong> grid = [[0,3,6],[5,8,1],[2,7,4]]
<strong>Output:</strong> false
<strong>Explanation:</strong> The above diagram represents the grid. The 8<sup>th</sup> move of the knight is not valid considering its position after the 7<sup>th</sup> move.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length == grid[i].length</code></li>
<li><code>3 <= n <= 7</code></li>
<li><code>0 <= grid[row][col] < n * n</code></li>
<li>All integers in <code>grid</code> are <strong>unique</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix; Simulation
|
Go
|
func checkValidGrid(grid [][]int) bool {
if grid[0][0] != 0 {
return false
}
n := len(grid)
type pair struct{ x, y int }
pos := make([]pair, n*n)
for i, row := range grid {
for j, x := range row {
pos[x] = pair{i, j}
}
}
for i := 1; i < n*n; i++ {
p1, p2 := pos[i-1], pos[i]
dx := abs(p1.x - p2.x)
dy := abs(p1.y - p2.y)
ok := (dx == 2 && dy == 1) || (dx == 1 && dy == 2)
if !ok {
return false
}
}
return true
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
2,596
|
Check Knight Tour Configuration
|
Medium
|
<p>There is a knight on an <code>n x n</code> chessboard. In a valid configuration, the knight starts <strong>at the top-left cell</strong> of the board and visits every cell on the board <strong>exactly once</strong>.</p>
<p>You are given an <code>n x n</code> integer matrix <code>grid</code> consisting of distinct integers from the range <code>[0, n * n - 1]</code> where <code>grid[row][col]</code> indicates that the cell <code>(row, col)</code> is the <code>grid[row][col]<sup>th</sup></code> cell that the knight visited. The moves are <strong>0-indexed</strong>.</p>
<p>Return <code>true</code> <em>if</em> <code>grid</code> <em>represents a valid configuration of the knight's movements or</em> <code>false</code> <em>otherwise</em>.</p>
<p><strong>Note</strong> that a valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The figure below illustrates all the possible eight moves of a knight from some cell.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/knight.png" style="width: 300px; height: 300px;" />
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/yetgriddrawio-5.png" style="width: 251px; height: 251px;" />
<pre>
<strong>Input:</strong> grid = [[0,11,16,5,20],[17,4,19,10,15],[12,1,8,21,6],[3,18,23,14,9],[24,13,2,7,22]]
<strong>Output:</strong> true
<strong>Explanation:</strong> The above diagram represents the grid. It can be shown that it is a valid configuration.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/yetgriddrawio-6.png" style="width: 151px; height: 151px;" />
<pre>
<strong>Input:</strong> grid = [[0,3,6],[5,8,1],[2,7,4]]
<strong>Output:</strong> false
<strong>Explanation:</strong> The above diagram represents the grid. The 8<sup>th</sup> move of the knight is not valid considering its position after the 7<sup>th</sup> move.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length == grid[i].length</code></li>
<li><code>3 <= n <= 7</code></li>
<li><code>0 <= grid[row][col] < n * n</code></li>
<li>All integers in <code>grid</code> are <strong>unique</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix; Simulation
|
Java
|
class Solution {
public boolean checkValidGrid(int[][] grid) {
if (grid[0][0] != 0) {
return false;
}
int n = grid.length;
int[][] pos = new int[n * n][2];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
pos[grid[i][j]] = new int[] {i, j};
}
}
for (int i = 1; i < n * n; ++i) {
int[] p1 = pos[i - 1];
int[] p2 = pos[i];
int dx = Math.abs(p1[0] - p2[0]);
int dy = Math.abs(p1[1] - p2[1]);
boolean ok = (dx == 1 && dy == 2) || (dx == 2 && dy == 1);
if (!ok) {
return false;
}
}
return true;
}
}
|
2,596
|
Check Knight Tour Configuration
|
Medium
|
<p>There is a knight on an <code>n x n</code> chessboard. In a valid configuration, the knight starts <strong>at the top-left cell</strong> of the board and visits every cell on the board <strong>exactly once</strong>.</p>
<p>You are given an <code>n x n</code> integer matrix <code>grid</code> consisting of distinct integers from the range <code>[0, n * n - 1]</code> where <code>grid[row][col]</code> indicates that the cell <code>(row, col)</code> is the <code>grid[row][col]<sup>th</sup></code> cell that the knight visited. The moves are <strong>0-indexed</strong>.</p>
<p>Return <code>true</code> <em>if</em> <code>grid</code> <em>represents a valid configuration of the knight's movements or</em> <code>false</code> <em>otherwise</em>.</p>
<p><strong>Note</strong> that a valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The figure below illustrates all the possible eight moves of a knight from some cell.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/knight.png" style="width: 300px; height: 300px;" />
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/yetgriddrawio-5.png" style="width: 251px; height: 251px;" />
<pre>
<strong>Input:</strong> grid = [[0,11,16,5,20],[17,4,19,10,15],[12,1,8,21,6],[3,18,23,14,9],[24,13,2,7,22]]
<strong>Output:</strong> true
<strong>Explanation:</strong> The above diagram represents the grid. It can be shown that it is a valid configuration.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/yetgriddrawio-6.png" style="width: 151px; height: 151px;" />
<pre>
<strong>Input:</strong> grid = [[0,3,6],[5,8,1],[2,7,4]]
<strong>Output:</strong> false
<strong>Explanation:</strong> The above diagram represents the grid. The 8<sup>th</sup> move of the knight is not valid considering its position after the 7<sup>th</sup> move.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length == grid[i].length</code></li>
<li><code>3 <= n <= 7</code></li>
<li><code>0 <= grid[row][col] < n * n</code></li>
<li>All integers in <code>grid</code> are <strong>unique</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix; Simulation
|
Python
|
class Solution:
def checkValidGrid(self, grid: List[List[int]]) -> bool:
if grid[0][0]:
return False
n = len(grid)
pos = [None] * (n * n)
for i in range(n):
for j in range(n):
pos[grid[i][j]] = (i, j)
for (x1, y1), (x2, y2) in pairwise(pos):
dx, dy = abs(x1 - x2), abs(y1 - y2)
ok = (dx == 1 and dy == 2) or (dx == 2 and dy == 1)
if not ok:
return False
return True
|
2,596
|
Check Knight Tour Configuration
|
Medium
|
<p>There is a knight on an <code>n x n</code> chessboard. In a valid configuration, the knight starts <strong>at the top-left cell</strong> of the board and visits every cell on the board <strong>exactly once</strong>.</p>
<p>You are given an <code>n x n</code> integer matrix <code>grid</code> consisting of distinct integers from the range <code>[0, n * n - 1]</code> where <code>grid[row][col]</code> indicates that the cell <code>(row, col)</code> is the <code>grid[row][col]<sup>th</sup></code> cell that the knight visited. The moves are <strong>0-indexed</strong>.</p>
<p>Return <code>true</code> <em>if</em> <code>grid</code> <em>represents a valid configuration of the knight's movements or</em> <code>false</code> <em>otherwise</em>.</p>
<p><strong>Note</strong> that a valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The figure below illustrates all the possible eight moves of a knight from some cell.</p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/knight.png" style="width: 300px; height: 300px;" />
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/yetgriddrawio-5.png" style="width: 251px; height: 251px;" />
<pre>
<strong>Input:</strong> grid = [[0,11,16,5,20],[17,4,19,10,15],[12,1,8,21,6],[3,18,23,14,9],[24,13,2,7,22]]
<strong>Output:</strong> true
<strong>Explanation:</strong> The above diagram represents the grid. It can be shown that it is a valid configuration.
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2500-2599/2596.Check%20Knight%20Tour%20Configuration/images/yetgriddrawio-6.png" style="width: 151px; height: 151px;" />
<pre>
<strong>Input:</strong> grid = [[0,3,6],[5,8,1],[2,7,4]]
<strong>Output:</strong> false
<strong>Explanation:</strong> The above diagram represents the grid. The 8<sup>th</sup> move of the knight is not valid considering its position after the 7<sup>th</sup> move.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == grid.length == grid[i].length</code></li>
<li><code>3 <= n <= 7</code></li>
<li><code>0 <= grid[row][col] < n * n</code></li>
<li>All integers in <code>grid</code> are <strong>unique</strong>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix; Simulation
|
TypeScript
|
function checkValidGrid(grid: number[][]): boolean {
if (grid[0][0] !== 0) {
return false;
}
const n = grid.length;
const pos = Array.from(new Array(n * n), () => new Array(2).fill(0));
for (let i = 0; i < n; ++i) {
for (let j = 0; j < n; ++j) {
pos[grid[i][j]] = [i, j];
}
}
for (let i = 1; i < n * n; ++i) {
const p1 = pos[i - 1];
const p2 = pos[i];
const dx = Math.abs(p1[0] - p2[0]);
const dy = Math.abs(p1[1] - p2[1]);
const ok = (dx === 1 && dy === 2) || (dx === 2 && dy === 1);
if (!ok) {
return false;
}
}
return true;
}
|
2,597
|
The Number of Beautiful Subsets
|
Medium
|
<p>You are given an array <code>nums</code> of positive integers and a <strong>positive</strong> integer <code>k</code>.</p>
<p>A subset of <code>nums</code> is <strong>beautiful</strong> if it does not contain two integers with an absolute difference equal to <code>k</code>.</p>
<p>Return <em>the number of <strong>non-empty beautiful </strong>subsets of the array</em> <code>nums</code>.</p>
<p>A <strong>subset</strong> of <code>nums</code> is an array that can be obtained by deleting some (possibly none) elements from <code>nums</code>. Two subsets are different if and only if the chosen indices to delete are different.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,6], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].
It can be proved that there are only 4 beautiful subsets in the array [2,4,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1], k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The beautiful subset of the array nums is [1].
It can be proved that there is only 1 beautiful subset in the array [1].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 18</code></li>
<li><code>1 <= nums[i], k <= 1000</code></li>
</ul>
|
Array; Hash Table; Math; Dynamic Programming; Backtracking; Combinatorics; Sorting
|
C++
|
class Solution {
public:
int beautifulSubsets(vector<int>& nums, int k) {
int ans = -1;
int cnt[1010]{};
int n = nums.size();
auto dfs = [&](this auto&& dfs, int i) {
if (i >= n) {
++ans;
return;
}
dfs(i + 1);
bool ok1 = nums[i] + k >= 1010 || cnt[nums[i] + k] == 0;
bool ok2 = nums[i] - k < 0 || cnt[nums[i] - k] == 0;
if (ok1 && ok2) {
++cnt[nums[i]];
dfs(i + 1);
--cnt[nums[i]];
}
};
dfs(0);
return ans;
}
};
|
2,597
|
The Number of Beautiful Subsets
|
Medium
|
<p>You are given an array <code>nums</code> of positive integers and a <strong>positive</strong> integer <code>k</code>.</p>
<p>A subset of <code>nums</code> is <strong>beautiful</strong> if it does not contain two integers with an absolute difference equal to <code>k</code>.</p>
<p>Return <em>the number of <strong>non-empty beautiful </strong>subsets of the array</em> <code>nums</code>.</p>
<p>A <strong>subset</strong> of <code>nums</code> is an array that can be obtained by deleting some (possibly none) elements from <code>nums</code>. Two subsets are different if and only if the chosen indices to delete are different.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,6], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].
It can be proved that there are only 4 beautiful subsets in the array [2,4,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1], k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The beautiful subset of the array nums is [1].
It can be proved that there is only 1 beautiful subset in the array [1].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 18</code></li>
<li><code>1 <= nums[i], k <= 1000</code></li>
</ul>
|
Array; Hash Table; Math; Dynamic Programming; Backtracking; Combinatorics; Sorting
|
C#
|
public class Solution {
public int BeautifulSubsets(int[] nums, int k) {
int ans = -1;
int[] cnt = new int[1010];
int n = nums.Length;
void Dfs(int i) {
if (i >= n) {
ans++;
return;
}
Dfs(i + 1);
bool ok1 = nums[i] + k >= 1010 || cnt[nums[i] + k] == 0;
bool ok2 = nums[i] - k < 0 || cnt[nums[i] - k] == 0;
if (ok1 && ok2) {
cnt[nums[i]]++;
Dfs(i + 1);
cnt[nums[i]]--;
}
}
Dfs(0);
return ans;
}
}
|
2,597
|
The Number of Beautiful Subsets
|
Medium
|
<p>You are given an array <code>nums</code> of positive integers and a <strong>positive</strong> integer <code>k</code>.</p>
<p>A subset of <code>nums</code> is <strong>beautiful</strong> if it does not contain two integers with an absolute difference equal to <code>k</code>.</p>
<p>Return <em>the number of <strong>non-empty beautiful </strong>subsets of the array</em> <code>nums</code>.</p>
<p>A <strong>subset</strong> of <code>nums</code> is an array that can be obtained by deleting some (possibly none) elements from <code>nums</code>. Two subsets are different if and only if the chosen indices to delete are different.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,6], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].
It can be proved that there are only 4 beautiful subsets in the array [2,4,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1], k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The beautiful subset of the array nums is [1].
It can be proved that there is only 1 beautiful subset in the array [1].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 18</code></li>
<li><code>1 <= nums[i], k <= 1000</code></li>
</ul>
|
Array; Hash Table; Math; Dynamic Programming; Backtracking; Combinatorics; Sorting
|
Go
|
func beautifulSubsets(nums []int, k int) int {
ans := -1
n := len(nums)
cnt := [1010]int{}
var dfs func(int)
dfs = func(i int) {
if i >= n {
ans++
return
}
dfs(i + 1)
ok1 := nums[i]+k >= len(cnt) || cnt[nums[i]+k] == 0
ok2 := nums[i]-k < 0 || cnt[nums[i]-k] == 0
if ok1 && ok2 {
cnt[nums[i]]++
dfs(i + 1)
cnt[nums[i]]--
}
}
dfs(0)
return ans
}
|
2,597
|
The Number of Beautiful Subsets
|
Medium
|
<p>You are given an array <code>nums</code> of positive integers and a <strong>positive</strong> integer <code>k</code>.</p>
<p>A subset of <code>nums</code> is <strong>beautiful</strong> if it does not contain two integers with an absolute difference equal to <code>k</code>.</p>
<p>Return <em>the number of <strong>non-empty beautiful </strong>subsets of the array</em> <code>nums</code>.</p>
<p>A <strong>subset</strong> of <code>nums</code> is an array that can be obtained by deleting some (possibly none) elements from <code>nums</code>. Two subsets are different if and only if the chosen indices to delete are different.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,6], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].
It can be proved that there are only 4 beautiful subsets in the array [2,4,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1], k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The beautiful subset of the array nums is [1].
It can be proved that there is only 1 beautiful subset in the array [1].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 18</code></li>
<li><code>1 <= nums[i], k <= 1000</code></li>
</ul>
|
Array; Hash Table; Math; Dynamic Programming; Backtracking; Combinatorics; Sorting
|
Java
|
class Solution {
private int[] nums;
private int[] cnt = new int[1010];
private int ans = -1;
private int k;
public int beautifulSubsets(int[] nums, int k) {
this.k = k;
this.nums = nums;
dfs(0);
return ans;
}
private void dfs(int i) {
if (i >= nums.length) {
++ans;
return;
}
dfs(i + 1);
boolean ok1 = nums[i] + k >= cnt.length || cnt[nums[i] + k] == 0;
boolean ok2 = nums[i] - k < 0 || cnt[nums[i] - k] == 0;
if (ok1 && ok2) {
++cnt[nums[i]];
dfs(i + 1);
--cnt[nums[i]];
}
}
}
|
2,597
|
The Number of Beautiful Subsets
|
Medium
|
<p>You are given an array <code>nums</code> of positive integers and a <strong>positive</strong> integer <code>k</code>.</p>
<p>A subset of <code>nums</code> is <strong>beautiful</strong> if it does not contain two integers with an absolute difference equal to <code>k</code>.</p>
<p>Return <em>the number of <strong>non-empty beautiful </strong>subsets of the array</em> <code>nums</code>.</p>
<p>A <strong>subset</strong> of <code>nums</code> is an array that can be obtained by deleting some (possibly none) elements from <code>nums</code>. Two subsets are different if and only if the chosen indices to delete are different.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,6], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].
It can be proved that there are only 4 beautiful subsets in the array [2,4,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1], k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The beautiful subset of the array nums is [1].
It can be proved that there is only 1 beautiful subset in the array [1].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 18</code></li>
<li><code>1 <= nums[i], k <= 1000</code></li>
</ul>
|
Array; Hash Table; Math; Dynamic Programming; Backtracking; Combinatorics; Sorting
|
Python
|
class Solution:
def beautifulSubsets(self, nums: List[int], k: int) -> int:
def dfs(i: int) -> None:
nonlocal ans
if i >= len(nums):
ans += 1
return
dfs(i + 1)
if cnt[nums[i] + k] == 0 and cnt[nums[i] - k] == 0:
cnt[nums[i]] += 1
dfs(i + 1)
cnt[nums[i]] -= 1
ans = -1
cnt = Counter()
dfs(0)
return ans
|
2,597
|
The Number of Beautiful Subsets
|
Medium
|
<p>You are given an array <code>nums</code> of positive integers and a <strong>positive</strong> integer <code>k</code>.</p>
<p>A subset of <code>nums</code> is <strong>beautiful</strong> if it does not contain two integers with an absolute difference equal to <code>k</code>.</p>
<p>Return <em>the number of <strong>non-empty beautiful </strong>subsets of the array</em> <code>nums</code>.</p>
<p>A <strong>subset</strong> of <code>nums</code> is an array that can be obtained by deleting some (possibly none) elements from <code>nums</code>. Two subsets are different if and only if the chosen indices to delete are different.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,4,6], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].
It can be proved that there are only 4 beautiful subsets in the array [2,4,6].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1], k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The beautiful subset of the array nums is [1].
It can be proved that there is only 1 beautiful subset in the array [1].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 18</code></li>
<li><code>1 <= nums[i], k <= 1000</code></li>
</ul>
|
Array; Hash Table; Math; Dynamic Programming; Backtracking; Combinatorics; Sorting
|
TypeScript
|
function beautifulSubsets(nums: number[], k: number): number {
let ans: number = -1;
const cnt: number[] = new Array(1010).fill(0);
const n: number = nums.length;
const dfs = (i: number) => {
if (i >= n) {
++ans;
return;
}
dfs(i + 1);
const ok1: boolean = nums[i] + k >= 1010 || cnt[nums[i] + k] === 0;
const ok2: boolean = nums[i] - k < 0 || cnt[nums[i] - k] === 0;
if (ok1 && ok2) {
++cnt[nums[i]];
dfs(i + 1);
--cnt[nums[i]];
}
};
dfs(0);
return ans;
}
|
2,598
|
Smallest Missing Non-negative Integer After Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>value</code>.</p>
<p>In one operation, you can add or subtract <code>value</code> from any element of <code>nums</code>.</p>
<ul>
<li>For example, if <code>nums = [1,2,3]</code> and <code>value = 2</code>, you can choose to subtract <code>value</code> from <code>nums[0]</code> to make <code>nums = [-1,2,3]</code>.</li>
</ul>
<p>The MEX (minimum excluded) of an array is the smallest missing <strong>non-negative</strong> integer in it.</p>
<ul>
<li>For example, the MEX of <code>[-1,2,3]</code> is <code>0</code> while the MEX of <code>[1,0,3]</code> is <code>2</code>.</li>
</ul>
<p>Return <em>the maximum MEX of </em><code>nums</code><em> after applying the mentioned operation <strong>any number of times</strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,-10,7,13,6,8], value = 5
<strong>Output:</strong> 4
<strong>Explanation:</strong> One can achieve this result by applying the following operations:
- Add value to nums[1] twice to make nums = [1,<strong><u>0</u></strong>,7,13,6,8]
- Subtract value from nums[2] once to make nums = [1,0,<strong><u>2</u></strong>,13,6,8]
- Subtract value from nums[3] twice to make nums = [1,0,2,<strong><u>3</u></strong>,6,8]
The MEX of nums is 4. It can be shown that 4 is the maximum MEX we can achieve.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,-10,7,13,6,8], value = 7
<strong>Output:</strong> 2
<strong>Explanation:</strong> One can achieve this result by applying the following operation:
- subtract value from nums[2] once to make nums = [1,-10,<u><strong>0</strong></u>,13,6,8]
The MEX of nums is 2. It can be shown that 2 is the maximum MEX we can achieve.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, value <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table; Math
|
C++
|
class Solution {
public:
int findSmallestInteger(vector<int>& nums, int value) {
int cnt[value];
memset(cnt, 0, sizeof(cnt));
for (int x : nums) {
++cnt[(x % value + value) % value];
}
for (int i = 0;; ++i) {
if (cnt[i % value]-- == 0) {
return i;
}
}
}
};
|
2,598
|
Smallest Missing Non-negative Integer After Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>value</code>.</p>
<p>In one operation, you can add or subtract <code>value</code> from any element of <code>nums</code>.</p>
<ul>
<li>For example, if <code>nums = [1,2,3]</code> and <code>value = 2</code>, you can choose to subtract <code>value</code> from <code>nums[0]</code> to make <code>nums = [-1,2,3]</code>.</li>
</ul>
<p>The MEX (minimum excluded) of an array is the smallest missing <strong>non-negative</strong> integer in it.</p>
<ul>
<li>For example, the MEX of <code>[-1,2,3]</code> is <code>0</code> while the MEX of <code>[1,0,3]</code> is <code>2</code>.</li>
</ul>
<p>Return <em>the maximum MEX of </em><code>nums</code><em> after applying the mentioned operation <strong>any number of times</strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,-10,7,13,6,8], value = 5
<strong>Output:</strong> 4
<strong>Explanation:</strong> One can achieve this result by applying the following operations:
- Add value to nums[1] twice to make nums = [1,<strong><u>0</u></strong>,7,13,6,8]
- Subtract value from nums[2] once to make nums = [1,0,<strong><u>2</u></strong>,13,6,8]
- Subtract value from nums[3] twice to make nums = [1,0,2,<strong><u>3</u></strong>,6,8]
The MEX of nums is 4. It can be shown that 4 is the maximum MEX we can achieve.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,-10,7,13,6,8], value = 7
<strong>Output:</strong> 2
<strong>Explanation:</strong> One can achieve this result by applying the following operation:
- subtract value from nums[2] once to make nums = [1,-10,<u><strong>0</strong></u>,13,6,8]
The MEX of nums is 2. It can be shown that 2 is the maximum MEX we can achieve.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, value <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table; Math
|
Go
|
func findSmallestInteger(nums []int, value int) int {
cnt := make([]int, value)
for _, x := range nums {
cnt[(x%value+value)%value]++
}
for i := 0; ; i++ {
if cnt[i%value] == 0 {
return i
}
cnt[i%value]--
}
}
|
2,598
|
Smallest Missing Non-negative Integer After Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>value</code>.</p>
<p>In one operation, you can add or subtract <code>value</code> from any element of <code>nums</code>.</p>
<ul>
<li>For example, if <code>nums = [1,2,3]</code> and <code>value = 2</code>, you can choose to subtract <code>value</code> from <code>nums[0]</code> to make <code>nums = [-1,2,3]</code>.</li>
</ul>
<p>The MEX (minimum excluded) of an array is the smallest missing <strong>non-negative</strong> integer in it.</p>
<ul>
<li>For example, the MEX of <code>[-1,2,3]</code> is <code>0</code> while the MEX of <code>[1,0,3]</code> is <code>2</code>.</li>
</ul>
<p>Return <em>the maximum MEX of </em><code>nums</code><em> after applying the mentioned operation <strong>any number of times</strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,-10,7,13,6,8], value = 5
<strong>Output:</strong> 4
<strong>Explanation:</strong> One can achieve this result by applying the following operations:
- Add value to nums[1] twice to make nums = [1,<strong><u>0</u></strong>,7,13,6,8]
- Subtract value from nums[2] once to make nums = [1,0,<strong><u>2</u></strong>,13,6,8]
- Subtract value from nums[3] twice to make nums = [1,0,2,<strong><u>3</u></strong>,6,8]
The MEX of nums is 4. It can be shown that 4 is the maximum MEX we can achieve.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,-10,7,13,6,8], value = 7
<strong>Output:</strong> 2
<strong>Explanation:</strong> One can achieve this result by applying the following operation:
- subtract value from nums[2] once to make nums = [1,-10,<u><strong>0</strong></u>,13,6,8]
The MEX of nums is 2. It can be shown that 2 is the maximum MEX we can achieve.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, value <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table; Math
|
Java
|
class Solution {
public int findSmallestInteger(int[] nums, int value) {
int[] cnt = new int[value];
for (int x : nums) {
++cnt[(x % value + value) % value];
}
for (int i = 0;; ++i) {
if (cnt[i % value]-- == 0) {
return i;
}
}
}
}
|
2,598
|
Smallest Missing Non-negative Integer After Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>value</code>.</p>
<p>In one operation, you can add or subtract <code>value</code> from any element of <code>nums</code>.</p>
<ul>
<li>For example, if <code>nums = [1,2,3]</code> and <code>value = 2</code>, you can choose to subtract <code>value</code> from <code>nums[0]</code> to make <code>nums = [-1,2,3]</code>.</li>
</ul>
<p>The MEX (minimum excluded) of an array is the smallest missing <strong>non-negative</strong> integer in it.</p>
<ul>
<li>For example, the MEX of <code>[-1,2,3]</code> is <code>0</code> while the MEX of <code>[1,0,3]</code> is <code>2</code>.</li>
</ul>
<p>Return <em>the maximum MEX of </em><code>nums</code><em> after applying the mentioned operation <strong>any number of times</strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,-10,7,13,6,8], value = 5
<strong>Output:</strong> 4
<strong>Explanation:</strong> One can achieve this result by applying the following operations:
- Add value to nums[1] twice to make nums = [1,<strong><u>0</u></strong>,7,13,6,8]
- Subtract value from nums[2] once to make nums = [1,0,<strong><u>2</u></strong>,13,6,8]
- Subtract value from nums[3] twice to make nums = [1,0,2,<strong><u>3</u></strong>,6,8]
The MEX of nums is 4. It can be shown that 4 is the maximum MEX we can achieve.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,-10,7,13,6,8], value = 7
<strong>Output:</strong> 2
<strong>Explanation:</strong> One can achieve this result by applying the following operation:
- subtract value from nums[2] once to make nums = [1,-10,<u><strong>0</strong></u>,13,6,8]
The MEX of nums is 2. It can be shown that 2 is the maximum MEX we can achieve.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, value <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table; Math
|
Python
|
class Solution:
def findSmallestInteger(self, nums: List[int], value: int) -> int:
cnt = Counter(x % value for x in nums)
for i in range(len(nums) + 1):
if cnt[i % value] == 0:
return i
cnt[i % value] -= 1
|
2,598
|
Smallest Missing Non-negative Integer After Operations
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>value</code>.</p>
<p>In one operation, you can add or subtract <code>value</code> from any element of <code>nums</code>.</p>
<ul>
<li>For example, if <code>nums = [1,2,3]</code> and <code>value = 2</code>, you can choose to subtract <code>value</code> from <code>nums[0]</code> to make <code>nums = [-1,2,3]</code>.</li>
</ul>
<p>The MEX (minimum excluded) of an array is the smallest missing <strong>non-negative</strong> integer in it.</p>
<ul>
<li>For example, the MEX of <code>[-1,2,3]</code> is <code>0</code> while the MEX of <code>[1,0,3]</code> is <code>2</code>.</li>
</ul>
<p>Return <em>the maximum MEX of </em><code>nums</code><em> after applying the mentioned operation <strong>any number of times</strong></em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,-10,7,13,6,8], value = 5
<strong>Output:</strong> 4
<strong>Explanation:</strong> One can achieve this result by applying the following operations:
- Add value to nums[1] twice to make nums = [1,<strong><u>0</u></strong>,7,13,6,8]
- Subtract value from nums[2] once to make nums = [1,0,<strong><u>2</u></strong>,13,6,8]
- Subtract value from nums[3] twice to make nums = [1,0,2,<strong><u>3</u></strong>,6,8]
The MEX of nums is 4. It can be shown that 4 is the maximum MEX we can achieve.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,-10,7,13,6,8], value = 7
<strong>Output:</strong> 2
<strong>Explanation:</strong> One can achieve this result by applying the following operation:
- subtract value from nums[2] once to make nums = [1,-10,<u><strong>0</strong></u>,13,6,8]
The MEX of nums is 2. It can be shown that 2 is the maximum MEX we can achieve.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length, value <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Hash Table; Math
|
TypeScript
|
function findSmallestInteger(nums: number[], value: number): number {
const cnt: number[] = new Array(value).fill(0);
for (const x of nums) {
++cnt[((x % value) + value) % value];
}
for (let i = 0; ; ++i) {
if (cnt[i % value]-- === 0) {
return i;
}
}
}
|
2,599
|
Make the Prefix Sum Non-negative
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. You can apply the following operation any number of times:</p>
<ul>
<li>Pick any element from <code>nums</code> and put it at the end of <code>nums</code>.</li>
</ul>
<p>The prefix sum array of <code>nums</code> is an array <code>prefix</code> of the same length as <code>nums</code> such that <code>prefix[i]</code> is the sum of all the integers <code>nums[j]</code> where <code>j</code> is in the inclusive range <code>[0, i]</code>.</p>
<p>Return <em>the minimum number of operations such that the prefix sum array does not contain negative integers</em>. The test cases are generated such that it is always possible to make the prefix sum array non-negative.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,-5,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> we do not need to do any operations.
The array is [2,3,-5,4]. The prefix sum array is [2, 5, 0, 4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,-5,-2,6]
<strong>Output:</strong> 1
<strong>Explanation:</strong> we can do one operation on index 1.
The array after the operation is [3,-2,6,-5]. The prefix sum array is [3, 1, 7, 2].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Heap (Priority Queue)
|
C++
|
class Solution {
public:
int makePrefSumNonNegative(vector<int>& nums) {
priority_queue<int, vector<int>, greater<int>> pq;
int ans = 0;
long long s = 0;
for (int& x : nums) {
s += x;
if (x < 0) {
pq.push(x);
}
while (s < 0) {
s -= pq.top();
pq.pop();
++ans;
}
}
return ans;
}
};
|
2,599
|
Make the Prefix Sum Non-negative
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. You can apply the following operation any number of times:</p>
<ul>
<li>Pick any element from <code>nums</code> and put it at the end of <code>nums</code>.</li>
</ul>
<p>The prefix sum array of <code>nums</code> is an array <code>prefix</code> of the same length as <code>nums</code> such that <code>prefix[i]</code> is the sum of all the integers <code>nums[j]</code> where <code>j</code> is in the inclusive range <code>[0, i]</code>.</p>
<p>Return <em>the minimum number of operations such that the prefix sum array does not contain negative integers</em>. The test cases are generated such that it is always possible to make the prefix sum array non-negative.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,-5,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> we do not need to do any operations.
The array is [2,3,-5,4]. The prefix sum array is [2, 5, 0, 4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,-5,-2,6]
<strong>Output:</strong> 1
<strong>Explanation:</strong> we can do one operation on index 1.
The array after the operation is [3,-2,6,-5]. The prefix sum array is [3, 1, 7, 2].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Heap (Priority Queue)
|
Go
|
func makePrefSumNonNegative(nums []int) (ans int) {
pq := hp{}
s := 0
for _, x := range nums {
s += x
if x < 0 {
heap.Push(&pq, x)
}
for s < 0 {
s -= heap.Pop(&pq).(int)
ans++
}
}
return ans
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
|
2,599
|
Make the Prefix Sum Non-negative
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. You can apply the following operation any number of times:</p>
<ul>
<li>Pick any element from <code>nums</code> and put it at the end of <code>nums</code>.</li>
</ul>
<p>The prefix sum array of <code>nums</code> is an array <code>prefix</code> of the same length as <code>nums</code> such that <code>prefix[i]</code> is the sum of all the integers <code>nums[j]</code> where <code>j</code> is in the inclusive range <code>[0, i]</code>.</p>
<p>Return <em>the minimum number of operations such that the prefix sum array does not contain negative integers</em>. The test cases are generated such that it is always possible to make the prefix sum array non-negative.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,-5,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> we do not need to do any operations.
The array is [2,3,-5,4]. The prefix sum array is [2, 5, 0, 4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,-5,-2,6]
<strong>Output:</strong> 1
<strong>Explanation:</strong> we can do one operation on index 1.
The array after the operation is [3,-2,6,-5]. The prefix sum array is [3, 1, 7, 2].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Heap (Priority Queue)
|
Java
|
class Solution {
public int makePrefSumNonNegative(int[] nums) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
int ans = 0;
long s = 0;
for (int x : nums) {
s += x;
if (x < 0) {
pq.offer(x);
}
while (s < 0) {
s -= pq.poll();
++ans;
}
}
return ans;
}
}
|
2,599
|
Make the Prefix Sum Non-negative
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. You can apply the following operation any number of times:</p>
<ul>
<li>Pick any element from <code>nums</code> and put it at the end of <code>nums</code>.</li>
</ul>
<p>The prefix sum array of <code>nums</code> is an array <code>prefix</code> of the same length as <code>nums</code> such that <code>prefix[i]</code> is the sum of all the integers <code>nums[j]</code> where <code>j</code> is in the inclusive range <code>[0, i]</code>.</p>
<p>Return <em>the minimum number of operations such that the prefix sum array does not contain negative integers</em>. The test cases are generated such that it is always possible to make the prefix sum array non-negative.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,-5,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> we do not need to do any operations.
The array is [2,3,-5,4]. The prefix sum array is [2, 5, 0, 4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,-5,-2,6]
<strong>Output:</strong> 1
<strong>Explanation:</strong> we can do one operation on index 1.
The array after the operation is [3,-2,6,-5]. The prefix sum array is [3, 1, 7, 2].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Heap (Priority Queue)
|
Python
|
class Solution:
def makePrefSumNonNegative(self, nums: List[int]) -> int:
h = []
ans = s = 0
for x in nums:
s += x
if x < 0:
heappush(h, x)
while s < 0:
s -= heappop(h)
ans += 1
return ans
|
2,599
|
Make the Prefix Sum Non-negative
|
Medium
|
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. You can apply the following operation any number of times:</p>
<ul>
<li>Pick any element from <code>nums</code> and put it at the end of <code>nums</code>.</li>
</ul>
<p>The prefix sum array of <code>nums</code> is an array <code>prefix</code> of the same length as <code>nums</code> such that <code>prefix[i]</code> is the sum of all the integers <code>nums[j]</code> where <code>j</code> is in the inclusive range <code>[0, i]</code>.</p>
<p>Return <em>the minimum number of operations such that the prefix sum array does not contain negative integers</em>. The test cases are generated such that it is always possible to make the prefix sum array non-negative.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [2,3,-5,4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> we do not need to do any operations.
The array is [2,3,-5,4]. The prefix sum array is [2, 5, 0, 4].
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [3,-5,-2,6]
<strong>Output:</strong> 1
<strong>Explanation:</strong> we can do one operation on index 1.
The array after the operation is [3,-2,6,-5]. The prefix sum array is [3, 1, 7, 2].
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Greedy; Array; Heap (Priority Queue)
|
TypeScript
|
function makePrefSumNonNegative(nums: number[]): number {
const pq = new MinPriorityQueue();
let ans = 0;
let s = 0;
for (const x of nums) {
s += x;
if (x < 0) {
pq.enqueue(x);
}
while (s < 0) {
s -= pq.dequeue().element;
++ans;
}
}
return ans;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.