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,850
Minimum Moves to Spread Stones Over Grid
Medium
<p>You are given a <strong>0-indexed</strong> 2D integer matrix <code>grid</code> of size <code>3 * 3</code>, representing the number of stones in each cell. The grid contains exactly <code>9</code> stones, and there can be <strong>multiple</strong> stones in a single cell.</p> <p>In one move, you can move a single stone from its current cell to any other cell if the two cells share a side.</p> <p>Return <em>the <strong>minimum number of moves</strong> required to place one stone in each cell</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2850.Minimum%20Moves%20to%20Spread%20Stones%20Over%20Grid/images/example1-3.svg" style="width: 401px; height: 281px;" /> <pre> <strong>Input:</strong> grid = [[1,1,0],[1,1,1],[1,2,1]] <strong>Output:</strong> 3 <strong>Explanation:</strong> One possible sequence of moves to place one stone in each cell is: 1- Move one stone from cell (2,1) to cell (2,2). 2- Move one stone from cell (2,2) to cell (1,2). 3- Move one stone from cell (1,2) to cell (0,2). In total, it takes 3 moves to place one stone in each cell of the grid. It can be shown that 3 is the minimum number of moves required to place one stone in each cell. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2850.Minimum%20Moves%20to%20Spread%20Stones%20Over%20Grid/images/example2-2.svg" style="width: 401px; height: 281px;" /> <pre> <strong>Input:</strong> grid = [[1,3,0],[1,0,0],[1,0,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One possible sequence of moves to place one stone in each cell is: 1- Move one stone from cell (0,1) to cell (0,2). 2- Move one stone from cell (0,1) to cell (1,1). 3- Move one stone from cell (2,2) to cell (1,2). 4- Move one stone from cell (2,2) to cell (2,1). In total, it takes 4 moves to place one stone in each cell of the grid. It can be shown that 4 is the minimum number of moves required to place one stone in each cell. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>grid.length == grid[i].length == 3</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 9</code></li> <li>Sum of <code>grid</code> is equal to <code>9</code>.</li> </ul>
Breadth-First Search; Array; Dynamic Programming; Matrix
C++
class Solution { public: int minimumMoves(vector<vector<int>>& grid) { queue<string> q; q.push(f(grid)); unordered_set<string> vis; vis.insert(f(grid)); vector<int> dirs = {-1, 0, 1, 0, -1}; for (int ans = 0;; ++ans) { int sz = q.size(); while (sz--) { string p = q.front(); q.pop(); if (p == "111111111") { return ans; } vector<vector<int>> cur = g(p); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (cur[i][j] > 1) { for (int d = 0; d < 4; ++d) { int x = i + dirs[d]; int y = j + dirs[d + 1]; if (x >= 0 && x < 3 && y >= 0 && y < 3 && cur[x][y] < 2) { vector<vector<int>> nxt = cur; nxt[i][j]--; nxt[x][y]++; string s = f(nxt); if (!vis.count(s)) { vis.insert(s); q.push(s); } } } } } } } } } private: string f(const vector<vector<int>>& grid) { string s; for (const auto& row : grid) { for (int x : row) { s += to_string(x); } } return s; } vector<vector<int>> g(const string& s) { vector<vector<int>> grid(3, vector<int>(3)); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { grid[i][j] = s[i * 3 + j] - '0'; } } return grid; } };
2,850
Minimum Moves to Spread Stones Over Grid
Medium
<p>You are given a <strong>0-indexed</strong> 2D integer matrix <code>grid</code> of size <code>3 * 3</code>, representing the number of stones in each cell. The grid contains exactly <code>9</code> stones, and there can be <strong>multiple</strong> stones in a single cell.</p> <p>In one move, you can move a single stone from its current cell to any other cell if the two cells share a side.</p> <p>Return <em>the <strong>minimum number of moves</strong> required to place one stone in each cell</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2850.Minimum%20Moves%20to%20Spread%20Stones%20Over%20Grid/images/example1-3.svg" style="width: 401px; height: 281px;" /> <pre> <strong>Input:</strong> grid = [[1,1,0],[1,1,1],[1,2,1]] <strong>Output:</strong> 3 <strong>Explanation:</strong> One possible sequence of moves to place one stone in each cell is: 1- Move one stone from cell (2,1) to cell (2,2). 2- Move one stone from cell (2,2) to cell (1,2). 3- Move one stone from cell (1,2) to cell (0,2). In total, it takes 3 moves to place one stone in each cell of the grid. It can be shown that 3 is the minimum number of moves required to place one stone in each cell. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2850.Minimum%20Moves%20to%20Spread%20Stones%20Over%20Grid/images/example2-2.svg" style="width: 401px; height: 281px;" /> <pre> <strong>Input:</strong> grid = [[1,3,0],[1,0,0],[1,0,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One possible sequence of moves to place one stone in each cell is: 1- Move one stone from cell (0,1) to cell (0,2). 2- Move one stone from cell (0,1) to cell (1,1). 3- Move one stone from cell (2,2) to cell (1,2). 4- Move one stone from cell (2,2) to cell (2,1). In total, it takes 4 moves to place one stone in each cell of the grid. It can be shown that 4 is the minimum number of moves required to place one stone in each cell. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>grid.length == grid[i].length == 3</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 9</code></li> <li>Sum of <code>grid</code> is equal to <code>9</code>.</li> </ul>
Breadth-First Search; Array; Dynamic Programming; Matrix
Go
type Queue []string func (q *Queue) Push(s string) { *q = append(*q, s) } func (q *Queue) Pop() string { s := (*q)[0] *q = (*q)[1:] return s } func (q *Queue) Empty() bool { return len(*q) == 0 } func minimumMoves(grid [][]int) int { q := Queue{f(grid)} vis := map[string]bool{f(grid): true} dirs := []int{-1, 0, 1, 0, -1} for ans := 0; ; ans++ { sz := len(q) for ; sz > 0; sz-- { p := q.Pop() if p == "111111111" { return ans } cur := g(p) for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { if cur[i][j] > 1 { for d := 0; d < 4; d++ { x, y := i+dirs[d], j+dirs[d+1] if x >= 0 && x < 3 && y >= 0 && y < 3 && cur[x][y] < 2 { nxt := make([][]int, 3) for r := range nxt { nxt[r] = append([]int(nil), cur[r]...) } nxt[i][j]-- nxt[x][y]++ s := f(nxt) if !vis[s] { vis[s] = true q.Push(s) } } } } } } } } } func f(grid [][]int) string { var sb strings.Builder for _, row := range grid { for _, x := range row { sb.WriteByte(byte(x) + '0') } } return sb.String() } func g(s string) [][]int { grid := make([][]int, 3) for i := range grid { grid[i] = make([]int, 3) for j := 0; j < 3; j++ { grid[i][j] = int(s[i*3+j] - '0') } } return grid }
2,850
Minimum Moves to Spread Stones Over Grid
Medium
<p>You are given a <strong>0-indexed</strong> 2D integer matrix <code>grid</code> of size <code>3 * 3</code>, representing the number of stones in each cell. The grid contains exactly <code>9</code> stones, and there can be <strong>multiple</strong> stones in a single cell.</p> <p>In one move, you can move a single stone from its current cell to any other cell if the two cells share a side.</p> <p>Return <em>the <strong>minimum number of moves</strong> required to place one stone in each cell</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2850.Minimum%20Moves%20to%20Spread%20Stones%20Over%20Grid/images/example1-3.svg" style="width: 401px; height: 281px;" /> <pre> <strong>Input:</strong> grid = [[1,1,0],[1,1,1],[1,2,1]] <strong>Output:</strong> 3 <strong>Explanation:</strong> One possible sequence of moves to place one stone in each cell is: 1- Move one stone from cell (2,1) to cell (2,2). 2- Move one stone from cell (2,2) to cell (1,2). 3- Move one stone from cell (1,2) to cell (0,2). In total, it takes 3 moves to place one stone in each cell of the grid. It can be shown that 3 is the minimum number of moves required to place one stone in each cell. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2850.Minimum%20Moves%20to%20Spread%20Stones%20Over%20Grid/images/example2-2.svg" style="width: 401px; height: 281px;" /> <pre> <strong>Input:</strong> grid = [[1,3,0],[1,0,0],[1,0,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One possible sequence of moves to place one stone in each cell is: 1- Move one stone from cell (0,1) to cell (0,2). 2- Move one stone from cell (0,1) to cell (1,1). 3- Move one stone from cell (2,2) to cell (1,2). 4- Move one stone from cell (2,2) to cell (2,1). In total, it takes 4 moves to place one stone in each cell of the grid. It can be shown that 4 is the minimum number of moves required to place one stone in each cell. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>grid.length == grid[i].length == 3</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 9</code></li> <li>Sum of <code>grid</code> is equal to <code>9</code>.</li> </ul>
Breadth-First Search; Array; Dynamic Programming; Matrix
Java
class Solution { public int minimumMoves(int[][] grid) { Deque<String> q = new ArrayDeque<>(); q.add(f(grid)); Set<String> vis = new HashSet<>(); vis.add(f(grid)); int[] dirs = {-1, 0, 1, 0, -1}; for (int ans = 0;; ++ans) { for (int k = q.size(); k > 0; --k) { String p = q.poll(); if ("111111111".equals(p)) { return ans; } int[][] cur = g(p); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (cur[i][j] > 1) { for (int d = 0; d < 4; ++d) { int x = i + dirs[d]; int y = j + dirs[d + 1]; if (x >= 0 && x < 3 && y >= 0 && y < 3 && cur[x][y] < 2) { int[][] nxt = new int[3][3]; for (int r = 0; r < 3; ++r) { for (int c = 0; c < 3; ++c) { nxt[r][c] = cur[r][c]; } } nxt[i][j]--; nxt[x][y]++; String s = f(nxt); if (!vis.contains(s)) { vis.add(s); q.add(s); } } } } } } } } } private String f(int[][] grid) { StringBuilder sb = new StringBuilder(); for (int[] row : grid) { for (int x : row) { sb.append(x); } } return sb.toString(); } private int[][] g(String s) { int[][] grid = new int[3][3]; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { grid[i][j] = s.charAt(i * 3 + j) - '0'; } } return grid; } }
2,850
Minimum Moves to Spread Stones Over Grid
Medium
<p>You are given a <strong>0-indexed</strong> 2D integer matrix <code>grid</code> of size <code>3 * 3</code>, representing the number of stones in each cell. The grid contains exactly <code>9</code> stones, and there can be <strong>multiple</strong> stones in a single cell.</p> <p>In one move, you can move a single stone from its current cell to any other cell if the two cells share a side.</p> <p>Return <em>the <strong>minimum number of moves</strong> required to place one stone in each cell</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2850.Minimum%20Moves%20to%20Spread%20Stones%20Over%20Grid/images/example1-3.svg" style="width: 401px; height: 281px;" /> <pre> <strong>Input:</strong> grid = [[1,1,0],[1,1,1],[1,2,1]] <strong>Output:</strong> 3 <strong>Explanation:</strong> One possible sequence of moves to place one stone in each cell is: 1- Move one stone from cell (2,1) to cell (2,2). 2- Move one stone from cell (2,2) to cell (1,2). 3- Move one stone from cell (1,2) to cell (0,2). In total, it takes 3 moves to place one stone in each cell of the grid. It can be shown that 3 is the minimum number of moves required to place one stone in each cell. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2850.Minimum%20Moves%20to%20Spread%20Stones%20Over%20Grid/images/example2-2.svg" style="width: 401px; height: 281px;" /> <pre> <strong>Input:</strong> grid = [[1,3,0],[1,0,0],[1,0,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One possible sequence of moves to place one stone in each cell is: 1- Move one stone from cell (0,1) to cell (0,2). 2- Move one stone from cell (0,1) to cell (1,1). 3- Move one stone from cell (2,2) to cell (1,2). 4- Move one stone from cell (2,2) to cell (2,1). In total, it takes 4 moves to place one stone in each cell of the grid. It can be shown that 4 is the minimum number of moves required to place one stone in each cell. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>grid.length == grid[i].length == 3</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 9</code></li> <li>Sum of <code>grid</code> is equal to <code>9</code>.</li> </ul>
Breadth-First Search; Array; Dynamic Programming; Matrix
Python
class Solution: def minimumMoves(self, grid: List[List[int]]) -> int: q = deque([tuple(tuple(row) for row in grid)]) vis = set(q) ans = 0 dirs = (-1, 0, 1, 0, -1) while 1: for _ in range(len(q)): cur = q.popleft() if all(x for row in cur for x in row): return ans for i in range(3): for j in range(3): if cur[i][j] > 1: for a, b in pairwise(dirs): x, y = i + a, j + b if 0 <= x < 3 and 0 <= y < 3 and cur[x][y] < 2: nxt = [list(row) for row in cur] nxt[i][j] -= 1 nxt[x][y] += 1 nxt = tuple(tuple(row) for row in nxt) if nxt not in vis: vis.add(nxt) q.append(nxt) ans += 1
2,850
Minimum Moves to Spread Stones Over Grid
Medium
<p>You are given a <strong>0-indexed</strong> 2D integer matrix <code>grid</code> of size <code>3 * 3</code>, representing the number of stones in each cell. The grid contains exactly <code>9</code> stones, and there can be <strong>multiple</strong> stones in a single cell.</p> <p>In one move, you can move a single stone from its current cell to any other cell if the two cells share a side.</p> <p>Return <em>the <strong>minimum number of moves</strong> required to place one stone in each cell</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2850.Minimum%20Moves%20to%20Spread%20Stones%20Over%20Grid/images/example1-3.svg" style="width: 401px; height: 281px;" /> <pre> <strong>Input:</strong> grid = [[1,1,0],[1,1,1],[1,2,1]] <strong>Output:</strong> 3 <strong>Explanation:</strong> One possible sequence of moves to place one stone in each cell is: 1- Move one stone from cell (2,1) to cell (2,2). 2- Move one stone from cell (2,2) to cell (1,2). 3- Move one stone from cell (1,2) to cell (0,2). In total, it takes 3 moves to place one stone in each cell of the grid. It can be shown that 3 is the minimum number of moves required to place one stone in each cell. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2850.Minimum%20Moves%20to%20Spread%20Stones%20Over%20Grid/images/example2-2.svg" style="width: 401px; height: 281px;" /> <pre> <strong>Input:</strong> grid = [[1,3,0],[1,0,0],[1,0,3]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One possible sequence of moves to place one stone in each cell is: 1- Move one stone from cell (0,1) to cell (0,2). 2- Move one stone from cell (0,1) to cell (1,1). 3- Move one stone from cell (2,2) to cell (1,2). 4- Move one stone from cell (2,2) to cell (2,1). In total, it takes 4 moves to place one stone in each cell of the grid. It can be shown that 4 is the minimum number of moves required to place one stone in each cell. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>grid.length == grid[i].length == 3</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 9</code></li> <li>Sum of <code>grid</code> is equal to <code>9</code>.</li> </ul>
Breadth-First Search; Array; Dynamic Programming; Matrix
TypeScript
function minimumMoves(grid: number[][]): number { const q: string[] = [f(grid)]; const vis: Set<string> = new Set([f(grid)]); const dirs: number[] = [-1, 0, 1, 0, -1]; for (let ans = 0; ; ans++) { let sz = q.length; while (sz-- > 0) { const p = q.shift()!; if (p === '111111111') { return ans; } const cur = g(p); for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (cur[i][j] > 1) { for (let d = 0; d < 4; d++) { const x = i + dirs[d], y = j + dirs[d + 1]; if (x >= 0 && x < 3 && y >= 0 && y < 3 && cur[x][y] < 2) { const nxt = cur.map(row => [...row]); nxt[i][j]--; nxt[x][y]++; const s = f(nxt); if (!vis.has(s)) { vis.add(s); q.push(s); } } } } } } } } } function f(grid: number[][]): string { return grid.flat().join(''); } function g(s: string): number[][] { return Array.from({ length: 3 }, (_, i) => Array.from({ length: 3 }, (_, j) => Number(s[i * 3 + j])), ); }
2,851
String Transformation
Hard
<p>You are given two strings <code>s</code> and <code>t</code> of equal length <code>n</code>. You can perform the following operation on the string <code>s</code>:</p> <ul> <li>Remove a <strong>suffix</strong> of <code>s</code> of length <code>l</code> where <code>0 &lt; l &lt; n</code> and append it at the start of <code>s</code>.<br /> For example, let <code>s = &#39;abcd&#39;</code> then in one operation you can remove the suffix <code>&#39;cd&#39;</code> and append it in front of <code>s</code> making <code>s = &#39;cdab&#39;</code>.</li> </ul> <p>You are also given an integer <code>k</code>. Return <em>the number of ways in which </em><code>s</code> <em>can be transformed into </em><code>t</code><em> in <strong>exactly</strong> </em><code>k</code><em> operations.</em></p> <p>Since the answer can be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, t = &quot;cdab&quot;, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> First way: In first operation, choose suffix from index = 3, so resulting s = &quot;dabc&quot;. In second operation, choose suffix from index = 3, so resulting s = &quot;cdab&quot;. Second way: In first operation, choose suffix from index = 1, so resulting s = &quot;bcda&quot;. In second operation, choose suffix from index = 1, so resulting s = &quot;cdab&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ababab&quot;, t = &quot;ababab&quot;, k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> First way: Choose suffix from index = 2, so resulting s = &quot;ababab&quot;. Second way: Choose suffix from index = 4, so resulting s = &quot;ababab&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>15</sup></code></li> <li><code>s.length == t.length</code></li> <li><code>s</code> and <code>t</code> consist of only lowercase English alphabets.</li> </ul>
Math; String; Dynamic Programming; String Matching
C++
class Solution { const int M = 1000000007; int add(int x, int y) { if ((x += y) >= M) { x -= M; } return x; } int mul(long long x, long long y) { return x * y % M; } vector<int> getz(const string& s) { const int n = s.length(); vector<int> z(n); for (int i = 1, left = 0, right = 0; i < n; ++i) { if (i <= right && z[i - left] <= right - i) { z[i] = z[i - left]; } else { for (z[i] = max(0, right - i + 1); i + z[i] < n && s[i + z[i]] == s[z[i]]; ++z[i]) ; } if (i + z[i] - 1 > right) { left = i; right = i + z[i] - 1; } } return z; } vector<vector<int>> mul(const vector<vector<int>>& a, const vector<vector<int>>& b) { const int m = a.size(), n = a[0].size(), p = b[0].size(); vector<vector<int>> r(m, vector<int>(p)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { for (int k = 0; k < p; ++k) { r[i][k] = add(r[i][k], mul(a[i][j], b[j][k])); } } } return r; } vector<vector<int>> pow(const vector<vector<int>>& a, long long y) { const int n = a.size(); vector<vector<int>> r(n, vector<int>(n)); for (int i = 0; i < n; ++i) { r[i][i] = 1; } auto x = a; for (; y; y >>= 1) { if (y & 1) { r = mul(r, x); } x = mul(x, x); } return r; } public: int numberOfWays(string s, string t, long long k) { const int n = s.length(); const auto dp = pow({{0, 1}, {n - 1, n - 2}}, k)[0]; s.append(t); s.append(t); const auto z = getz(s); const int m = n + n; int r = 0; for (int i = n; i < m; ++i) { if (z[i] >= n) { r = add(r, dp[!!(i - n)]); } } return r; } };
2,851
String Transformation
Hard
<p>You are given two strings <code>s</code> and <code>t</code> of equal length <code>n</code>. You can perform the following operation on the string <code>s</code>:</p> <ul> <li>Remove a <strong>suffix</strong> of <code>s</code> of length <code>l</code> where <code>0 &lt; l &lt; n</code> and append it at the start of <code>s</code>.<br /> For example, let <code>s = &#39;abcd&#39;</code> then in one operation you can remove the suffix <code>&#39;cd&#39;</code> and append it in front of <code>s</code> making <code>s = &#39;cdab&#39;</code>.</li> </ul> <p>You are also given an integer <code>k</code>. Return <em>the number of ways in which </em><code>s</code> <em>can be transformed into </em><code>t</code><em> in <strong>exactly</strong> </em><code>k</code><em> operations.</em></p> <p>Since the answer can be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, t = &quot;cdab&quot;, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> First way: In first operation, choose suffix from index = 3, so resulting s = &quot;dabc&quot;. In second operation, choose suffix from index = 3, so resulting s = &quot;cdab&quot;. Second way: In first operation, choose suffix from index = 1, so resulting s = &quot;bcda&quot;. In second operation, choose suffix from index = 1, so resulting s = &quot;cdab&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ababab&quot;, t = &quot;ababab&quot;, k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> First way: Choose suffix from index = 2, so resulting s = &quot;ababab&quot;. Second way: Choose suffix from index = 4, so resulting s = &quot;ababab&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>15</sup></code></li> <li><code>s.length == t.length</code></li> <li><code>s</code> and <code>t</code> consist of only lowercase English alphabets.</li> </ul>
Math; String; Dynamic Programming; String Matching
Java
class Solution { private static final int M = 1000000007; private int add(int x, int y) { if ((x += y) >= M) { x -= M; } return x; } private int mul(long x, long y) { return (int) (x * y % M); } private int[] getZ(String s) { int n = s.length(); int[] z = new int[n]; for (int i = 1, left = 0, right = 0; i < n; ++i) { if (i <= right && z[i - left] <= right - i) { z[i] = z[i - left]; } else { int z_i = Math.max(0, right - i + 1); while (i + z_i < n && s.charAt(i + z_i) == s.charAt(z_i)) { z_i++; } z[i] = z_i; } if (i + z[i] - 1 > right) { left = i; right = i + z[i] - 1; } } return z; } private int[][] matrixMultiply(int[][] a, int[][] b) { int m = a.length, n = a[0].length, p = b[0].length; int[][] r = new int[m][p]; for (int i = 0; i < m; ++i) { for (int j = 0; j < p; ++j) { for (int k = 0; k < n; ++k) { r[i][j] = add(r[i][j], mul(a[i][k], b[k][j])); } } } return r; } private int[][] matrixPower(int[][] a, long y) { int n = a.length; int[][] r = new int[n][n]; for (int i = 0; i < n; ++i) { r[i][i] = 1; } int[][] x = new int[n][n]; for (int i = 0; i < n; ++i) { System.arraycopy(a[i], 0, x[i], 0, n); } while (y > 0) { if ((y & 1) == 1) { r = matrixMultiply(r, x); } x = matrixMultiply(x, x); y >>= 1; } return r; } public int numberOfWays(String s, String t, long k) { int n = s.length(); int[] dp = matrixPower(new int[][] {{0, 1}, {n - 1, n - 2}}, k)[0]; s += t + t; int[] z = getZ(s); int m = n + n; int result = 0; for (int i = n; i < m; ++i) { if (z[i] >= n) { result = add(result, dp[i - n == 0 ? 0 : 1]); } } return result; } }
2,851
String Transformation
Hard
<p>You are given two strings <code>s</code> and <code>t</code> of equal length <code>n</code>. You can perform the following operation on the string <code>s</code>:</p> <ul> <li>Remove a <strong>suffix</strong> of <code>s</code> of length <code>l</code> where <code>0 &lt; l &lt; n</code> and append it at the start of <code>s</code>.<br /> For example, let <code>s = &#39;abcd&#39;</code> then in one operation you can remove the suffix <code>&#39;cd&#39;</code> and append it in front of <code>s</code> making <code>s = &#39;cdab&#39;</code>.</li> </ul> <p>You are also given an integer <code>k</code>. Return <em>the number of ways in which </em><code>s</code> <em>can be transformed into </em><code>t</code><em> in <strong>exactly</strong> </em><code>k</code><em> operations.</em></p> <p>Since the answer can be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, t = &quot;cdab&quot;, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> First way: In first operation, choose suffix from index = 3, so resulting s = &quot;dabc&quot;. In second operation, choose suffix from index = 3, so resulting s = &quot;cdab&quot;. Second way: In first operation, choose suffix from index = 1, so resulting s = &quot;bcda&quot;. In second operation, choose suffix from index = 1, so resulting s = &quot;cdab&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ababab&quot;, t = &quot;ababab&quot;, k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> First way: Choose suffix from index = 2, so resulting s = &quot;ababab&quot;. Second way: Choose suffix from index = 4, so resulting s = &quot;ababab&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>15</sup></code></li> <li><code>s.length == t.length</code></li> <li><code>s</code> and <code>t</code> consist of only lowercase English alphabets.</li> </ul>
Math; String; Dynamic Programming; String Matching
Python
""" DP, Z-algorithm, Fast mod. Approach How to represent a string? Each operation is just a rotation. Each result string can be represented by an integer from 0 to n - 1. Namely, it's just the new index of s[0]. How to find the integer(s) that can represent string t? Create a new string s + t + t (length = 3 * n). Use Z-algorithm (or KMP), for each n <= index < 2 * n, calculate the maximum prefix length that each substring starts from index can match, if the length >= n, then (index - n) is a valid integer representation. How to get the result? It's a very obvious DP. If we use an integer to represent a string, we only need to consider the transition from zero to non-zero and from non-zero to zero. In other words, all the non-zero strings should have the same result. So let dp[t][i = 0/1] be the number of ways to get the zero/nonzero string after excatly t steps. Then dp[t][0] = dp[t - 1][1] * (n - 1). All the non zero strings can make it. dp[t][1] = dp[t - 1][0] + dp[t - 1] * (n - 2). For a particular non zero string, all the other non zero strings and zero string can make it. We have dp[0][0] = 1 and dp[0][1] = 0 Use matrix multiplication. How to calculate dp[k][x = 0, 1] faster? Use matrix multiplication vector (dp[t - 1][0], dp[t - 1][1]) multiplies matrix [0 1] [n - 1 n - 2] == vector (dp[t][0], dp[t - 1][1]). So we just need to calculate the kth power of the matrix which can be done by fast power algorith. Complexity Time complexity: O(n + logk) Space complexity: O(n) """ class Solution: M: int = 1000000007 def add(self, x: int, y: int) -> int: x += y if x >= self.M: x -= self.M return x def mul(self, x: int, y: int) -> int: return int(x * y % self.M) def getZ(self, s: str) -> List[int]: n = len(s) z = [0] * n left = right = 0 for i in range(1, n): if i <= right and z[i - left] <= right - i: z[i] = z[i - left] else: z_i = max(0, right - i + 1) while i + z_i < n and s[i + z_i] == s[z_i]: z_i += 1 z[i] = z_i if i + z[i] - 1 > right: left = i right = i + z[i] - 1 return z def matrixMultiply(self, a: List[List[int]], b: List[List[int]]) -> List[List[int]]: m = len(a) n = len(a[0]) p = len(b[0]) r = [[0] * p for _ in range(m)] for i in range(m): for j in range(p): for k in range(n): r[i][j] = self.add(r[i][j], self.mul(a[i][k], b[k][j])) return r def matrixPower(self, a: List[List[int]], y: int) -> List[List[int]]: n = len(a) r = [[0] * n for _ in range(n)] for i in range(n): r[i][i] = 1 x = [a[i][:] for i in range(n)] while y > 0: if y & 1: r = self.matrixMultiply(r, x) x = self.matrixMultiply(x, x) y >>= 1 return r def numberOfWays(self, s: str, t: str, k: int) -> int: n = len(s) dp = self.matrixPower([[0, 1], [n - 1, n - 2]], k)[0] s += t + t z = self.getZ(s) m = n + n result = 0 for i in range(n, m): if z[i] >= n: result = self.add(result, dp[0] if i - n == 0 else dp[1]) return result
2,852
Sum of Remoteness of All Cells
Medium
<p>You are given a <strong>0-indexed</strong> matrix <code>grid</code> of order <code>n * n</code>. Each cell in this matrix has a value <code>grid[i][j]</code>, which is either a <strong>positive</strong> integer or <code>-1</code> representing a blocked cell.</p> <p>You can move from a non-blocked cell to any non-blocked cell that shares an edge.</p> <p>For any cell <code>(i, j)</code>, we represent its <strong>remoteness</strong> as <code>R[i][j]</code> which is defined as the following:</p> <ul> <li>If the cell <code>(i, j)</code> is a <strong>non-blocked</strong> cell, <code>R[i][j]</code> is the sum of the values <code>grid[x][y]</code> such that there is <strong>no path</strong> from the <strong>non-blocked</strong> cell <code>(x, y)</code> to the cell <code>(i, j)</code>.</li> <li>For blocked cells, <code>R[i][j] == 0</code>.</li> </ul> <p>Return<em> the sum of </em><code>R[i][j]</code><em> over all cells.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2852.Sum%20of%20Remoteness%20of%20All%20Cells/images/1-new.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 400px; height: 304px;" /></p> <pre> <strong>Input:</strong> grid = [[-1,1,-1],[5,-1,4],[-1,3,-1]] <strong>Output:</strong> 39 <strong>Explanation:</strong> In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 0 + 12 + 0 + 8 + 0 + 9 + 0 + 10 + 0 = 39. Let&#39;s jump on the bottom-left grid in the above picture and calculate R[0][1] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (0, 1). These cells are colored yellow in this grid. So R[0][1] = 5 + 4 + 3 = 12. Now let&#39;s jump on the bottom-right grid in the above picture and calculate R[1][2] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (1, 2). These cells are colored yellow in this grid. So R[1][2] = 1 + 5 + 3 = 9. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2852.Sum%20of%20Remoteness%20of%20All%20Cells/images/2.png" style="width: 400px; height: 302px; background: #fff; border-radius: .5rem;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[-1,3,4],[-1,-1,-1],[3,-1,-1]] <strong>Output:</strong> 13 <strong>Explanation:</strong> In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 3 + 3 + 0 + 0 + 0 + 0 + 7 + 0 + 0 = 13. Let&#39;s jump on the bottom-left grid in the above picture and calculate R[0][2] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (0, 2). This cell is colored yellow in this grid. So R[0][2] = 3. Now let&#39;s jump on the bottom-right grid in the above picture and calculate R[2][0] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (2, 0). These cells are colored yellow in this grid. So R[2][0] = 3 + 4 = 7. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> grid = [[1]] <strong>Output:</strong> 0 <strong>Explanation:</strong> Since there are no other cells than (0, 0), R[0][0] is equal to 0. So the sum of R[i][j] over all cells would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 300</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>6</sup></code> or <code>grid[i][j] == -1</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Hash Table; Matrix
C++
class Solution { public: long long sumRemoteness(vector<vector<int>>& grid) { using pli = pair<long long, int>; int n = grid.size(); int cnt = 0; for (auto& row : grid) { for (int x : row) { cnt += x > 0; } } int dirs[5] = {-1, 0, 1, 0, -1}; function<pli(int, int)> dfs = [&](int i, int j) { long long s = grid[i][j]; int t = 1; grid[i][j] = 0; for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] > 0) { auto [ss, tt] = dfs(x, y); s += ss; t += tt; } } return pli(s, t); }; long long ans = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] > 0) { auto [s, t] = dfs(i, j); ans += (cnt - t) * s; } } } return ans; } };
2,852
Sum of Remoteness of All Cells
Medium
<p>You are given a <strong>0-indexed</strong> matrix <code>grid</code> of order <code>n * n</code>. Each cell in this matrix has a value <code>grid[i][j]</code>, which is either a <strong>positive</strong> integer or <code>-1</code> representing a blocked cell.</p> <p>You can move from a non-blocked cell to any non-blocked cell that shares an edge.</p> <p>For any cell <code>(i, j)</code>, we represent its <strong>remoteness</strong> as <code>R[i][j]</code> which is defined as the following:</p> <ul> <li>If the cell <code>(i, j)</code> is a <strong>non-blocked</strong> cell, <code>R[i][j]</code> is the sum of the values <code>grid[x][y]</code> such that there is <strong>no path</strong> from the <strong>non-blocked</strong> cell <code>(x, y)</code> to the cell <code>(i, j)</code>.</li> <li>For blocked cells, <code>R[i][j] == 0</code>.</li> </ul> <p>Return<em> the sum of </em><code>R[i][j]</code><em> over all cells.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2852.Sum%20of%20Remoteness%20of%20All%20Cells/images/1-new.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 400px; height: 304px;" /></p> <pre> <strong>Input:</strong> grid = [[-1,1,-1],[5,-1,4],[-1,3,-1]] <strong>Output:</strong> 39 <strong>Explanation:</strong> In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 0 + 12 + 0 + 8 + 0 + 9 + 0 + 10 + 0 = 39. Let&#39;s jump on the bottom-left grid in the above picture and calculate R[0][1] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (0, 1). These cells are colored yellow in this grid. So R[0][1] = 5 + 4 + 3 = 12. Now let&#39;s jump on the bottom-right grid in the above picture and calculate R[1][2] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (1, 2). These cells are colored yellow in this grid. So R[1][2] = 1 + 5 + 3 = 9. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2852.Sum%20of%20Remoteness%20of%20All%20Cells/images/2.png" style="width: 400px; height: 302px; background: #fff; border-radius: .5rem;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[-1,3,4],[-1,-1,-1],[3,-1,-1]] <strong>Output:</strong> 13 <strong>Explanation:</strong> In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 3 + 3 + 0 + 0 + 0 + 0 + 7 + 0 + 0 = 13. Let&#39;s jump on the bottom-left grid in the above picture and calculate R[0][2] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (0, 2). This cell is colored yellow in this grid. So R[0][2] = 3. Now let&#39;s jump on the bottom-right grid in the above picture and calculate R[2][0] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (2, 0). These cells are colored yellow in this grid. So R[2][0] = 3 + 4 = 7. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> grid = [[1]] <strong>Output:</strong> 0 <strong>Explanation:</strong> Since there are no other cells than (0, 0), R[0][0] is equal to 0. So the sum of R[i][j] over all cells would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 300</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>6</sup></code> or <code>grid[i][j] == -1</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Hash Table; Matrix
Go
func sumRemoteness(grid [][]int) (ans int64) { n := len(grid) cnt := 0 for _, row := range grid { for _, x := range row { if x > 0 { cnt++ } } } var dfs func(i, j int) (int, int) dfs = func(i, j int) (int, int) { s, t := grid[i][j], 1 grid[i][j] = 0 dirs := [5]int{-1, 0, 1, 0, -1} for k := 0; k < 4; k++ { x, y := i+dirs[k], j+dirs[k+1] if x >= 0 && x < n && y >= 0 && y < n && grid[x][y] > 0 { ss, tt := dfs(x, y) s += ss t += tt } } return s, t } for i := range grid { for j := range grid[i] { if grid[i][j] > 0 { s, t := dfs(i, j) ans += int64(cnt-t) * int64(s) } } } return }
2,852
Sum of Remoteness of All Cells
Medium
<p>You are given a <strong>0-indexed</strong> matrix <code>grid</code> of order <code>n * n</code>. Each cell in this matrix has a value <code>grid[i][j]</code>, which is either a <strong>positive</strong> integer or <code>-1</code> representing a blocked cell.</p> <p>You can move from a non-blocked cell to any non-blocked cell that shares an edge.</p> <p>For any cell <code>(i, j)</code>, we represent its <strong>remoteness</strong> as <code>R[i][j]</code> which is defined as the following:</p> <ul> <li>If the cell <code>(i, j)</code> is a <strong>non-blocked</strong> cell, <code>R[i][j]</code> is the sum of the values <code>grid[x][y]</code> such that there is <strong>no path</strong> from the <strong>non-blocked</strong> cell <code>(x, y)</code> to the cell <code>(i, j)</code>.</li> <li>For blocked cells, <code>R[i][j] == 0</code>.</li> </ul> <p>Return<em> the sum of </em><code>R[i][j]</code><em> over all cells.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2852.Sum%20of%20Remoteness%20of%20All%20Cells/images/1-new.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 400px; height: 304px;" /></p> <pre> <strong>Input:</strong> grid = [[-1,1,-1],[5,-1,4],[-1,3,-1]] <strong>Output:</strong> 39 <strong>Explanation:</strong> In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 0 + 12 + 0 + 8 + 0 + 9 + 0 + 10 + 0 = 39. Let&#39;s jump on the bottom-left grid in the above picture and calculate R[0][1] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (0, 1). These cells are colored yellow in this grid. So R[0][1] = 5 + 4 + 3 = 12. Now let&#39;s jump on the bottom-right grid in the above picture and calculate R[1][2] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (1, 2). These cells are colored yellow in this grid. So R[1][2] = 1 + 5 + 3 = 9. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2852.Sum%20of%20Remoteness%20of%20All%20Cells/images/2.png" style="width: 400px; height: 302px; background: #fff; border-radius: .5rem;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[-1,3,4],[-1,-1,-1],[3,-1,-1]] <strong>Output:</strong> 13 <strong>Explanation:</strong> In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 3 + 3 + 0 + 0 + 0 + 0 + 7 + 0 + 0 = 13. Let&#39;s jump on the bottom-left grid in the above picture and calculate R[0][2] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (0, 2). This cell is colored yellow in this grid. So R[0][2] = 3. Now let&#39;s jump on the bottom-right grid in the above picture and calculate R[2][0] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (2, 0). These cells are colored yellow in this grid. So R[2][0] = 3 + 4 = 7. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> grid = [[1]] <strong>Output:</strong> 0 <strong>Explanation:</strong> Since there are no other cells than (0, 0), R[0][0] is equal to 0. So the sum of R[i][j] over all cells would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 300</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>6</sup></code> or <code>grid[i][j] == -1</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Hash Table; Matrix
Java
class Solution { private int n; private int[][] grid; private final int[] dirs = {-1, 0, 1, 0, -1}; public long sumRemoteness(int[][] grid) { n = grid.length; this.grid = grid; int cnt = 0; for (int[] row : grid) { for (int x : row) { if (x > 0) { ++cnt; } } } long ans = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] > 0) { long[] res = dfs(i, j); ans += (cnt - res[1]) * res[0]; } } } return ans; } private long[] dfs(int i, int j) { long[] res = new long[2]; res[0] = grid[i][j]; res[1] = 1; grid[i][j] = 0; for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] > 0) { long[] tmp = dfs(x, y); res[0] += tmp[0]; res[1] += tmp[1]; } } return res; } }
2,852
Sum of Remoteness of All Cells
Medium
<p>You are given a <strong>0-indexed</strong> matrix <code>grid</code> of order <code>n * n</code>. Each cell in this matrix has a value <code>grid[i][j]</code>, which is either a <strong>positive</strong> integer or <code>-1</code> representing a blocked cell.</p> <p>You can move from a non-blocked cell to any non-blocked cell that shares an edge.</p> <p>For any cell <code>(i, j)</code>, we represent its <strong>remoteness</strong> as <code>R[i][j]</code> which is defined as the following:</p> <ul> <li>If the cell <code>(i, j)</code> is a <strong>non-blocked</strong> cell, <code>R[i][j]</code> is the sum of the values <code>grid[x][y]</code> such that there is <strong>no path</strong> from the <strong>non-blocked</strong> cell <code>(x, y)</code> to the cell <code>(i, j)</code>.</li> <li>For blocked cells, <code>R[i][j] == 0</code>.</li> </ul> <p>Return<em> the sum of </em><code>R[i][j]</code><em> over all cells.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2852.Sum%20of%20Remoteness%20of%20All%20Cells/images/1-new.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 400px; height: 304px;" /></p> <pre> <strong>Input:</strong> grid = [[-1,1,-1],[5,-1,4],[-1,3,-1]] <strong>Output:</strong> 39 <strong>Explanation:</strong> In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 0 + 12 + 0 + 8 + 0 + 9 + 0 + 10 + 0 = 39. Let&#39;s jump on the bottom-left grid in the above picture and calculate R[0][1] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (0, 1). These cells are colored yellow in this grid. So R[0][1] = 5 + 4 + 3 = 12. Now let&#39;s jump on the bottom-right grid in the above picture and calculate R[1][2] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (1, 2). These cells are colored yellow in this grid. So R[1][2] = 1 + 5 + 3 = 9. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2852.Sum%20of%20Remoteness%20of%20All%20Cells/images/2.png" style="width: 400px; height: 302px; background: #fff; border-radius: .5rem;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[-1,3,4],[-1,-1,-1],[3,-1,-1]] <strong>Output:</strong> 13 <strong>Explanation:</strong> In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 3 + 3 + 0 + 0 + 0 + 0 + 7 + 0 + 0 = 13. Let&#39;s jump on the bottom-left grid in the above picture and calculate R[0][2] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (0, 2). This cell is colored yellow in this grid. So R[0][2] = 3. Now let&#39;s jump on the bottom-right grid in the above picture and calculate R[2][0] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (2, 0). These cells are colored yellow in this grid. So R[2][0] = 3 + 4 = 7. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> grid = [[1]] <strong>Output:</strong> 0 <strong>Explanation:</strong> Since there are no other cells than (0, 0), R[0][0] is equal to 0. So the sum of R[i][j] over all cells would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 300</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>6</sup></code> or <code>grid[i][j] == -1</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Hash Table; Matrix
Python
class Solution: def sumRemoteness(self, grid: List[List[int]]) -> int: def dfs(i: int, j: int) -> (int, int): s, t = grid[i][j], 1 grid[i][j] = 0 for a, b in pairwise(dirs): x, y = i + a, j + b if 0 <= x < n and 0 <= y < n and grid[x][y] > 0: s1, t1 = dfs(x, y) s, t = s + s1, t + t1 return s, t n = len(grid) dirs = (-1, 0, 1, 0, -1) cnt = sum(x > 0 for row in grid for x in row) ans = 0 for i, row in enumerate(grid): for j, x in enumerate(row): if x > 0: s, t = dfs(i, j) ans += (cnt - t) * s return ans
2,852
Sum of Remoteness of All Cells
Medium
<p>You are given a <strong>0-indexed</strong> matrix <code>grid</code> of order <code>n * n</code>. Each cell in this matrix has a value <code>grid[i][j]</code>, which is either a <strong>positive</strong> integer or <code>-1</code> representing a blocked cell.</p> <p>You can move from a non-blocked cell to any non-blocked cell that shares an edge.</p> <p>For any cell <code>(i, j)</code>, we represent its <strong>remoteness</strong> as <code>R[i][j]</code> which is defined as the following:</p> <ul> <li>If the cell <code>(i, j)</code> is a <strong>non-blocked</strong> cell, <code>R[i][j]</code> is the sum of the values <code>grid[x][y]</code> such that there is <strong>no path</strong> from the <strong>non-blocked</strong> cell <code>(x, y)</code> to the cell <code>(i, j)</code>.</li> <li>For blocked cells, <code>R[i][j] == 0</code>.</li> </ul> <p>Return<em> the sum of </em><code>R[i][j]</code><em> over all cells.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2852.Sum%20of%20Remoteness%20of%20All%20Cells/images/1-new.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 400px; height: 304px;" /></p> <pre> <strong>Input:</strong> grid = [[-1,1,-1],[5,-1,4],[-1,3,-1]] <strong>Output:</strong> 39 <strong>Explanation:</strong> In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 0 + 12 + 0 + 8 + 0 + 9 + 0 + 10 + 0 = 39. Let&#39;s jump on the bottom-left grid in the above picture and calculate R[0][1] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (0, 1). These cells are colored yellow in this grid. So R[0][1] = 5 + 4 + 3 = 12. Now let&#39;s jump on the bottom-right grid in the above picture and calculate R[1][2] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (1, 2). These cells are colored yellow in this grid. So R[1][2] = 1 + 5 + 3 = 9. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2852.Sum%20of%20Remoteness%20of%20All%20Cells/images/2.png" style="width: 400px; height: 302px; background: #fff; border-radius: .5rem;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> grid = [[-1,3,4],[-1,-1,-1],[3,-1,-1]] <strong>Output:</strong> 13 <strong>Explanation:</strong> In the picture above, there are four grids. The top-left grid contains the initial values in the grid. Blocked cells are colored black, and other cells get their values as it is in the input. In the top-right grid, you can see the value of R[i][j] for all cells. So the answer would be the sum of them. That is: 3 + 3 + 0 + 0 + 0 + 0 + 7 + 0 + 0 = 13. Let&#39;s jump on the bottom-left grid in the above picture and calculate R[0][2] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (0, 2). This cell is colored yellow in this grid. So R[0][2] = 3. Now let&#39;s jump on the bottom-right grid in the above picture and calculate R[2][0] (the target cell is colored green). We should sum up the value of cells that can&#39;t be reached by the cell (2, 0). These cells are colored yellow in this grid. So R[2][0] = 3 + 4 = 7. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> grid = [[1]] <strong>Output:</strong> 0 <strong>Explanation:</strong> Since there are no other cells than (0, 0), R[0][0] is equal to 0. So the sum of R[i][j] over all cells would be 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 300</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>6</sup></code> or <code>grid[i][j] == -1</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Hash Table; Matrix
TypeScript
function sumRemoteness(grid: number[][]): number { const n = grid.length; let cnt = 0; for (const row of grid) { for (const x of row) { if (x > 0) { cnt++; } } } const dirs = [-1, 0, 1, 0, -1]; const dfs = (i: number, j: number): [number, number] => { let s = grid[i][j]; let t = 1; grid[i][j] = 0; for (let k = 0; k < 4; ++k) { const [x, y] = [i + dirs[k], j + dirs[k + 1]]; if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] > 0) { const [ss, tt] = dfs(x, y); s += ss; t += tt; } } return [s, t]; }; let ans = 0; for (let i = 0; i < n; ++i) { for (let j = 0; j < n; ++j) { if (grid[i][j] > 0) { const [s, t] = dfs(i, j); ans += (cnt - t) * s; } } } return ans; }
2,853
Highest Salaries Difference
Easy
<p>Table: <code><font face="monospace">Salaries</font></code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | emp_name | varchar | | department | varchar | | salary | int | +-------------+---------+ (emp_name, department) is the primary key (combination of unique values) for this table. Each row of this table contains emp_name, department and salary. There will be <strong>at least one</strong> entry for the engineering and marketing departments. </pre> <p>Write a solution&nbsp;to calculate the difference between the <strong>highest</strong> salaries in the <strong>marketing</strong> and <strong>engineering</strong> <code>department</code>. Output the absolute difference in salaries.</p> <p>Return<em> the result table.</em></p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Salaries table: +----------+-------------+--------+ | emp_name | department | salary | +----------+-------------+--------+ | Kathy | Engineering | 50000 | | Roy | Marketing | 30000 | | Charles | Engineering | 45000 | | Jack | Engineering | 85000 | | Benjamin | Marketing | 34000 | | Anthony | Marketing | 42000 | | Edward | Engineering | 102000 | | Terry | Engineering | 44000 | | Evelyn | Marketing | 53000 | | Arthur | Engineering | 32000 | +----------+-------------+--------+ <strong>Output:</strong> +-------------------+ | salary_difference | +-------------------+ | 49000 | +-------------------+ <strong>Explanation:</strong> - The Engineering and Marketing departments have the highest salaries of 102,000 and 53,000, respectively. Resulting in an absolute difference of 49,000. </pre>
Database
SQL
# Write your MySQL query statement below SELECT MAX(s) - MIN(s) AS salary_difference FROM ( SELECT MAX(salary) AS s FROM Salaries GROUP BY department ) AS t;
2,854
Rolling Average Steps
Medium
<p>Table: <code><font face="monospace">Steps</font></code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | user_id | int | | steps_count | int | | steps_date | date | +-------------+------+ (user_id, steps_date) is the primary key for this table. Each row of this table contains user_id, steps_count, and steps_date. </pre> <p>Write a solution to calculate <code>3-day</code> <strong>rolling averages</strong> of steps for each user.</p> <p>We calculate the <code>n-day</code> <strong>rolling average</strong> this way:</p> <ul> <li>For each day, we calculate the average of <code>n</code> consecutive days of step counts ending on that day if available, otherwise, <code>n-day</code> rolling average is not defined for it.</li> </ul> <p>Output the <code>user_id</code>, <code>steps_date</code>, and rolling average. Round the rolling average to <strong>two decimal places</strong>.</p> <p>Return<em> the result table ordered by </em><code>user_id</code><em>, </em><code>steps_date</code><em> in <strong>ascending</strong> order.</em></p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Steps table: +---------+-------------+------------+ | user_id | steps_count | steps_date | +---------+-------------+------------+ | 1 | 687 | 2021-09-02 | | 1 | 395 | 2021-09-04 | | 1 | 499 | 2021-09-05 | | 1 | 712 | 2021-09-06 | | 1 | 576 | 2021-09-07 | | 2 | 153 | 2021-09-06 | | 2 | 171 | 2021-09-07 | | 2 | 530 | 2021-09-08 | | 3 | 945 | 2021-09-04 | | 3 | 120 | 2021-09-07 | | 3 | 557 | 2021-09-08 | | 3 | 840 | 2021-09-09 | | 3 | 627 | 2021-09-10 | | 5 | 382 | 2021-09-05 | | 6 | 480 | 2021-09-01 | | 6 | 191 | 2021-09-02 | | 6 | 303 | 2021-09-05 | +---------+-------------+------------+ <strong>Output:</strong> +---------+------------+-----------------+ | user_id | steps_date | rolling_average | +---------+------------+-----------------+ | 1 | 2021-09-06 | 535.33 | | 1 | 2021-09-07 | 595.67 | | 2 | 2021-09-08 | 284.67 | | 3 | 2021-09-09 | 505.67 | | 3 | 2021-09-10 | 674.67 | +---------+------------+-----------------+ <strong>Explanation:</strong> - For user id 1, the step counts for the three consecutive days up to 2021-09-06 are available. Consequently, the rolling average for this particular date is computed as (395 + 499 + 712) / 3 = 535.33. - For user id 1, the step counts for the three consecutive days up to 2021-09-07 are available. Consequently, the rolling average for this particular date is computed as (499 + 712 + 576) / 3 = 595.67. - For user id 2, the step counts for the three consecutive days up to 2021-09-08 are available. Consequently, the rolling average for this particular date is computed as (153 + 171 + 530) / 3 = 284.67. - For user id 3, the step counts for the three consecutive days up to 2021-09-09 are available. Consequently, the rolling average for this particular date is computed as (120 + 557 + 840) / 3 = 505.67. - For user id 3, the step counts for the three consecutive days up to 2021-09-10 are available. Consequently, the rolling average for this particular date is computed as (557 + 840 + 627) / 3 = 674.67. - For user id 4 and 5, the calculation of the rolling average is not viable as there is insufficient data for the consecutive three days. Output table ordered by user_id and steps_date in ascending order.</pre>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT user_id, steps_date, ROUND( AVG(steps_count) OVER ( PARTITION BY user_id ORDER BY steps_date ROWS 2 PRECEDING ), 2 ) AS rolling_average, DATEDIFF( steps_date, LAG(steps_date, 2) OVER ( PARTITION BY user_id ORDER BY steps_date ) ) = 2 AS st FROM Steps ) SELECT user_id, steps_date, rolling_average FROM T WHERE st = 1 ORDER BY 1, 2;
2,855
Minimum Right Shifts to Sort the Array
Easy
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of length <code>n</code> containing <strong>distinct</strong> positive integers. Return <em>the <strong>minimum</strong> number of <strong>right shifts</strong> required to sort </em><code>nums</code><em> and </em><code>-1</code><em> if this is not possible.</em></p> <p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,5,1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> After the first right shift, nums = [2,3,4,5,1]. After the second right shift, nums = [1,2,3,4,5]. Now nums is sorted; therefore the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5] <strong>Output:</strong> 0 <strong>Explanation:</strong> nums is already sorted therefore, the answer is 0.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4] <strong>Output:</strong> -1 <strong>Explanation:</strong> It&#39;s impossible to sort the array using right shifts. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> contains distinct integers.</li> </ul>
Array
C++
class Solution { public: int minimumRightShifts(vector<int>& nums) { int n = nums.size(); int i = 1; while (i < n && nums[i - 1] < nums[i]) { ++i; } int k = i + 1; while (k < n && nums[k - 1] < nums[k] && nums[k] < nums[0]) { ++k; } return k < n ? -1 : n - i; } };
2,855
Minimum Right Shifts to Sort the Array
Easy
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of length <code>n</code> containing <strong>distinct</strong> positive integers. Return <em>the <strong>minimum</strong> number of <strong>right shifts</strong> required to sort </em><code>nums</code><em> and </em><code>-1</code><em> if this is not possible.</em></p> <p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,5,1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> After the first right shift, nums = [2,3,4,5,1]. After the second right shift, nums = [1,2,3,4,5]. Now nums is sorted; therefore the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5] <strong>Output:</strong> 0 <strong>Explanation:</strong> nums is already sorted therefore, the answer is 0.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4] <strong>Output:</strong> -1 <strong>Explanation:</strong> It&#39;s impossible to sort the array using right shifts. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> contains distinct integers.</li> </ul>
Array
Go
func minimumRightShifts(nums []int) int { n := len(nums) i := 1 for i < n && nums[i-1] < nums[i] { i++ } k := i + 1 for k < n && nums[k-1] < nums[k] && nums[k] < nums[0] { k++ } if k < n { return -1 } return n - i }
2,855
Minimum Right Shifts to Sort the Array
Easy
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of length <code>n</code> containing <strong>distinct</strong> positive integers. Return <em>the <strong>minimum</strong> number of <strong>right shifts</strong> required to sort </em><code>nums</code><em> and </em><code>-1</code><em> if this is not possible.</em></p> <p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,5,1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> After the first right shift, nums = [2,3,4,5,1]. After the second right shift, nums = [1,2,3,4,5]. Now nums is sorted; therefore the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5] <strong>Output:</strong> 0 <strong>Explanation:</strong> nums is already sorted therefore, the answer is 0.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4] <strong>Output:</strong> -1 <strong>Explanation:</strong> It&#39;s impossible to sort the array using right shifts. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> contains distinct integers.</li> </ul>
Array
Java
class Solution { public int minimumRightShifts(List<Integer> nums) { int n = nums.size(); int i = 1; while (i < n && nums.get(i - 1) < nums.get(i)) { ++i; } int k = i + 1; while (k < n && nums.get(k - 1) < nums.get(k) && nums.get(k) < nums.get(0)) { ++k; } return k < n ? -1 : n - i; } }
2,855
Minimum Right Shifts to Sort the Array
Easy
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of length <code>n</code> containing <strong>distinct</strong> positive integers. Return <em>the <strong>minimum</strong> number of <strong>right shifts</strong> required to sort </em><code>nums</code><em> and </em><code>-1</code><em> if this is not possible.</em></p> <p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,5,1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> After the first right shift, nums = [2,3,4,5,1]. After the second right shift, nums = [1,2,3,4,5]. Now nums is sorted; therefore the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5] <strong>Output:</strong> 0 <strong>Explanation:</strong> nums is already sorted therefore, the answer is 0.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4] <strong>Output:</strong> -1 <strong>Explanation:</strong> It&#39;s impossible to sort the array using right shifts. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> contains distinct integers.</li> </ul>
Array
Python
class Solution: def minimumRightShifts(self, nums: List[int]) -> int: n = len(nums) i = 1 while i < n and nums[i - 1] < nums[i]: i += 1 k = i + 1 while k < n and nums[k - 1] < nums[k] < nums[0]: k += 1 return -1 if k < n else n - i
2,855
Minimum Right Shifts to Sort the Array
Easy
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of length <code>n</code> containing <strong>distinct</strong> positive integers. Return <em>the <strong>minimum</strong> number of <strong>right shifts</strong> required to sort </em><code>nums</code><em> and </em><code>-1</code><em> if this is not possible.</em></p> <p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,5,1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> After the first right shift, nums = [2,3,4,5,1]. After the second right shift, nums = [1,2,3,4,5]. Now nums is sorted; therefore the answer is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5] <strong>Output:</strong> 0 <strong>Explanation:</strong> nums is already sorted therefore, the answer is 0.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4] <strong>Output:</strong> -1 <strong>Explanation:</strong> It&#39;s impossible to sort the array using right shifts. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>nums</code> contains distinct integers.</li> </ul>
Array
TypeScript
function minimumRightShifts(nums: number[]): number { const n = nums.length; let i = 1; while (i < n && nums[i - 1] < nums[i]) { ++i; } let k = i + 1; while (k < n && nums[k - 1] < nums[k] && nums[k] < nums[0]) { ++k; } return k < n ? -1 : n - i; }
2,856
Minimum Array Length After Pair Removals
Medium
<p>Given an integer array <code>num</code> sorted in non-decreasing order.</p> <p>You can perform the following operation any number of times:</p> <ul> <li>Choose <strong>two</strong> indices, <code>i</code> and <code>j</code>, where <code>nums[i] &lt; nums[j]</code>.</li> <li>Then, remove the elements at indices <code>i</code> and <code>j</code> from <code>nums</code>. The remaining elements retain their original order, and the array is re-indexed.</li> </ul> <p>Return the <strong>minimum</strong> length of <code>nums</code> after applying the operation zero or more times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase1.gif" style="width: 160px; height: 70px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,2,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase2.gif" style="width: 240px; height: 70px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1000000000,1000000000]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Since both numbers are equal, they cannot be removed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase3.gif" style="width: 210px; height: 70px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Greedy; Array; Hash Table; Two Pointers; Binary Search; Counting
C++
class Solution { public: int minLengthAfterRemovals(vector<int>& nums) { unordered_map<int, int> cnt; for (int x : nums) { ++cnt[x]; } priority_queue<int> pq; for (auto& [_, v] : cnt) { pq.push(v); } int ans = nums.size(); while (pq.size() > 1) { int x = pq.top(); pq.pop(); int y = pq.top(); pq.pop(); x--; y--; if (x > 0) { pq.push(x); } if (y > 0) { pq.push(y); } ans -= 2; } return ans; } };
2,856
Minimum Array Length After Pair Removals
Medium
<p>Given an integer array <code>num</code> sorted in non-decreasing order.</p> <p>You can perform the following operation any number of times:</p> <ul> <li>Choose <strong>two</strong> indices, <code>i</code> and <code>j</code>, where <code>nums[i] &lt; nums[j]</code>.</li> <li>Then, remove the elements at indices <code>i</code> and <code>j</code> from <code>nums</code>. The remaining elements retain their original order, and the array is re-indexed.</li> </ul> <p>Return the <strong>minimum</strong> length of <code>nums</code> after applying the operation zero or more times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase1.gif" style="width: 160px; height: 70px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,2,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase2.gif" style="width: 240px; height: 70px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1000000000,1000000000]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Since both numbers are equal, they cannot be removed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase3.gif" style="width: 210px; height: 70px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Greedy; Array; Hash Table; Two Pointers; Binary Search; Counting
Go
func minLengthAfterRemovals(nums []int) int { cnt := map[int]int{} for _, x := range nums { cnt[x]++ } h := &hp{} for _, x := range cnt { h.push(x) } ans := len(nums) for h.Len() > 1 { x, y := h.pop(), h.pop() if x > 1 { h.push(x - 1) } if y > 1 { h.push(y - 1) } ans -= 2 } 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 } func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) }
2,856
Minimum Array Length After Pair Removals
Medium
<p>Given an integer array <code>num</code> sorted in non-decreasing order.</p> <p>You can perform the following operation any number of times:</p> <ul> <li>Choose <strong>two</strong> indices, <code>i</code> and <code>j</code>, where <code>nums[i] &lt; nums[j]</code>.</li> <li>Then, remove the elements at indices <code>i</code> and <code>j</code> from <code>nums</code>. The remaining elements retain their original order, and the array is re-indexed.</li> </ul> <p>Return the <strong>minimum</strong> length of <code>nums</code> after applying the operation zero or more times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase1.gif" style="width: 160px; height: 70px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,2,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase2.gif" style="width: 240px; height: 70px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1000000000,1000000000]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Since both numbers are equal, they cannot be removed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase3.gif" style="width: 210px; height: 70px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Greedy; Array; Hash Table; Two Pointers; Binary Search; Counting
Java
class Solution { public int minLengthAfterRemovals(List<Integer> nums) { Map<Integer, Integer> cnt = new HashMap<>(); for (int x : nums) { cnt.merge(x, 1, Integer::sum); } PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder()); for (int x : cnt.values()) { pq.offer(x); } int ans = nums.size(); while (pq.size() > 1) { int x = pq.poll(); int y = pq.poll(); x--; y--; if (x > 0) { pq.offer(x); } if (y > 0) { pq.offer(y); } ans -= 2; } return ans; } }
2,856
Minimum Array Length After Pair Removals
Medium
<p>Given an integer array <code>num</code> sorted in non-decreasing order.</p> <p>You can perform the following operation any number of times:</p> <ul> <li>Choose <strong>two</strong> indices, <code>i</code> and <code>j</code>, where <code>nums[i] &lt; nums[j]</code>.</li> <li>Then, remove the elements at indices <code>i</code> and <code>j</code> from <code>nums</code>. The remaining elements retain their original order, and the array is re-indexed.</li> </ul> <p>Return the <strong>minimum</strong> length of <code>nums</code> after applying the operation zero or more times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase1.gif" style="width: 160px; height: 70px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,2,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase2.gif" style="width: 240px; height: 70px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1000000000,1000000000]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Since both numbers are equal, they cannot be removed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase3.gif" style="width: 210px; height: 70px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Greedy; Array; Hash Table; Two Pointers; Binary Search; Counting
Python
class Solution: def minLengthAfterRemovals(self, nums: List[int]) -> int: cnt = Counter(nums) pq = [-x for x in cnt.values()] heapify(pq) ans = len(nums) while len(pq) > 1: x, y = -heappop(pq), -heappop(pq) x -= 1 y -= 1 if x > 0: heappush(pq, -x) if y > 0: heappush(pq, -y) ans -= 2 return ans
2,856
Minimum Array Length After Pair Removals
Medium
<p>Given an integer array <code>num</code> sorted in non-decreasing order.</p> <p>You can perform the following operation any number of times:</p> <ul> <li>Choose <strong>two</strong> indices, <code>i</code> and <code>j</code>, where <code>nums[i] &lt; nums[j]</code>.</li> <li>Then, remove the elements at indices <code>i</code> and <code>j</code> from <code>nums</code>. The remaining elements retain their original order, and the array is re-indexed.</li> </ul> <p>Return the <strong>minimum</strong> length of <code>nums</code> after applying the operation zero or more times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase1.gif" style="width: 160px; height: 70px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,2,2,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase2.gif" style="width: 240px; height: 70px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1000000000,1000000000]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Since both numbers are equal, they cannot be removed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2856.Minimum%20Array%20Length%20After%20Pair%20Removals/images/tcase3.gif" style="width: 210px; height: 70px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> </ul>
Greedy; Array; Hash Table; Two Pointers; Binary Search; Counting
TypeScript
function minLengthAfterRemovals(nums: number[]): number { const cnt: Map<number, number> = new Map(); for (const x of nums) { cnt.set(x, (cnt.get(x) ?? 0) + 1); } const pq = new MaxPriorityQueue<number>(); for (const [_, v] of cnt) { pq.enqueue(v); } let ans = nums.length; while (pq.size() > 1) { let x = pq.dequeue(); let y = pq.dequeue(); if (--x > 0) { pq.enqueue(x); } if (--y > 0) { pq.enqueue(y); } ans -= 2; } return ans; }
2,857
Count Pairs of Points With Distance k
Medium
<p>You are given a <strong>2D</strong> integer array <code>coordinates</code> and an integer <code>k</code>, where <code>coordinates[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> are the coordinates of the <code>i<sup>th</sup></code> point in a 2D plane.</p> <p>We define the <strong>distance</strong> between two points <code>(x<sub>1</sub>, y<sub>1</sub>)</code> and <code>(x<sub>2</sub>, y<sub>2</sub>)</code> as <code>(x1 XOR x2) + (y1 XOR y2)</code> where <code>XOR</code> is the bitwise <code>XOR</code> operation.</p> <p>Return <em>the number of pairs </em><code>(i, j)</code><em> such that </em><code>i &lt; j</code><em> and the distance between points </em><code>i</code><em> and </em><code>j</code><em> is equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> coordinates = [[1,2],[4,2],[1,3],[5,2]], k = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> We can choose the following pairs: - (0,1): Because we have (1 XOR 4) + (2 XOR 2) = 5. - (2,3): Because we have (1 XOR 5) + (3 XOR 2) = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> coordinates = [[1,3],[1,3],[1,3],[1,3],[1,3]], k = 0 <strong>Output:</strong> 10 <strong>Explanation:</strong> Any two chosen pairs will have a distance of 0. There are 10 ways to choose two pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= coordinates.length &lt;= 50000</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= k &lt;= 100</code></li> </ul>
Bit Manipulation; Array; Hash Table
C++
class Solution { public: int countPairs(vector<vector<int>>& coordinates, int k) { map<pair<int, int>, int> cnt; int ans = 0; for (auto& c : coordinates) { int x2 = c[0], y2 = c[1]; for (int a = 0; a <= k; ++a) { int b = k - a; int x1 = a ^ x2, y1 = b ^ y2; ans += cnt[{x1, y1}]; } ++cnt[{x2, y2}]; } return ans; } };
2,857
Count Pairs of Points With Distance k
Medium
<p>You are given a <strong>2D</strong> integer array <code>coordinates</code> and an integer <code>k</code>, where <code>coordinates[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> are the coordinates of the <code>i<sup>th</sup></code> point in a 2D plane.</p> <p>We define the <strong>distance</strong> between two points <code>(x<sub>1</sub>, y<sub>1</sub>)</code> and <code>(x<sub>2</sub>, y<sub>2</sub>)</code> as <code>(x1 XOR x2) + (y1 XOR y2)</code> where <code>XOR</code> is the bitwise <code>XOR</code> operation.</p> <p>Return <em>the number of pairs </em><code>(i, j)</code><em> such that </em><code>i &lt; j</code><em> and the distance between points </em><code>i</code><em> and </em><code>j</code><em> is equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> coordinates = [[1,2],[4,2],[1,3],[5,2]], k = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> We can choose the following pairs: - (0,1): Because we have (1 XOR 4) + (2 XOR 2) = 5. - (2,3): Because we have (1 XOR 5) + (3 XOR 2) = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> coordinates = [[1,3],[1,3],[1,3],[1,3],[1,3]], k = 0 <strong>Output:</strong> 10 <strong>Explanation:</strong> Any two chosen pairs will have a distance of 0. There are 10 ways to choose two pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= coordinates.length &lt;= 50000</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= k &lt;= 100</code></li> </ul>
Bit Manipulation; Array; Hash Table
Go
func countPairs(coordinates [][]int, k int) (ans int) { cnt := map[[2]int]int{} for _, c := range coordinates { x2, y2 := c[0], c[1] for a := 0; a <= k; a++ { b := k - a x1, y1 := a^x2, b^y2 ans += cnt[[2]int{x1, y1}] } cnt[[2]int{x2, y2}]++ } return }
2,857
Count Pairs of Points With Distance k
Medium
<p>You are given a <strong>2D</strong> integer array <code>coordinates</code> and an integer <code>k</code>, where <code>coordinates[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> are the coordinates of the <code>i<sup>th</sup></code> point in a 2D plane.</p> <p>We define the <strong>distance</strong> between two points <code>(x<sub>1</sub>, y<sub>1</sub>)</code> and <code>(x<sub>2</sub>, y<sub>2</sub>)</code> as <code>(x1 XOR x2) + (y1 XOR y2)</code> where <code>XOR</code> is the bitwise <code>XOR</code> operation.</p> <p>Return <em>the number of pairs </em><code>(i, j)</code><em> such that </em><code>i &lt; j</code><em> and the distance between points </em><code>i</code><em> and </em><code>j</code><em> is equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> coordinates = [[1,2],[4,2],[1,3],[5,2]], k = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> We can choose the following pairs: - (0,1): Because we have (1 XOR 4) + (2 XOR 2) = 5. - (2,3): Because we have (1 XOR 5) + (3 XOR 2) = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> coordinates = [[1,3],[1,3],[1,3],[1,3],[1,3]], k = 0 <strong>Output:</strong> 10 <strong>Explanation:</strong> Any two chosen pairs will have a distance of 0. There are 10 ways to choose two pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= coordinates.length &lt;= 50000</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= k &lt;= 100</code></li> </ul>
Bit Manipulation; Array; Hash Table
Java
class Solution { public int countPairs(List<List<Integer>> coordinates, int k) { Map<List<Integer>, Integer> cnt = new HashMap<>(); int ans = 0; for (var c : coordinates) { int x2 = c.get(0), y2 = c.get(1); for (int a = 0; a <= k; ++a) { int b = k - a; int x1 = a ^ x2, y1 = b ^ y2; ans += cnt.getOrDefault(List.of(x1, y1), 0); } cnt.merge(c, 1, Integer::sum); } return ans; } }
2,857
Count Pairs of Points With Distance k
Medium
<p>You are given a <strong>2D</strong> integer array <code>coordinates</code> and an integer <code>k</code>, where <code>coordinates[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> are the coordinates of the <code>i<sup>th</sup></code> point in a 2D plane.</p> <p>We define the <strong>distance</strong> between two points <code>(x<sub>1</sub>, y<sub>1</sub>)</code> and <code>(x<sub>2</sub>, y<sub>2</sub>)</code> as <code>(x1 XOR x2) + (y1 XOR y2)</code> where <code>XOR</code> is the bitwise <code>XOR</code> operation.</p> <p>Return <em>the number of pairs </em><code>(i, j)</code><em> such that </em><code>i &lt; j</code><em> and the distance between points </em><code>i</code><em> and </em><code>j</code><em> is equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> coordinates = [[1,2],[4,2],[1,3],[5,2]], k = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> We can choose the following pairs: - (0,1): Because we have (1 XOR 4) + (2 XOR 2) = 5. - (2,3): Because we have (1 XOR 5) + (3 XOR 2) = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> coordinates = [[1,3],[1,3],[1,3],[1,3],[1,3]], k = 0 <strong>Output:</strong> 10 <strong>Explanation:</strong> Any two chosen pairs will have a distance of 0. There are 10 ways to choose two pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= coordinates.length &lt;= 50000</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= k &lt;= 100</code></li> </ul>
Bit Manipulation; Array; Hash Table
Python
class Solution: def countPairs(self, coordinates: List[List[int]], k: int) -> int: cnt = Counter() ans = 0 for x2, y2 in coordinates: for a in range(k + 1): b = k - a x1, y1 = a ^ x2, b ^ y2 ans += cnt[(x1, y1)] cnt[(x2, y2)] += 1 return ans
2,857
Count Pairs of Points With Distance k
Medium
<p>You are given a <strong>2D</strong> integer array <code>coordinates</code> and an integer <code>k</code>, where <code>coordinates[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> are the coordinates of the <code>i<sup>th</sup></code> point in a 2D plane.</p> <p>We define the <strong>distance</strong> between two points <code>(x<sub>1</sub>, y<sub>1</sub>)</code> and <code>(x<sub>2</sub>, y<sub>2</sub>)</code> as <code>(x1 XOR x2) + (y1 XOR y2)</code> where <code>XOR</code> is the bitwise <code>XOR</code> operation.</p> <p>Return <em>the number of pairs </em><code>(i, j)</code><em> such that </em><code>i &lt; j</code><em> and the distance between points </em><code>i</code><em> and </em><code>j</code><em> is equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> coordinates = [[1,2],[4,2],[1,3],[5,2]], k = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> We can choose the following pairs: - (0,1): Because we have (1 XOR 4) + (2 XOR 2) = 5. - (2,3): Because we have (1 XOR 5) + (3 XOR 2) = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> coordinates = [[1,3],[1,3],[1,3],[1,3],[1,3]], k = 0 <strong>Output:</strong> 10 <strong>Explanation:</strong> Any two chosen pairs will have a distance of 0. There are 10 ways to choose two pairs. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= coordinates.length &lt;= 50000</code></li> <li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= k &lt;= 100</code></li> </ul>
Bit Manipulation; Array; Hash Table
TypeScript
function countPairs(coordinates: number[][], k: number): number { const cnt: Map<number, number> = new Map(); const f = (x: number, y: number): number => x * 1000000 + y; let ans = 0; for (const [x2, y2] of coordinates) { for (let a = 0; a <= k; ++a) { const b = k - a; const [x1, y1] = [a ^ x2, b ^ y2]; ans += cnt.get(f(x1, y1)) ?? 0; } cnt.set(f(x2, y2), (cnt.get(f(x2, y2)) ?? 0) + 1); } return ans; }
2,858
Minimum Edge Reversals So Every Node Is Reachable
Hard
<p>There is a <strong>simple directed graph</strong> with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. The graph would form a <strong>tree</strong> if its edges were bi-directional.</p> <p>You are given an integer <code>n</code> and a <strong>2D</strong> integer array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> represents a <strong>directed edge</strong> going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code>.</p> <p>An <strong>edge reversal</strong> changes the direction of an edge, i.e., a directed edge going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code> becomes a directed edge going from node <code>v<sub>i</sub></code> to node <code>u<sub>i</sub></code>.</p> <p>For every node <code>i</code> in the range <code>[0, n - 1]</code>, your task is to <strong>independently</strong> calculate the <strong>minimum</strong> number of <strong>edge reversals</strong> required so it is possible to reach any other node starting from node <code>i</code> through a <strong>sequence</strong> of <strong>directed edges</strong>.</p> <p>Return <em>an integer array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> is the</em><em> </em> <em><strong>minimum</strong> number of <strong>edge reversals</strong> required so it is possible to reach any other node starting from node </em><code>i</code><em> through a <strong>sequence</strong> of <strong>directed edges</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img height="246" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2858.Minimum%20Edge%20Reversals%20So%20Every%20Node%20Is%20Reachable/images/image-20230826221104-3.png" width="312" /></p> <pre> <strong>Input:</strong> n = 4, edges = [[2,0],[2,1],[1,3]] <strong>Output:</strong> [1,1,0,2] <strong>Explanation:</strong> The image above shows the graph formed by the edges. For node 0: after reversing the edge [2,0], it is possible to reach any other node starting from node 0. So, answer[0] = 1. For node 1: after reversing the edge [2,1], it is possible to reach any other node starting from node 1. So, answer[1] = 1. For node 2: it is already possible to reach any other node starting from node 2. So, answer[2] = 0. For node 3: after reversing the edges [1,3] and [2,1], it is possible to reach any other node starting from node 3. So, answer[3] = 2. </pre> <p><strong class="example">Example 2:</strong></p> <p><img height="217" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2858.Minimum%20Edge%20Reversals%20So%20Every%20Node%20Is%20Reachable/images/image-20230826225541-2.png" width="322" /></p> <pre> <strong>Input:</strong> n = 3, edges = [[1,2],[2,0]] <strong>Output:</strong> [2,0,1] <strong>Explanation:</strong> The image above shows the graph formed by the edges. For node 0: after reversing the edges [2,0] and [1,2], it is possible to reach any other node starting from node 0. So, answer[0] = 2. For node 1: it is already possible to reach any other node starting from node 1. So, answer[1] = 0. For node 2: after reversing the edge [1, 2], it is possible to reach any other node starting from node 2. So, answer[2] = 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= u<sub>i</sub> == edges[i][0] &lt; n</code></li> <li><code>0 &lt;= v<sub>i</sub> == edges[i][1] &lt; n</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li>The input is generated such&nbsp;that if the edges were bi-directional, the graph would be a tree.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Dynamic Programming
C++
class Solution { public: vector<int> minEdgeReversals(int n, vector<vector<int>>& edges) { vector<pair<int, int>> g[n]; vector<int> ans(n); for (auto& e : edges) { int x = e[0], y = e[1]; g[x].emplace_back(y, 1); g[y].emplace_back(x, -1); } function<void(int, int)> dfs = [&](int i, int fa) { for (auto& [j, k] : g[i]) { if (j != fa) { ans[0] += k < 0; dfs(j, i); } } }; function<void(int, int)> dfs2 = [&](int i, int fa) { for (auto& [j, k] : g[i]) { if (j != fa) { ans[j] = ans[i] + k; dfs2(j, i); } } }; dfs(0, -1); dfs2(0, -1); return ans; } };
2,858
Minimum Edge Reversals So Every Node Is Reachable
Hard
<p>There is a <strong>simple directed graph</strong> with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. The graph would form a <strong>tree</strong> if its edges were bi-directional.</p> <p>You are given an integer <code>n</code> and a <strong>2D</strong> integer array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> represents a <strong>directed edge</strong> going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code>.</p> <p>An <strong>edge reversal</strong> changes the direction of an edge, i.e., a directed edge going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code> becomes a directed edge going from node <code>v<sub>i</sub></code> to node <code>u<sub>i</sub></code>.</p> <p>For every node <code>i</code> in the range <code>[0, n - 1]</code>, your task is to <strong>independently</strong> calculate the <strong>minimum</strong> number of <strong>edge reversals</strong> required so it is possible to reach any other node starting from node <code>i</code> through a <strong>sequence</strong> of <strong>directed edges</strong>.</p> <p>Return <em>an integer array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> is the</em><em> </em> <em><strong>minimum</strong> number of <strong>edge reversals</strong> required so it is possible to reach any other node starting from node </em><code>i</code><em> through a <strong>sequence</strong> of <strong>directed edges</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img height="246" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2858.Minimum%20Edge%20Reversals%20So%20Every%20Node%20Is%20Reachable/images/image-20230826221104-3.png" width="312" /></p> <pre> <strong>Input:</strong> n = 4, edges = [[2,0],[2,1],[1,3]] <strong>Output:</strong> [1,1,0,2] <strong>Explanation:</strong> The image above shows the graph formed by the edges. For node 0: after reversing the edge [2,0], it is possible to reach any other node starting from node 0. So, answer[0] = 1. For node 1: after reversing the edge [2,1], it is possible to reach any other node starting from node 1. So, answer[1] = 1. For node 2: it is already possible to reach any other node starting from node 2. So, answer[2] = 0. For node 3: after reversing the edges [1,3] and [2,1], it is possible to reach any other node starting from node 3. So, answer[3] = 2. </pre> <p><strong class="example">Example 2:</strong></p> <p><img height="217" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2858.Minimum%20Edge%20Reversals%20So%20Every%20Node%20Is%20Reachable/images/image-20230826225541-2.png" width="322" /></p> <pre> <strong>Input:</strong> n = 3, edges = [[1,2],[2,0]] <strong>Output:</strong> [2,0,1] <strong>Explanation:</strong> The image above shows the graph formed by the edges. For node 0: after reversing the edges [2,0] and [1,2], it is possible to reach any other node starting from node 0. So, answer[0] = 2. For node 1: it is already possible to reach any other node starting from node 1. So, answer[1] = 0. For node 2: after reversing the edge [1, 2], it is possible to reach any other node starting from node 2. So, answer[2] = 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= u<sub>i</sub> == edges[i][0] &lt; n</code></li> <li><code>0 &lt;= v<sub>i</sub> == edges[i][1] &lt; n</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li>The input is generated such&nbsp;that if the edges were bi-directional, the graph would be a tree.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Dynamic Programming
Go
func minEdgeReversals(n int, edges [][]int) []int { g := make([][][2]int, n) for _, e := range edges { x, y := e[0], e[1] g[x] = append(g[x], [2]int{y, 1}) g[y] = append(g[y], [2]int{x, -1}) } ans := make([]int, n) var dfs func(int, int) var dfs2 func(int, int) dfs = func(i, fa int) { for _, ne := range g[i] { j, k := ne[0], ne[1] if j != fa { if k < 0 { ans[0]++ } dfs(j, i) } } } dfs2 = func(i, fa int) { for _, ne := range g[i] { j, k := ne[0], ne[1] if j != fa { ans[j] = ans[i] + k dfs2(j, i) } } } dfs(0, -1) dfs2(0, -1) return ans }
2,858
Minimum Edge Reversals So Every Node Is Reachable
Hard
<p>There is a <strong>simple directed graph</strong> with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. The graph would form a <strong>tree</strong> if its edges were bi-directional.</p> <p>You are given an integer <code>n</code> and a <strong>2D</strong> integer array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> represents a <strong>directed edge</strong> going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code>.</p> <p>An <strong>edge reversal</strong> changes the direction of an edge, i.e., a directed edge going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code> becomes a directed edge going from node <code>v<sub>i</sub></code> to node <code>u<sub>i</sub></code>.</p> <p>For every node <code>i</code> in the range <code>[0, n - 1]</code>, your task is to <strong>independently</strong> calculate the <strong>minimum</strong> number of <strong>edge reversals</strong> required so it is possible to reach any other node starting from node <code>i</code> through a <strong>sequence</strong> of <strong>directed edges</strong>.</p> <p>Return <em>an integer array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> is the</em><em> </em> <em><strong>minimum</strong> number of <strong>edge reversals</strong> required so it is possible to reach any other node starting from node </em><code>i</code><em> through a <strong>sequence</strong> of <strong>directed edges</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img height="246" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2858.Minimum%20Edge%20Reversals%20So%20Every%20Node%20Is%20Reachable/images/image-20230826221104-3.png" width="312" /></p> <pre> <strong>Input:</strong> n = 4, edges = [[2,0],[2,1],[1,3]] <strong>Output:</strong> [1,1,0,2] <strong>Explanation:</strong> The image above shows the graph formed by the edges. For node 0: after reversing the edge [2,0], it is possible to reach any other node starting from node 0. So, answer[0] = 1. For node 1: after reversing the edge [2,1], it is possible to reach any other node starting from node 1. So, answer[1] = 1. For node 2: it is already possible to reach any other node starting from node 2. So, answer[2] = 0. For node 3: after reversing the edges [1,3] and [2,1], it is possible to reach any other node starting from node 3. So, answer[3] = 2. </pre> <p><strong class="example">Example 2:</strong></p> <p><img height="217" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2858.Minimum%20Edge%20Reversals%20So%20Every%20Node%20Is%20Reachable/images/image-20230826225541-2.png" width="322" /></p> <pre> <strong>Input:</strong> n = 3, edges = [[1,2],[2,0]] <strong>Output:</strong> [2,0,1] <strong>Explanation:</strong> The image above shows the graph formed by the edges. For node 0: after reversing the edges [2,0] and [1,2], it is possible to reach any other node starting from node 0. So, answer[0] = 2. For node 1: it is already possible to reach any other node starting from node 1. So, answer[1] = 0. For node 2: after reversing the edge [1, 2], it is possible to reach any other node starting from node 2. So, answer[2] = 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= u<sub>i</sub> == edges[i][0] &lt; n</code></li> <li><code>0 &lt;= v<sub>i</sub> == edges[i][1] &lt; n</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li>The input is generated such&nbsp;that if the edges were bi-directional, the graph would be a tree.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Dynamic Programming
Java
class Solution { private List<int[]>[] g; private int[] ans; public int[] minEdgeReversals(int n, int[][] edges) { ans = new int[n]; g = new List[n]; Arrays.setAll(g, i -> new ArrayList<>()); for (var e : edges) { int x = e[0], y = e[1]; g[x].add(new int[] {y, 1}); g[y].add(new int[] {x, -1}); } dfs(0, -1); dfs2(0, -1); return ans; } private void dfs(int i, int fa) { for (var ne : g[i]) { int j = ne[0], k = ne[1]; if (j != fa) { ans[0] += k < 0 ? 1 : 0; dfs(j, i); } } } private void dfs2(int i, int fa) { for (var ne : g[i]) { int j = ne[0], k = ne[1]; if (j != fa) { ans[j] = ans[i] + k; dfs2(j, i); } } } }
2,858
Minimum Edge Reversals So Every Node Is Reachable
Hard
<p>There is a <strong>simple directed graph</strong> with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. The graph would form a <strong>tree</strong> if its edges were bi-directional.</p> <p>You are given an integer <code>n</code> and a <strong>2D</strong> integer array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> represents a <strong>directed edge</strong> going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code>.</p> <p>An <strong>edge reversal</strong> changes the direction of an edge, i.e., a directed edge going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code> becomes a directed edge going from node <code>v<sub>i</sub></code> to node <code>u<sub>i</sub></code>.</p> <p>For every node <code>i</code> in the range <code>[0, n - 1]</code>, your task is to <strong>independently</strong> calculate the <strong>minimum</strong> number of <strong>edge reversals</strong> required so it is possible to reach any other node starting from node <code>i</code> through a <strong>sequence</strong> of <strong>directed edges</strong>.</p> <p>Return <em>an integer array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> is the</em><em> </em> <em><strong>minimum</strong> number of <strong>edge reversals</strong> required so it is possible to reach any other node starting from node </em><code>i</code><em> through a <strong>sequence</strong> of <strong>directed edges</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img height="246" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2858.Minimum%20Edge%20Reversals%20So%20Every%20Node%20Is%20Reachable/images/image-20230826221104-3.png" width="312" /></p> <pre> <strong>Input:</strong> n = 4, edges = [[2,0],[2,1],[1,3]] <strong>Output:</strong> [1,1,0,2] <strong>Explanation:</strong> The image above shows the graph formed by the edges. For node 0: after reversing the edge [2,0], it is possible to reach any other node starting from node 0. So, answer[0] = 1. For node 1: after reversing the edge [2,1], it is possible to reach any other node starting from node 1. So, answer[1] = 1. For node 2: it is already possible to reach any other node starting from node 2. So, answer[2] = 0. For node 3: after reversing the edges [1,3] and [2,1], it is possible to reach any other node starting from node 3. So, answer[3] = 2. </pre> <p><strong class="example">Example 2:</strong></p> <p><img height="217" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2858.Minimum%20Edge%20Reversals%20So%20Every%20Node%20Is%20Reachable/images/image-20230826225541-2.png" width="322" /></p> <pre> <strong>Input:</strong> n = 3, edges = [[1,2],[2,0]] <strong>Output:</strong> [2,0,1] <strong>Explanation:</strong> The image above shows the graph formed by the edges. For node 0: after reversing the edges [2,0] and [1,2], it is possible to reach any other node starting from node 0. So, answer[0] = 2. For node 1: it is already possible to reach any other node starting from node 1. So, answer[1] = 0. For node 2: after reversing the edge [1, 2], it is possible to reach any other node starting from node 2. So, answer[2] = 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= u<sub>i</sub> == edges[i][0] &lt; n</code></li> <li><code>0 &lt;= v<sub>i</sub> == edges[i][1] &lt; n</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li>The input is generated such&nbsp;that if the edges were bi-directional, the graph would be a tree.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Dynamic Programming
Python
class Solution: def minEdgeReversals(self, n: int, edges: List[List[int]]) -> List[int]: ans = [0] * n g = [[] for _ in range(n)] for x, y in edges: g[x].append((y, 1)) g[y].append((x, -1)) def dfs(i: int, fa: int): for j, k in g[i]: if j != fa: ans[0] += int(k < 0) dfs(j, i) dfs(0, -1) def dfs2(i: int, fa: int): for j, k in g[i]: if j != fa: ans[j] = ans[i] + k dfs2(j, i) dfs2(0, -1) return ans
2,858
Minimum Edge Reversals So Every Node Is Reachable
Hard
<p>There is a <strong>simple directed graph</strong> with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. The graph would form a <strong>tree</strong> if its edges were bi-directional.</p> <p>You are given an integer <code>n</code> and a <strong>2D</strong> integer array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> represents a <strong>directed edge</strong> going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code>.</p> <p>An <strong>edge reversal</strong> changes the direction of an edge, i.e., a directed edge going from node <code>u<sub>i</sub></code> to node <code>v<sub>i</sub></code> becomes a directed edge going from node <code>v<sub>i</sub></code> to node <code>u<sub>i</sub></code>.</p> <p>For every node <code>i</code> in the range <code>[0, n - 1]</code>, your task is to <strong>independently</strong> calculate the <strong>minimum</strong> number of <strong>edge reversals</strong> required so it is possible to reach any other node starting from node <code>i</code> through a <strong>sequence</strong> of <strong>directed edges</strong>.</p> <p>Return <em>an integer array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> is the</em><em> </em> <em><strong>minimum</strong> number of <strong>edge reversals</strong> required so it is possible to reach any other node starting from node </em><code>i</code><em> through a <strong>sequence</strong> of <strong>directed edges</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img height="246" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2858.Minimum%20Edge%20Reversals%20So%20Every%20Node%20Is%20Reachable/images/image-20230826221104-3.png" width="312" /></p> <pre> <strong>Input:</strong> n = 4, edges = [[2,0],[2,1],[1,3]] <strong>Output:</strong> [1,1,0,2] <strong>Explanation:</strong> The image above shows the graph formed by the edges. For node 0: after reversing the edge [2,0], it is possible to reach any other node starting from node 0. So, answer[0] = 1. For node 1: after reversing the edge [2,1], it is possible to reach any other node starting from node 1. So, answer[1] = 1. For node 2: it is already possible to reach any other node starting from node 2. So, answer[2] = 0. For node 3: after reversing the edges [1,3] and [2,1], it is possible to reach any other node starting from node 3. So, answer[3] = 2. </pre> <p><strong class="example">Example 2:</strong></p> <p><img height="217" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2858.Minimum%20Edge%20Reversals%20So%20Every%20Node%20Is%20Reachable/images/image-20230826225541-2.png" width="322" /></p> <pre> <strong>Input:</strong> n = 3, edges = [[1,2],[2,0]] <strong>Output:</strong> [2,0,1] <strong>Explanation:</strong> The image above shows the graph formed by the edges. For node 0: after reversing the edges [2,0] and [1,2], it is possible to reach any other node starting from node 0. So, answer[0] = 2. For node 1: it is already possible to reach any other node starting from node 1. So, answer[1] = 0. For node 2: after reversing the edge [1, 2], it is possible to reach any other node starting from node 2. So, answer[2] = 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= u<sub>i</sub> == edges[i][0] &lt; n</code></li> <li><code>0 &lt;= v<sub>i</sub> == edges[i][1] &lt; n</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li>The input is generated such&nbsp;that if the edges were bi-directional, the graph would be a tree.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Dynamic Programming
TypeScript
function minEdgeReversals(n: number, edges: number[][]): number[] { const g: number[][][] = Array.from({ length: n }, () => []); for (const [x, y] of edges) { g[x].push([y, 1]); g[y].push([x, -1]); } const ans: number[] = Array(n).fill(0); const dfs = (i: number, fa: number) => { for (const [j, k] of g[i]) { if (j !== fa) { ans[0] += k < 0 ? 1 : 0; dfs(j, i); } } }; const dfs2 = (i: number, fa: number) => { for (const [j, k] of g[i]) { if (j !== fa) { ans[j] = ans[i] + k; dfs2(j, i); } } }; dfs(0, -1); dfs2(0, -1); return ans; }
2,859
Sum of Values at Indices With K Set Bits
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>Return <em>an integer that denotes the <strong>sum</strong> of elements in </em><code>nums</code><em> whose corresponding <strong>indices</strong> have <strong>exactly</strong> </em><code>k</code><em> set bits in their binary representation.</em></p> <p>The <strong>set bits</strong> in an integer are the <code>1</code>&#39;s present when it is written in binary.</p> <ul> <li>For example, the binary representation of <code>21</code> is <code>10101</code>, which has <code>3</code> set bits.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,10,1,5,2], k = 1 <strong>Output:</strong> 13 <strong>Explanation:</strong> The binary representation of the indices are: 0 = 000<sub>2</sub> 1 = 001<sub>2</sub> 2 = 010<sub>2</sub> 3 = 011<sub>2</sub> 4 = 100<sub>2 </sub>Indices 1, 2, and 4 have k = 1 set bits in their binary representation. Hence, the answer is nums[1] + nums[2] + nums[4] = 13.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,1], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The binary representation of the indices are: 0 = 00<sub>2</sub> 1 = 01<sub>2</sub> 2 = 10<sub>2</sub> 3 = 11<sub>2 </sub>Only index 3 has k = 2 set bits in its binary representation. Hence, the answer is nums[3] = 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10</code></li> </ul>
Bit Manipulation; Array
C++
class Solution { public: int sumIndicesWithKSetBits(vector<int>& nums, int k) { int ans = 0; for (int i = 0; i < nums.size(); ++i) { if (__builtin_popcount(i) == k) { ans += nums[i]; } } return ans; } };
2,859
Sum of Values at Indices With K Set Bits
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>Return <em>an integer that denotes the <strong>sum</strong> of elements in </em><code>nums</code><em> whose corresponding <strong>indices</strong> have <strong>exactly</strong> </em><code>k</code><em> set bits in their binary representation.</em></p> <p>The <strong>set bits</strong> in an integer are the <code>1</code>&#39;s present when it is written in binary.</p> <ul> <li>For example, the binary representation of <code>21</code> is <code>10101</code>, which has <code>3</code> set bits.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,10,1,5,2], k = 1 <strong>Output:</strong> 13 <strong>Explanation:</strong> The binary representation of the indices are: 0 = 000<sub>2</sub> 1 = 001<sub>2</sub> 2 = 010<sub>2</sub> 3 = 011<sub>2</sub> 4 = 100<sub>2 </sub>Indices 1, 2, and 4 have k = 1 set bits in their binary representation. Hence, the answer is nums[1] + nums[2] + nums[4] = 13.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,1], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The binary representation of the indices are: 0 = 00<sub>2</sub> 1 = 01<sub>2</sub> 2 = 10<sub>2</sub> 3 = 11<sub>2 </sub>Only index 3 has k = 2 set bits in its binary representation. Hence, the answer is nums[3] = 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10</code></li> </ul>
Bit Manipulation; Array
Go
func sumIndicesWithKSetBits(nums []int, k int) (ans int) { for i, x := range nums { if bits.OnesCount(uint(i)) == k { ans += x } } return }
2,859
Sum of Values at Indices With K Set Bits
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>Return <em>an integer that denotes the <strong>sum</strong> of elements in </em><code>nums</code><em> whose corresponding <strong>indices</strong> have <strong>exactly</strong> </em><code>k</code><em> set bits in their binary representation.</em></p> <p>The <strong>set bits</strong> in an integer are the <code>1</code>&#39;s present when it is written in binary.</p> <ul> <li>For example, the binary representation of <code>21</code> is <code>10101</code>, which has <code>3</code> set bits.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,10,1,5,2], k = 1 <strong>Output:</strong> 13 <strong>Explanation:</strong> The binary representation of the indices are: 0 = 000<sub>2</sub> 1 = 001<sub>2</sub> 2 = 010<sub>2</sub> 3 = 011<sub>2</sub> 4 = 100<sub>2 </sub>Indices 1, 2, and 4 have k = 1 set bits in their binary representation. Hence, the answer is nums[1] + nums[2] + nums[4] = 13.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,1], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The binary representation of the indices are: 0 = 00<sub>2</sub> 1 = 01<sub>2</sub> 2 = 10<sub>2</sub> 3 = 11<sub>2 </sub>Only index 3 has k = 2 set bits in its binary representation. Hence, the answer is nums[3] = 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10</code></li> </ul>
Bit Manipulation; Array
Java
class Solution { public int sumIndicesWithKSetBits(List<Integer> nums, int k) { int ans = 0; for (int i = 0; i < nums.size(); i++) { if (Integer.bitCount(i) == k) { ans += nums.get(i); } } return ans; } }
2,859
Sum of Values at Indices With K Set Bits
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>Return <em>an integer that denotes the <strong>sum</strong> of elements in </em><code>nums</code><em> whose corresponding <strong>indices</strong> have <strong>exactly</strong> </em><code>k</code><em> set bits in their binary representation.</em></p> <p>The <strong>set bits</strong> in an integer are the <code>1</code>&#39;s present when it is written in binary.</p> <ul> <li>For example, the binary representation of <code>21</code> is <code>10101</code>, which has <code>3</code> set bits.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,10,1,5,2], k = 1 <strong>Output:</strong> 13 <strong>Explanation:</strong> The binary representation of the indices are: 0 = 000<sub>2</sub> 1 = 001<sub>2</sub> 2 = 010<sub>2</sub> 3 = 011<sub>2</sub> 4 = 100<sub>2 </sub>Indices 1, 2, and 4 have k = 1 set bits in their binary representation. Hence, the answer is nums[1] + nums[2] + nums[4] = 13.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,1], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The binary representation of the indices are: 0 = 00<sub>2</sub> 1 = 01<sub>2</sub> 2 = 10<sub>2</sub> 3 = 11<sub>2 </sub>Only index 3 has k = 2 set bits in its binary representation. Hence, the answer is nums[3] = 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10</code></li> </ul>
Bit Manipulation; Array
Python
class Solution: def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int: return sum(x for i, x in enumerate(nums) if i.bit_count() == k)
2,859
Sum of Values at Indices With K Set Bits
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p> <p>Return <em>an integer that denotes the <strong>sum</strong> of elements in </em><code>nums</code><em> whose corresponding <strong>indices</strong> have <strong>exactly</strong> </em><code>k</code><em> set bits in their binary representation.</em></p> <p>The <strong>set bits</strong> in an integer are the <code>1</code>&#39;s present when it is written in binary.</p> <ul> <li>For example, the binary representation of <code>21</code> is <code>10101</code>, which has <code>3</code> set bits.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,10,1,5,2], k = 1 <strong>Output:</strong> 13 <strong>Explanation:</strong> The binary representation of the indices are: 0 = 000<sub>2</sub> 1 = 001<sub>2</sub> 2 = 010<sub>2</sub> 3 = 011<sub>2</sub> 4 = 100<sub>2 </sub>Indices 1, 2, and 4 have k = 1 set bits in their binary representation. Hence, the answer is nums[1] + nums[2] + nums[4] = 13.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,1], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The binary representation of the indices are: 0 = 00<sub>2</sub> 1 = 01<sub>2</sub> 2 = 10<sub>2</sub> 3 = 11<sub>2 </sub>Only index 3 has k = 2 set bits in its binary representation. Hence, the answer is nums[3] = 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10</code></li> </ul>
Bit Manipulation; Array
TypeScript
function sumIndicesWithKSetBits(nums: number[], k: number): number { let ans = 0; for (let i = 0; i < nums.length; ++i) { if (bitCount(i) === k) { ans += nums[i]; } } return ans; } function bitCount(n: number): number { let count = 0; while (n) { n &= n - 1; count++; } return count; }
2,860
Happy Students
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> where <code>n</code> is the total number of students in the class. The class teacher tries to select a group of students so that all the students remain happy.</p> <p>The <code>i<sup>th</sup></code> student will become happy if one of these two conditions is met:</p> <ul> <li>The student is selected and the total number of selected students is<strong> strictly greater than</strong> <code>nums[i]</code>.</li> <li>The student is not selected and the total number of selected students is <strong>strictly</strong> <strong>less than</strong> <code>nums[i]</code>.</li> </ul> <p>Return <em>the number of ways to select a group of students so that everyone remains happy.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two possible ways are: The class teacher selects no student. The class teacher selects both students to form the group. If the class teacher selects just one student to form a group then the both students will not be happy. Therefore, there are only two possible ways. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,0,3,3,6,7,2,7] <strong>Output:</strong> 3 <strong>Explanation:</strong> The three possible ways are: The class teacher selects the student with index = 1 to form the group. The class teacher selects the students with index = 1, 2, 3, 6 to form the group. The class teacher selects all the students to form the group. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt; nums.length</code></li> </ul>
Array; Enumeration; Sorting
C++
class Solution { public: int countWays(vector<int>& nums) { sort(nums.begin(), nums.end()); int ans = 0; int n = nums.size(); for (int i = 0; i <= n; ++i) { if ((i && nums[i - 1] >= i) || (i < n && nums[i] <= i)) { continue; } ++ans; } return ans; } };
2,860
Happy Students
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> where <code>n</code> is the total number of students in the class. The class teacher tries to select a group of students so that all the students remain happy.</p> <p>The <code>i<sup>th</sup></code> student will become happy if one of these two conditions is met:</p> <ul> <li>The student is selected and the total number of selected students is<strong> strictly greater than</strong> <code>nums[i]</code>.</li> <li>The student is not selected and the total number of selected students is <strong>strictly</strong> <strong>less than</strong> <code>nums[i]</code>.</li> </ul> <p>Return <em>the number of ways to select a group of students so that everyone remains happy.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two possible ways are: The class teacher selects no student. The class teacher selects both students to form the group. If the class teacher selects just one student to form a group then the both students will not be happy. Therefore, there are only two possible ways. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,0,3,3,6,7,2,7] <strong>Output:</strong> 3 <strong>Explanation:</strong> The three possible ways are: The class teacher selects the student with index = 1 to form the group. The class teacher selects the students with index = 1, 2, 3, 6 to form the group. The class teacher selects all the students to form the group. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt; nums.length</code></li> </ul>
Array; Enumeration; Sorting
Go
func countWays(nums []int) (ans int) { sort.Ints(nums) n := len(nums) for i := 0; i <= n; i++ { if (i > 0 && nums[i-1] >= i) || (i < n && nums[i] <= i) { continue } ans++ } return }
2,860
Happy Students
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> where <code>n</code> is the total number of students in the class. The class teacher tries to select a group of students so that all the students remain happy.</p> <p>The <code>i<sup>th</sup></code> student will become happy if one of these two conditions is met:</p> <ul> <li>The student is selected and the total number of selected students is<strong> strictly greater than</strong> <code>nums[i]</code>.</li> <li>The student is not selected and the total number of selected students is <strong>strictly</strong> <strong>less than</strong> <code>nums[i]</code>.</li> </ul> <p>Return <em>the number of ways to select a group of students so that everyone remains happy.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two possible ways are: The class teacher selects no student. The class teacher selects both students to form the group. If the class teacher selects just one student to form a group then the both students will not be happy. Therefore, there are only two possible ways. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,0,3,3,6,7,2,7] <strong>Output:</strong> 3 <strong>Explanation:</strong> The three possible ways are: The class teacher selects the student with index = 1 to form the group. The class teacher selects the students with index = 1, 2, 3, 6 to form the group. The class teacher selects all the students to form the group. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt; nums.length</code></li> </ul>
Array; Enumeration; Sorting
Java
class Solution { public int countWays(List<Integer> nums) { Collections.sort(nums); int n = nums.size(); int ans = 0; for (int i = 0; i <= n; i++) { if ((i == 0 || nums.get(i - 1) < i) && (i == n || nums.get(i) > i)) { ans++; } } return ans; } }
2,860
Happy Students
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> where <code>n</code> is the total number of students in the class. The class teacher tries to select a group of students so that all the students remain happy.</p> <p>The <code>i<sup>th</sup></code> student will become happy if one of these two conditions is met:</p> <ul> <li>The student is selected and the total number of selected students is<strong> strictly greater than</strong> <code>nums[i]</code>.</li> <li>The student is not selected and the total number of selected students is <strong>strictly</strong> <strong>less than</strong> <code>nums[i]</code>.</li> </ul> <p>Return <em>the number of ways to select a group of students so that everyone remains happy.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two possible ways are: The class teacher selects no student. The class teacher selects both students to form the group. If the class teacher selects just one student to form a group then the both students will not be happy. Therefore, there are only two possible ways. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,0,3,3,6,7,2,7] <strong>Output:</strong> 3 <strong>Explanation:</strong> The three possible ways are: The class teacher selects the student with index = 1 to form the group. The class teacher selects the students with index = 1, 2, 3, 6 to form the group. The class teacher selects all the students to form the group. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt; nums.length</code></li> </ul>
Array; Enumeration; Sorting
Python
class Solution: def countWays(self, nums: List[int]) -> int: nums.sort() n = len(nums) ans = 0 for i in range(n + 1): if i and nums[i - 1] >= i: continue if i < n and nums[i] <= i: continue ans += 1 return ans
2,860
Happy Students
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> where <code>n</code> is the total number of students in the class. The class teacher tries to select a group of students so that all the students remain happy.</p> <p>The <code>i<sup>th</sup></code> student will become happy if one of these two conditions is met:</p> <ul> <li>The student is selected and the total number of selected students is<strong> strictly greater than</strong> <code>nums[i]</code>.</li> <li>The student is not selected and the total number of selected students is <strong>strictly</strong> <strong>less than</strong> <code>nums[i]</code>.</li> </ul> <p>Return <em>the number of ways to select a group of students so that everyone remains happy.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two possible ways are: The class teacher selects no student. The class teacher selects both students to form the group. If the class teacher selects just one student to form a group then the both students will not be happy. Therefore, there are only two possible ways. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,0,3,3,6,7,2,7] <strong>Output:</strong> 3 <strong>Explanation:</strong> The three possible ways are: The class teacher selects the student with index = 1 to form the group. The class teacher selects the students with index = 1, 2, 3, 6 to form the group. The class teacher selects all the students to form the group. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt; nums.length</code></li> </ul>
Array; Enumeration; Sorting
TypeScript
function countWays(nums: number[]): number { nums.sort((a, b) => a - b); let ans = 0; const n = nums.length; for (let i = 0; i <= n; ++i) { if ((i && nums[i - 1] >= i) || (i < n && nums[i] <= i)) { continue; } ++ans; } return ans; }
2,861
Maximum Number of Alloys
Medium
<p>You are the owner of a company that creates alloys using various types of metals. There are <code>n</code> different types of metals available, and you have access to <code>k</code> machines that can be used to create alloys. Each machine requires a specific amount of each metal type to create an alloy.</p> <p>For the <code>i<sup>th</sup></code> machine to create an alloy, it needs <code>composition[i][j]</code> units of metal of type <code>j</code>. Initially, you have <code>stock[i]</code> units of metal type <code>i</code>, and purchasing one unit of metal type <code>i</code> costs <code>cost[i]</code> coins.</p> <p>Given integers <code>n</code>, <code>k</code>, <code>budget</code>, a <strong>1-indexed</strong> 2D array <code>composition</code>, and <strong>1-indexed</strong> arrays <code>stock</code> and <code>cost</code>, your goal is to <strong>maximize</strong> the number of alloys the company can create while staying within the budget of <code>budget</code> coins.</p> <p><strong>All alloys must be created with the same machine.</strong></p> <p>Return <em>the maximum number of alloys that the company can create</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,0], cost = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> It is optimal to use the 1<sup>st</sup> machine to create alloys. To create 2 alloys we need to buy the: - 2 units of metal of the 1<sup>st</sup> type. - 2 units of metal of the 2<sup>nd</sup> type. - 2 units of metal of the 3<sup>rd</sup> type. In total, we need 2 * 1 + 2 * 2 + 2 * 3 = 12 coins, which is smaller than or equal to budget = 15. Notice that we have 0 units of metal of each type and we have to buy all the required units of metal. It can be proven that we can create at most 2 alloys. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,100], cost = [1,2,3] <strong>Output:</strong> 5 <strong>Explanation:</strong> It is optimal to use the 2<sup>nd</sup> machine to create alloys. To create 5 alloys we need to buy: - 5 units of metal of the 1<sup>st</sup> type. - 5 units of metal of the 2<sup>nd</sup> type. - 0 units of metal of the 3<sup>rd</sup> type. In total, we need 5 * 1 + 5 * 2 + 0 * 3 = 15 coins, which is smaller than or equal to budget = 15. It can be proven that we can create at most 5 alloys. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, k = 3, budget = 10, composition = [[2,1],[1,2],[1,1]], stock = [1,1], cost = [5,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> It is optimal to use the 3<sup>rd</sup> machine to create alloys. To create 2 alloys we need to buy the: - 1 unit of metal of the 1<sup>st</sup> type. - 1 unit of metal of the 2<sup>nd</sup> type. In total, we need 1 * 5 + 1 * 5 = 10 coins, which is smaller than or equal to budget = 10. It can be proven that we can create at most 2 alloys. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, k &lt;= 100</code></li> <li><code>0 &lt;= budget &lt;= 10<sup>8</sup></code></li> <li><code>composition.length == k</code></li> <li><code>composition[i].length == n</code></li> <li><code>1 &lt;= composition[i][j] &lt;= 100</code></li> <li><code>stock.length == cost.length == n</code></li> <li><code>0 &lt;= stock[i] &lt;= 10<sup>8</sup></code></li> <li><code>1 &lt;= cost[i] &lt;= 100</code></li> </ul>
Array; Binary Search
C++
class Solution { public: int maxNumberOfAlloys(int n, int k, int budget, vector<vector<int>>& composition, vector<int>& stock, vector<int>& cost) { auto isValid = [&](long long target) { for (int i = 0; i < k; i++) { long long remain = budget; auto currMachine = composition[i]; for (int j = 0; j < n && remain >= 0; j++) { long long need = max(0LL, target * currMachine[j] - stock[j]); remain -= need * cost[j]; } if (remain >= 0) { return true; } } return false; }; long long l = 0, r = budget + stock[0]; while (l < r) { long long mid = (l + r + 1) >> 1; if (isValid(mid)) { l = mid; } else { r = mid - 1; } } return l; } };
2,861
Maximum Number of Alloys
Medium
<p>You are the owner of a company that creates alloys using various types of metals. There are <code>n</code> different types of metals available, and you have access to <code>k</code> machines that can be used to create alloys. Each machine requires a specific amount of each metal type to create an alloy.</p> <p>For the <code>i<sup>th</sup></code> machine to create an alloy, it needs <code>composition[i][j]</code> units of metal of type <code>j</code>. Initially, you have <code>stock[i]</code> units of metal type <code>i</code>, and purchasing one unit of metal type <code>i</code> costs <code>cost[i]</code> coins.</p> <p>Given integers <code>n</code>, <code>k</code>, <code>budget</code>, a <strong>1-indexed</strong> 2D array <code>composition</code>, and <strong>1-indexed</strong> arrays <code>stock</code> and <code>cost</code>, your goal is to <strong>maximize</strong> the number of alloys the company can create while staying within the budget of <code>budget</code> coins.</p> <p><strong>All alloys must be created with the same machine.</strong></p> <p>Return <em>the maximum number of alloys that the company can create</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,0], cost = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> It is optimal to use the 1<sup>st</sup> machine to create alloys. To create 2 alloys we need to buy the: - 2 units of metal of the 1<sup>st</sup> type. - 2 units of metal of the 2<sup>nd</sup> type. - 2 units of metal of the 3<sup>rd</sup> type. In total, we need 2 * 1 + 2 * 2 + 2 * 3 = 12 coins, which is smaller than or equal to budget = 15. Notice that we have 0 units of metal of each type and we have to buy all the required units of metal. It can be proven that we can create at most 2 alloys. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,100], cost = [1,2,3] <strong>Output:</strong> 5 <strong>Explanation:</strong> It is optimal to use the 2<sup>nd</sup> machine to create alloys. To create 5 alloys we need to buy: - 5 units of metal of the 1<sup>st</sup> type. - 5 units of metal of the 2<sup>nd</sup> type. - 0 units of metal of the 3<sup>rd</sup> type. In total, we need 5 * 1 + 5 * 2 + 0 * 3 = 15 coins, which is smaller than or equal to budget = 15. It can be proven that we can create at most 5 alloys. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, k = 3, budget = 10, composition = [[2,1],[1,2],[1,1]], stock = [1,1], cost = [5,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> It is optimal to use the 3<sup>rd</sup> machine to create alloys. To create 2 alloys we need to buy the: - 1 unit of metal of the 1<sup>st</sup> type. - 1 unit of metal of the 2<sup>nd</sup> type. In total, we need 1 * 5 + 1 * 5 = 10 coins, which is smaller than or equal to budget = 10. It can be proven that we can create at most 2 alloys. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, k &lt;= 100</code></li> <li><code>0 &lt;= budget &lt;= 10<sup>8</sup></code></li> <li><code>composition.length == k</code></li> <li><code>composition[i].length == n</code></li> <li><code>1 &lt;= composition[i][j] &lt;= 100</code></li> <li><code>stock.length == cost.length == n</code></li> <li><code>0 &lt;= stock[i] &lt;= 10<sup>8</sup></code></li> <li><code>1 &lt;= cost[i] &lt;= 100</code></li> </ul>
Array; Binary Search
Go
func maxNumberOfAlloys(n int, k int, budget int, composition [][]int, stock []int, cost []int) int { isValid := func(target int) bool { for _, currMachine := range composition { remain := budget for i, x := range currMachine { need := max(0, x*target-stock[i]) remain -= need * cost[i] } if remain >= 0 { return true } } return false } l, r := 0, budget+stock[0] for l < r { mid := (l + r + 1) >> 1 if isValid(mid) { l = mid } else { r = mid - 1 } } return l }
2,861
Maximum Number of Alloys
Medium
<p>You are the owner of a company that creates alloys using various types of metals. There are <code>n</code> different types of metals available, and you have access to <code>k</code> machines that can be used to create alloys. Each machine requires a specific amount of each metal type to create an alloy.</p> <p>For the <code>i<sup>th</sup></code> machine to create an alloy, it needs <code>composition[i][j]</code> units of metal of type <code>j</code>. Initially, you have <code>stock[i]</code> units of metal type <code>i</code>, and purchasing one unit of metal type <code>i</code> costs <code>cost[i]</code> coins.</p> <p>Given integers <code>n</code>, <code>k</code>, <code>budget</code>, a <strong>1-indexed</strong> 2D array <code>composition</code>, and <strong>1-indexed</strong> arrays <code>stock</code> and <code>cost</code>, your goal is to <strong>maximize</strong> the number of alloys the company can create while staying within the budget of <code>budget</code> coins.</p> <p><strong>All alloys must be created with the same machine.</strong></p> <p>Return <em>the maximum number of alloys that the company can create</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,0], cost = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> It is optimal to use the 1<sup>st</sup> machine to create alloys. To create 2 alloys we need to buy the: - 2 units of metal of the 1<sup>st</sup> type. - 2 units of metal of the 2<sup>nd</sup> type. - 2 units of metal of the 3<sup>rd</sup> type. In total, we need 2 * 1 + 2 * 2 + 2 * 3 = 12 coins, which is smaller than or equal to budget = 15. Notice that we have 0 units of metal of each type and we have to buy all the required units of metal. It can be proven that we can create at most 2 alloys. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,100], cost = [1,2,3] <strong>Output:</strong> 5 <strong>Explanation:</strong> It is optimal to use the 2<sup>nd</sup> machine to create alloys. To create 5 alloys we need to buy: - 5 units of metal of the 1<sup>st</sup> type. - 5 units of metal of the 2<sup>nd</sup> type. - 0 units of metal of the 3<sup>rd</sup> type. In total, we need 5 * 1 + 5 * 2 + 0 * 3 = 15 coins, which is smaller than or equal to budget = 15. It can be proven that we can create at most 5 alloys. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, k = 3, budget = 10, composition = [[2,1],[1,2],[1,1]], stock = [1,1], cost = [5,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> It is optimal to use the 3<sup>rd</sup> machine to create alloys. To create 2 alloys we need to buy the: - 1 unit of metal of the 1<sup>st</sup> type. - 1 unit of metal of the 2<sup>nd</sup> type. In total, we need 1 * 5 + 1 * 5 = 10 coins, which is smaller than or equal to budget = 10. It can be proven that we can create at most 2 alloys. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, k &lt;= 100</code></li> <li><code>0 &lt;= budget &lt;= 10<sup>8</sup></code></li> <li><code>composition.length == k</code></li> <li><code>composition[i].length == n</code></li> <li><code>1 &lt;= composition[i][j] &lt;= 100</code></li> <li><code>stock.length == cost.length == n</code></li> <li><code>0 &lt;= stock[i] &lt;= 10<sup>8</sup></code></li> <li><code>1 &lt;= cost[i] &lt;= 100</code></li> </ul>
Array; Binary Search
Java
class Solution { int n; int budget; List<List<Integer>> composition; List<Integer> stock; List<Integer> cost; boolean isValid(long target) { for (List<Integer> currMachine : composition) { long remain = budget; for (int j = 0; j < n && remain >= 0; j++) { long need = Math.max(0, currMachine.get(j) * target - stock.get(j)); remain -= need * cost.get(j); } if (remain >= 0) { return true; } } return false; } public int maxNumberOfAlloys(int n, int k, int budget, List<List<Integer>> composition, List<Integer> stock, List<Integer> cost) { this.n = n; this.budget = budget; this.composition = composition; this.stock = stock; this.cost = cost; int l = -1; int r = budget / cost.get(0) + stock.get(0); while (l < r) { int mid = (l + r + 1) >> 1; if (isValid(mid)) { l = mid; } else { r = mid - 1; } } return l; } }
2,861
Maximum Number of Alloys
Medium
<p>You are the owner of a company that creates alloys using various types of metals. There are <code>n</code> different types of metals available, and you have access to <code>k</code> machines that can be used to create alloys. Each machine requires a specific amount of each metal type to create an alloy.</p> <p>For the <code>i<sup>th</sup></code> machine to create an alloy, it needs <code>composition[i][j]</code> units of metal of type <code>j</code>. Initially, you have <code>stock[i]</code> units of metal type <code>i</code>, and purchasing one unit of metal type <code>i</code> costs <code>cost[i]</code> coins.</p> <p>Given integers <code>n</code>, <code>k</code>, <code>budget</code>, a <strong>1-indexed</strong> 2D array <code>composition</code>, and <strong>1-indexed</strong> arrays <code>stock</code> and <code>cost</code>, your goal is to <strong>maximize</strong> the number of alloys the company can create while staying within the budget of <code>budget</code> coins.</p> <p><strong>All alloys must be created with the same machine.</strong></p> <p>Return <em>the maximum number of alloys that the company can create</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,0], cost = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> It is optimal to use the 1<sup>st</sup> machine to create alloys. To create 2 alloys we need to buy the: - 2 units of metal of the 1<sup>st</sup> type. - 2 units of metal of the 2<sup>nd</sup> type. - 2 units of metal of the 3<sup>rd</sup> type. In total, we need 2 * 1 + 2 * 2 + 2 * 3 = 12 coins, which is smaller than or equal to budget = 15. Notice that we have 0 units of metal of each type and we have to buy all the required units of metal. It can be proven that we can create at most 2 alloys. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,100], cost = [1,2,3] <strong>Output:</strong> 5 <strong>Explanation:</strong> It is optimal to use the 2<sup>nd</sup> machine to create alloys. To create 5 alloys we need to buy: - 5 units of metal of the 1<sup>st</sup> type. - 5 units of metal of the 2<sup>nd</sup> type. - 0 units of metal of the 3<sup>rd</sup> type. In total, we need 5 * 1 + 5 * 2 + 0 * 3 = 15 coins, which is smaller than or equal to budget = 15. It can be proven that we can create at most 5 alloys. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, k = 3, budget = 10, composition = [[2,1],[1,2],[1,1]], stock = [1,1], cost = [5,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> It is optimal to use the 3<sup>rd</sup> machine to create alloys. To create 2 alloys we need to buy the: - 1 unit of metal of the 1<sup>st</sup> type. - 1 unit of metal of the 2<sup>nd</sup> type. In total, we need 1 * 5 + 1 * 5 = 10 coins, which is smaller than or equal to budget = 10. It can be proven that we can create at most 2 alloys. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, k &lt;= 100</code></li> <li><code>0 &lt;= budget &lt;= 10<sup>8</sup></code></li> <li><code>composition.length == k</code></li> <li><code>composition[i].length == n</code></li> <li><code>1 &lt;= composition[i][j] &lt;= 100</code></li> <li><code>stock.length == cost.length == n</code></li> <li><code>0 &lt;= stock[i] &lt;= 10<sup>8</sup></code></li> <li><code>1 &lt;= cost[i] &lt;= 100</code></li> </ul>
Array; Binary Search
Python
class Solution: def maxNumberOfAlloys( self, n: int, k: int, budget: int, composition: List[List[int]], stock: List[int], cost: List[int], ) -> int: ans = 0 for c in composition: l, r = 0, budget + stock[0] while l < r: mid = (l + r + 1) >> 1 s = sum(max(0, mid * x - y) * z for x, y, z in zip(c, stock, cost)) if s <= budget: l = mid else: r = mid - 1 ans = max(ans, l) return ans
2,861
Maximum Number of Alloys
Medium
<p>You are the owner of a company that creates alloys using various types of metals. There are <code>n</code> different types of metals available, and you have access to <code>k</code> machines that can be used to create alloys. Each machine requires a specific amount of each metal type to create an alloy.</p> <p>For the <code>i<sup>th</sup></code> machine to create an alloy, it needs <code>composition[i][j]</code> units of metal of type <code>j</code>. Initially, you have <code>stock[i]</code> units of metal type <code>i</code>, and purchasing one unit of metal type <code>i</code> costs <code>cost[i]</code> coins.</p> <p>Given integers <code>n</code>, <code>k</code>, <code>budget</code>, a <strong>1-indexed</strong> 2D array <code>composition</code>, and <strong>1-indexed</strong> arrays <code>stock</code> and <code>cost</code>, your goal is to <strong>maximize</strong> the number of alloys the company can create while staying within the budget of <code>budget</code> coins.</p> <p><strong>All alloys must be created with the same machine.</strong></p> <p>Return <em>the maximum number of alloys that the company can create</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,0], cost = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> It is optimal to use the 1<sup>st</sup> machine to create alloys. To create 2 alloys we need to buy the: - 2 units of metal of the 1<sup>st</sup> type. - 2 units of metal of the 2<sup>nd</sup> type. - 2 units of metal of the 3<sup>rd</sup> type. In total, we need 2 * 1 + 2 * 2 + 2 * 3 = 12 coins, which is smaller than or equal to budget = 15. Notice that we have 0 units of metal of each type and we have to buy all the required units of metal. It can be proven that we can create at most 2 alloys. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,100], cost = [1,2,3] <strong>Output:</strong> 5 <strong>Explanation:</strong> It is optimal to use the 2<sup>nd</sup> machine to create alloys. To create 5 alloys we need to buy: - 5 units of metal of the 1<sup>st</sup> type. - 5 units of metal of the 2<sup>nd</sup> type. - 0 units of metal of the 3<sup>rd</sup> type. In total, we need 5 * 1 + 5 * 2 + 0 * 3 = 15 coins, which is smaller than or equal to budget = 15. It can be proven that we can create at most 5 alloys. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 2, k = 3, budget = 10, composition = [[2,1],[1,2],[1,1]], stock = [1,1], cost = [5,5] <strong>Output:</strong> 2 <strong>Explanation:</strong> It is optimal to use the 3<sup>rd</sup> machine to create alloys. To create 2 alloys we need to buy the: - 1 unit of metal of the 1<sup>st</sup> type. - 1 unit of metal of the 2<sup>nd</sup> type. In total, we need 1 * 5 + 1 * 5 = 10 coins, which is smaller than or equal to budget = 10. It can be proven that we can create at most 2 alloys. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n, k &lt;= 100</code></li> <li><code>0 &lt;= budget &lt;= 10<sup>8</sup></code></li> <li><code>composition.length == k</code></li> <li><code>composition[i].length == n</code></li> <li><code>1 &lt;= composition[i][j] &lt;= 100</code></li> <li><code>stock.length == cost.length == n</code></li> <li><code>0 &lt;= stock[i] &lt;= 10<sup>8</sup></code></li> <li><code>1 &lt;= cost[i] &lt;= 100</code></li> </ul>
Array; Binary Search
TypeScript
function maxNumberOfAlloys( n: number, k: number, budget: number, composition: number[][], stock: number[], cost: number[], ): number { let l = 0; let r = budget + stock[0]; const isValid = (target: number): boolean => { for (const currMachine of composition) { let remain = budget; for (let i = 0; i < n; ++i) { let need = Math.max(0, target * currMachine[i] - stock[i]); remain -= need * cost[i]; } if (remain >= 0) { return true; } } return false; }; while (l < r) { const mid = (l + r + 1) >> 1; if (isValid(mid)) { l = mid; } else { r = mid - 1; } } return l; }
2,862
Maximum Element-Sum of a Complete Subset of Indices
Hard
<p>You are given a <strong>1</strong><strong>-indexed</strong> array <code>nums</code>. Your task is to select a <strong>complete subset</strong> from <code>nums</code> where every pair of selected indices multiplied is a <span data-keyword="perfect-square">perfect square,</span>. i. e. if you select <code>a<sub>i</sub></code> and <code>a<sub>j</sub></code>, <code>i * j</code> must be a perfect square.</p> <p>Return the <em>sum</em> of the complete subset with the <em>maximum sum</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,7,3,5,7,2,4,9]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>We select elements at indices 2 and 8 and <code>2 * 8</code> is a perfect square.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,10,3,8,1,13,7,9,4]</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>We select elements at indices 1, 4, and 9. <code>1 * 4</code>, <code>1 * 9</code>, <code>4 * 9</code> are perfect squares.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Math; Number Theory
C++
class Solution { public: long long maximumSum(vector<int>& nums) { long long ans = 0; int n = nums.size(); for (int k = 1; k <= n; ++k) { long long t = 0; for (int j = 1; k * j * j <= n; ++j) { t += nums[k * j * j - 1]; } ans = max(ans, t); } return ans; } };
2,862
Maximum Element-Sum of a Complete Subset of Indices
Hard
<p>You are given a <strong>1</strong><strong>-indexed</strong> array <code>nums</code>. Your task is to select a <strong>complete subset</strong> from <code>nums</code> where every pair of selected indices multiplied is a <span data-keyword="perfect-square">perfect square,</span>. i. e. if you select <code>a<sub>i</sub></code> and <code>a<sub>j</sub></code>, <code>i * j</code> must be a perfect square.</p> <p>Return the <em>sum</em> of the complete subset with the <em>maximum sum</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,7,3,5,7,2,4,9]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>We select elements at indices 2 and 8 and <code>2 * 8</code> is a perfect square.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,10,3,8,1,13,7,9,4]</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>We select elements at indices 1, 4, and 9. <code>1 * 4</code>, <code>1 * 9</code>, <code>4 * 9</code> are perfect squares.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Math; Number Theory
Go
func maximumSum(nums []int) (ans int64) { n := len(nums) for k := 1; k <= n; k++ { var t int64 for j := 1; k*j*j <= n; j++ { t += int64(nums[k*j*j-1]) } ans = max(ans, t) } return }
2,862
Maximum Element-Sum of a Complete Subset of Indices
Hard
<p>You are given a <strong>1</strong><strong>-indexed</strong> array <code>nums</code>. Your task is to select a <strong>complete subset</strong> from <code>nums</code> where every pair of selected indices multiplied is a <span data-keyword="perfect-square">perfect square,</span>. i. e. if you select <code>a<sub>i</sub></code> and <code>a<sub>j</sub></code>, <code>i * j</code> must be a perfect square.</p> <p>Return the <em>sum</em> of the complete subset with the <em>maximum sum</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,7,3,5,7,2,4,9]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>We select elements at indices 2 and 8 and <code>2 * 8</code> is a perfect square.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,10,3,8,1,13,7,9,4]</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>We select elements at indices 1, 4, and 9. <code>1 * 4</code>, <code>1 * 9</code>, <code>4 * 9</code> are perfect squares.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Math; Number Theory
Java
class Solution { public long maximumSum(List<Integer> nums) { long ans = 0; int n = nums.size(); boolean[] used = new boolean[n + 1]; int bound = (int) Math.floor(Math.sqrt(n)); int[] squares = new int[bound + 1]; for (int i = 1; i <= bound + 1; i++) { squares[i - 1] = i * i; } for (int i = 1; i <= n; i++) { long res = 0; int idx = 0; int curr = i * squares[idx]; while (curr <= n) { res += nums.get(curr - 1); curr = i * squares[++idx]; } ans = Math.max(ans, res); } return ans; } }
2,862
Maximum Element-Sum of a Complete Subset of Indices
Hard
<p>You are given a <strong>1</strong><strong>-indexed</strong> array <code>nums</code>. Your task is to select a <strong>complete subset</strong> from <code>nums</code> where every pair of selected indices multiplied is a <span data-keyword="perfect-square">perfect square,</span>. i. e. if you select <code>a<sub>i</sub></code> and <code>a<sub>j</sub></code>, <code>i * j</code> must be a perfect square.</p> <p>Return the <em>sum</em> of the complete subset with the <em>maximum sum</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,7,3,5,7,2,4,9]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>We select elements at indices 2 and 8 and <code>2 * 8</code> is a perfect square.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,10,3,8,1,13,7,9,4]</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>We select elements at indices 1, 4, and 9. <code>1 * 4</code>, <code>1 * 9</code>, <code>4 * 9</code> are perfect squares.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Math; Number Theory
Python
class Solution: def maximumSum(self, nums: List[int]) -> int: n = len(nums) ans = 0 for k in range(1, n + 1): t = 0 j = 1 while k * j * j <= n: t += nums[k * j * j - 1] j += 1 ans = max(ans, t) return ans
2,862
Maximum Element-Sum of a Complete Subset of Indices
Hard
<p>You are given a <strong>1</strong><strong>-indexed</strong> array <code>nums</code>. Your task is to select a <strong>complete subset</strong> from <code>nums</code> where every pair of selected indices multiplied is a <span data-keyword="perfect-square">perfect square,</span>. i. e. if you select <code>a<sub>i</sub></code> and <code>a<sub>j</sub></code>, <code>i * j</code> must be a perfect square.</p> <p>Return the <em>sum</em> of the complete subset with the <em>maximum sum</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,7,3,5,7,2,4,9]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>We select elements at indices 2 and 8 and <code>2 * 8</code> is a perfect square.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,10,3,8,1,13,7,9,4]</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>We select elements at indices 1, 4, and 9. <code>1 * 4</code>, <code>1 * 9</code>, <code>4 * 9</code> are perfect squares.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Math; Number Theory
TypeScript
function maximumSum(nums: number[]): number { let ans = 0; const n = nums.length; for (let k = 1; k <= n; ++k) { let t = 0; for (let j = 1; k * j * j <= n; ++j) { t += nums[k * j * j - 1]; } ans = Math.max(ans, t); } return ans; }
2,863
Maximum Length of Semi-Decreasing Subarrays
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>Return <em>the length of the <strong>longest semi-decreasing</strong> subarray of </em><code>nums</code><em>, and </em><code>0</code><em> if there are no such subarrays.</em></p> <ul> <li>A <b>subarray</b> is a contiguous non-empty sequence of elements within an array.</li> <li>A non-empty array is <strong>semi-decreasing</strong> if its first element is <strong>strictly greater</strong> than its last element.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,6,5,4,3,2,1,6,10,11] <strong>Output:</strong> 8 <strong>Explanation:</strong> Take the subarray [7,6,5,4,3,2,1,6]. The first element is 7 and the last one is 6 so the condition is met. Hence, the answer would be the length of the subarray or 8. It can be shown that there aren&#39;t any subarrays with the given condition with a length greater than 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [57,55,50,60,61,58,63,59,64,60,63] <strong>Output:</strong> 6 <strong>Explanation:</strong> Take the subarray [61,58,63,59,64,60]. The first element is 61 and the last one is 60 so the condition is met. Hence, the answer would be the length of the subarray or 6. It can be shown that there aren&#39;t any subarrays with the given condition with a length greater than 6. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> Since there are no semi-decreasing subarrays in the given array, the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Sorting; Monotonic Stack
C++
class Solution { public: int maxSubarrayLength(vector<int>& nums) { map<int, vector<int>, greater<int>> d; for (int i = 0; i < nums.size(); ++i) { d[nums[i]].push_back(i); } int ans = 0, k = 1 << 30; for (auto& [_, idx] : d) { ans = max(ans, idx.back() - k + 1); k = min(k, idx[0]); } return ans; } };
2,863
Maximum Length of Semi-Decreasing Subarrays
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>Return <em>the length of the <strong>longest semi-decreasing</strong> subarray of </em><code>nums</code><em>, and </em><code>0</code><em> if there are no such subarrays.</em></p> <ul> <li>A <b>subarray</b> is a contiguous non-empty sequence of elements within an array.</li> <li>A non-empty array is <strong>semi-decreasing</strong> if its first element is <strong>strictly greater</strong> than its last element.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,6,5,4,3,2,1,6,10,11] <strong>Output:</strong> 8 <strong>Explanation:</strong> Take the subarray [7,6,5,4,3,2,1,6]. The first element is 7 and the last one is 6 so the condition is met. Hence, the answer would be the length of the subarray or 8. It can be shown that there aren&#39;t any subarrays with the given condition with a length greater than 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [57,55,50,60,61,58,63,59,64,60,63] <strong>Output:</strong> 6 <strong>Explanation:</strong> Take the subarray [61,58,63,59,64,60]. The first element is 61 and the last one is 60 so the condition is met. Hence, the answer would be the length of the subarray or 6. It can be shown that there aren&#39;t any subarrays with the given condition with a length greater than 6. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> Since there are no semi-decreasing subarrays in the given array, the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Sorting; Monotonic Stack
Go
func maxSubarrayLength(nums []int) (ans int) { d := map[int][]int{} for i, x := range nums { d[x] = append(d[x], i) } keys := []int{} for x := range d { keys = append(keys, x) } sort.Slice(keys, func(i, j int) bool { return keys[i] > keys[j] }) k := 1 << 30 for _, x := range keys { idx := d[x] ans = max(ans, idx[len(idx)-1]-k+1) k = min(k, idx[0]) } return ans }
2,863
Maximum Length of Semi-Decreasing Subarrays
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>Return <em>the length of the <strong>longest semi-decreasing</strong> subarray of </em><code>nums</code><em>, and </em><code>0</code><em> if there are no such subarrays.</em></p> <ul> <li>A <b>subarray</b> is a contiguous non-empty sequence of elements within an array.</li> <li>A non-empty array is <strong>semi-decreasing</strong> if its first element is <strong>strictly greater</strong> than its last element.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,6,5,4,3,2,1,6,10,11] <strong>Output:</strong> 8 <strong>Explanation:</strong> Take the subarray [7,6,5,4,3,2,1,6]. The first element is 7 and the last one is 6 so the condition is met. Hence, the answer would be the length of the subarray or 8. It can be shown that there aren&#39;t any subarrays with the given condition with a length greater than 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [57,55,50,60,61,58,63,59,64,60,63] <strong>Output:</strong> 6 <strong>Explanation:</strong> Take the subarray [61,58,63,59,64,60]. The first element is 61 and the last one is 60 so the condition is met. Hence, the answer would be the length of the subarray or 6. It can be shown that there aren&#39;t any subarrays with the given condition with a length greater than 6. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> Since there are no semi-decreasing subarrays in the given array, the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Sorting; Monotonic Stack
Java
class Solution { public int maxSubarrayLength(int[] nums) { TreeMap<Integer, List<Integer>> d = new TreeMap<>(Comparator.reverseOrder()); for (int i = 0; i < nums.length; ++i) { d.computeIfAbsent(nums[i], k -> new ArrayList<>()).add(i); } int ans = 0, k = 1 << 30; for (List<Integer> idx : d.values()) { ans = Math.max(ans, idx.get(idx.size() - 1) - k + 1); k = Math.min(k, idx.get(0)); } return ans; } }
2,863
Maximum Length of Semi-Decreasing Subarrays
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>Return <em>the length of the <strong>longest semi-decreasing</strong> subarray of </em><code>nums</code><em>, and </em><code>0</code><em> if there are no such subarrays.</em></p> <ul> <li>A <b>subarray</b> is a contiguous non-empty sequence of elements within an array.</li> <li>A non-empty array is <strong>semi-decreasing</strong> if its first element is <strong>strictly greater</strong> than its last element.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,6,5,4,3,2,1,6,10,11] <strong>Output:</strong> 8 <strong>Explanation:</strong> Take the subarray [7,6,5,4,3,2,1,6]. The first element is 7 and the last one is 6 so the condition is met. Hence, the answer would be the length of the subarray or 8. It can be shown that there aren&#39;t any subarrays with the given condition with a length greater than 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [57,55,50,60,61,58,63,59,64,60,63] <strong>Output:</strong> 6 <strong>Explanation:</strong> Take the subarray [61,58,63,59,64,60]. The first element is 61 and the last one is 60 so the condition is met. Hence, the answer would be the length of the subarray or 6. It can be shown that there aren&#39;t any subarrays with the given condition with a length greater than 6. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> Since there are no semi-decreasing subarrays in the given array, the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Sorting; Monotonic Stack
Python
class Solution: def maxSubarrayLength(self, nums: List[int]) -> int: d = defaultdict(list) for i, x in enumerate(nums): d[x].append(i) ans, k = 0, inf for x in sorted(d, reverse=True): ans = max(ans, d[x][-1] - k + 1) k = min(k, d[x][0]) return ans
2,863
Maximum Length of Semi-Decreasing Subarrays
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>Return <em>the length of the <strong>longest semi-decreasing</strong> subarray of </em><code>nums</code><em>, and </em><code>0</code><em> if there are no such subarrays.</em></p> <ul> <li>A <b>subarray</b> is a contiguous non-empty sequence of elements within an array.</li> <li>A non-empty array is <strong>semi-decreasing</strong> if its first element is <strong>strictly greater</strong> than its last element.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [7,6,5,4,3,2,1,6,10,11] <strong>Output:</strong> 8 <strong>Explanation:</strong> Take the subarray [7,6,5,4,3,2,1,6]. The first element is 7 and the last one is 6 so the condition is met. Hence, the answer would be the length of the subarray or 8. It can be shown that there aren&#39;t any subarrays with the given condition with a length greater than 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [57,55,50,60,61,58,63,59,64,60,63] <strong>Output:</strong> 6 <strong>Explanation:</strong> Take the subarray [61,58,63,59,64,60]. The first element is 61 and the last one is 60 so the condition is met. Hence, the answer would be the length of the subarray or 6. It can be shown that there aren&#39;t any subarrays with the given condition with a length greater than 6. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> Since there are no semi-decreasing subarrays in the given array, the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Sorting; Monotonic Stack
TypeScript
function maxSubarrayLength(nums: number[]): number { const d: Map<number, number[]> = new Map(); for (let i = 0; i < nums.length; ++i) { if (!d.has(nums[i])) { d.set(nums[i], []); } d.get(nums[i])!.push(i); } const keys = Array.from(d.keys()).sort((a, b) => b - a); let ans = 0; let k = Infinity; for (const x of keys) { const idx = d.get(x)!; ans = Math.max(ans, idx.at(-1) - k + 1); k = Math.min(k, idx[0]); } return ans; }
2,864
Maximum Odd Binary Number
Easy
<p>You are given a <strong>binary</strong> string <code>s</code> that contains at least one <code>&#39;1&#39;</code>.</p> <p>You have to <strong>rearrange</strong> the bits in such a way that the resulting binary number is the <strong>maximum odd binary number</strong> that can be created from this combination.</p> <p>Return <em>a string representing the maximum odd binary number that can be created from the given combination.</em></p> <p><strong>Note </strong>that the resulting string <strong>can</strong> have leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;010&quot; <strong>Output:</strong> &quot;001&quot; <strong>Explanation:</strong> Because there is just one &#39;1&#39;, it must be in the last position. So the answer is &quot;001&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0101&quot; <strong>Output:</strong> &quot;1001&quot; <strong>Explanation: </strong>One of the &#39;1&#39;s must be in the last position. The maximum number that can be made with the remaining digits is &quot;100&quot;. So the answer is &quot;1001&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>s</code> contains at least one <code>&#39;1&#39;</code>.</li> </ul>
Greedy; Math; String
C++
class Solution { public: string maximumOddBinaryNumber(string s) { int cnt = count(s.begin(), s.end(), '1'); return string(cnt - 1, '1') + string(s.size() - cnt, '0') + '1'; } };
2,864
Maximum Odd Binary Number
Easy
<p>You are given a <strong>binary</strong> string <code>s</code> that contains at least one <code>&#39;1&#39;</code>.</p> <p>You have to <strong>rearrange</strong> the bits in such a way that the resulting binary number is the <strong>maximum odd binary number</strong> that can be created from this combination.</p> <p>Return <em>a string representing the maximum odd binary number that can be created from the given combination.</em></p> <p><strong>Note </strong>that the resulting string <strong>can</strong> have leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;010&quot; <strong>Output:</strong> &quot;001&quot; <strong>Explanation:</strong> Because there is just one &#39;1&#39;, it must be in the last position. So the answer is &quot;001&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0101&quot; <strong>Output:</strong> &quot;1001&quot; <strong>Explanation: </strong>One of the &#39;1&#39;s must be in the last position. The maximum number that can be made with the remaining digits is &quot;100&quot;. So the answer is &quot;1001&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>s</code> contains at least one <code>&#39;1&#39;</code>.</li> </ul>
Greedy; Math; String
Go
func maximumOddBinaryNumber(s string) string { cnt := strings.Count(s, "1") return strings.Repeat("1", cnt-1) + strings.Repeat("0", len(s)-cnt) + "1" }
2,864
Maximum Odd Binary Number
Easy
<p>You are given a <strong>binary</strong> string <code>s</code> that contains at least one <code>&#39;1&#39;</code>.</p> <p>You have to <strong>rearrange</strong> the bits in such a way that the resulting binary number is the <strong>maximum odd binary number</strong> that can be created from this combination.</p> <p>Return <em>a string representing the maximum odd binary number that can be created from the given combination.</em></p> <p><strong>Note </strong>that the resulting string <strong>can</strong> have leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;010&quot; <strong>Output:</strong> &quot;001&quot; <strong>Explanation:</strong> Because there is just one &#39;1&#39;, it must be in the last position. So the answer is &quot;001&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0101&quot; <strong>Output:</strong> &quot;1001&quot; <strong>Explanation: </strong>One of the &#39;1&#39;s must be in the last position. The maximum number that can be made with the remaining digits is &quot;100&quot;. So the answer is &quot;1001&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>s</code> contains at least one <code>&#39;1&#39;</code>.</li> </ul>
Greedy; Math; String
Java
class Solution { public String maximumOddBinaryNumber(String s) { int cnt = s.length() - s.replace("1", "").length(); return "1".repeat(cnt - 1) + "0".repeat(s.length() - cnt) + "1"; } }
2,864
Maximum Odd Binary Number
Easy
<p>You are given a <strong>binary</strong> string <code>s</code> that contains at least one <code>&#39;1&#39;</code>.</p> <p>You have to <strong>rearrange</strong> the bits in such a way that the resulting binary number is the <strong>maximum odd binary number</strong> that can be created from this combination.</p> <p>Return <em>a string representing the maximum odd binary number that can be created from the given combination.</em></p> <p><strong>Note </strong>that the resulting string <strong>can</strong> have leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;010&quot; <strong>Output:</strong> &quot;001&quot; <strong>Explanation:</strong> Because there is just one &#39;1&#39;, it must be in the last position. So the answer is &quot;001&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0101&quot; <strong>Output:</strong> &quot;1001&quot; <strong>Explanation: </strong>One of the &#39;1&#39;s must be in the last position. The maximum number that can be made with the remaining digits is &quot;100&quot;. So the answer is &quot;1001&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>s</code> contains at least one <code>&#39;1&#39;</code>.</li> </ul>
Greedy; Math; String
Python
class Solution: def maximumOddBinaryNumber(self, s: str) -> str: cnt = s.count("1") return "1" * (cnt - 1) + (len(s) - cnt) * "0" + "1"
2,864
Maximum Odd Binary Number
Easy
<p>You are given a <strong>binary</strong> string <code>s</code> that contains at least one <code>&#39;1&#39;</code>.</p> <p>You have to <strong>rearrange</strong> the bits in such a way that the resulting binary number is the <strong>maximum odd binary number</strong> that can be created from this combination.</p> <p>Return <em>a string representing the maximum odd binary number that can be created from the given combination.</em></p> <p><strong>Note </strong>that the resulting string <strong>can</strong> have leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;010&quot; <strong>Output:</strong> &quot;001&quot; <strong>Explanation:</strong> Because there is just one &#39;1&#39;, it must be in the last position. So the answer is &quot;001&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0101&quot; <strong>Output:</strong> &quot;1001&quot; <strong>Explanation: </strong>One of the &#39;1&#39;s must be in the last position. The maximum number that can be made with the remaining digits is &quot;100&quot;. So the answer is &quot;1001&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>s</code> contains at least one <code>&#39;1&#39;</code>.</li> </ul>
Greedy; Math; String
Rust
impl Solution { pub fn maximum_odd_binary_number(s: String) -> String { let cnt = s.chars().filter(|&c| c == '1').count(); "1".repeat(cnt - 1) + &"0".repeat(s.len() - cnt) + "1" } }
2,864
Maximum Odd Binary Number
Easy
<p>You are given a <strong>binary</strong> string <code>s</code> that contains at least one <code>&#39;1&#39;</code>.</p> <p>You have to <strong>rearrange</strong> the bits in such a way that the resulting binary number is the <strong>maximum odd binary number</strong> that can be created from this combination.</p> <p>Return <em>a string representing the maximum odd binary number that can be created from the given combination.</em></p> <p><strong>Note </strong>that the resulting string <strong>can</strong> have leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;010&quot; <strong>Output:</strong> &quot;001&quot; <strong>Explanation:</strong> Because there is just one &#39;1&#39;, it must be in the last position. So the answer is &quot;001&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;0101&quot; <strong>Output:</strong> &quot;1001&quot; <strong>Explanation: </strong>One of the &#39;1&#39;s must be in the last position. The maximum number that can be made with the remaining digits is &quot;100&quot;. So the answer is &quot;1001&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>s</code> contains at least one <code>&#39;1&#39;</code>.</li> </ul>
Greedy; Math; String
TypeScript
function maximumOddBinaryNumber(s: string): string { const cnt = s.length - s.replace(/1/g, '').length; return '1'.repeat(cnt - 1) + '0'.repeat(s.length - cnt) + '1'; }
2,865
Beautiful Towers I
Medium
<p>You are given an array <code>heights</code> of <code>n</code> integers representing the number of bricks in <code>n</code> consecutive towers. Your task is to remove some bricks to form a <strong>mountain-shaped</strong> tower arrangement. In this arrangement, the tower heights are non-decreasing, reaching a maximum peak value with one or multiple consecutive towers and then non-increasing.</p> <p>Return the <strong>maximum possible sum</strong> of heights of a mountain-shaped tower arrangement.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [5,3,4,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights =&nbsp;[5,3,3,1,1]</code>, the peak is at index 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [6,5,3,9,2,7]</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights =&nbsp;[3,3,3,9,2,2]</code>, the peak is at index 3.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [3,2,5,5,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">18</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights = [2,2,5,5,2,2]</code>, the peak is at index 2 or 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == heights.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= heights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
C++
class Solution { public: long long maximumSumOfHeights(vector<int>& maxHeights) { long long ans = 0; int n = maxHeights.size(); for (int i = 0; i < n; ++i) { long long t = maxHeights[i]; int y = t; for (int j = i - 1; ~j; --j) { y = min(y, maxHeights[j]); t += y; } y = maxHeights[i]; for (int j = i + 1; j < n; ++j) { y = min(y, maxHeights[j]); t += y; } ans = max(ans, t); } return ans; } };
2,865
Beautiful Towers I
Medium
<p>You are given an array <code>heights</code> of <code>n</code> integers representing the number of bricks in <code>n</code> consecutive towers. Your task is to remove some bricks to form a <strong>mountain-shaped</strong> tower arrangement. In this arrangement, the tower heights are non-decreasing, reaching a maximum peak value with one or multiple consecutive towers and then non-increasing.</p> <p>Return the <strong>maximum possible sum</strong> of heights of a mountain-shaped tower arrangement.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [5,3,4,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights =&nbsp;[5,3,3,1,1]</code>, the peak is at index 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [6,5,3,9,2,7]</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights =&nbsp;[3,3,3,9,2,2]</code>, the peak is at index 3.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [3,2,5,5,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">18</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights = [2,2,5,5,2,2]</code>, the peak is at index 2 or 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == heights.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= heights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
Go
func maximumSumOfHeights(maxHeights []int) (ans int64) { n := len(maxHeights) for i, x := range maxHeights { y, t := x, x for j := i - 1; j >= 0; j-- { y = min(y, maxHeights[j]) t += y } y = x for j := i + 1; j < n; j++ { y = min(y, maxHeights[j]) t += y } ans = max(ans, int64(t)) } return }
2,865
Beautiful Towers I
Medium
<p>You are given an array <code>heights</code> of <code>n</code> integers representing the number of bricks in <code>n</code> consecutive towers. Your task is to remove some bricks to form a <strong>mountain-shaped</strong> tower arrangement. In this arrangement, the tower heights are non-decreasing, reaching a maximum peak value with one or multiple consecutive towers and then non-increasing.</p> <p>Return the <strong>maximum possible sum</strong> of heights of a mountain-shaped tower arrangement.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [5,3,4,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights =&nbsp;[5,3,3,1,1]</code>, the peak is at index 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [6,5,3,9,2,7]</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights =&nbsp;[3,3,3,9,2,2]</code>, the peak is at index 3.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [3,2,5,5,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">18</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights = [2,2,5,5,2,2]</code>, the peak is at index 2 or 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == heights.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= heights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
Java
class Solution { public long maximumSumOfHeights(List<Integer> maxHeights) { long ans = 0; int n = maxHeights.size(); for (int i = 0; i < n; ++i) { int y = maxHeights.get(i); long t = y; for (int j = i - 1; j >= 0; --j) { y = Math.min(y, maxHeights.get(j)); t += y; } y = maxHeights.get(i); for (int j = i + 1; j < n; ++j) { y = Math.min(y, maxHeights.get(j)); t += y; } ans = Math.max(ans, t); } return ans; } }
2,865
Beautiful Towers I
Medium
<p>You are given an array <code>heights</code> of <code>n</code> integers representing the number of bricks in <code>n</code> consecutive towers. Your task is to remove some bricks to form a <strong>mountain-shaped</strong> tower arrangement. In this arrangement, the tower heights are non-decreasing, reaching a maximum peak value with one or multiple consecutive towers and then non-increasing.</p> <p>Return the <strong>maximum possible sum</strong> of heights of a mountain-shaped tower arrangement.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [5,3,4,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights =&nbsp;[5,3,3,1,1]</code>, the peak is at index 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [6,5,3,9,2,7]</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights =&nbsp;[3,3,3,9,2,2]</code>, the peak is at index 3.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [3,2,5,5,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">18</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights = [2,2,5,5,2,2]</code>, the peak is at index 2 or 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == heights.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= heights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
Python
class Solution: def maximumSumOfHeights(self, maxHeights: List[int]) -> int: ans, n = 0, len(maxHeights) for i, x in enumerate(maxHeights): y = t = x for j in range(i - 1, -1, -1): y = min(y, maxHeights[j]) t += y y = x for j in range(i + 1, n): y = min(y, maxHeights[j]) t += y ans = max(ans, t) return ans
2,865
Beautiful Towers I
Medium
<p>You are given an array <code>heights</code> of <code>n</code> integers representing the number of bricks in <code>n</code> consecutive towers. Your task is to remove some bricks to form a <strong>mountain-shaped</strong> tower arrangement. In this arrangement, the tower heights are non-decreasing, reaching a maximum peak value with one or multiple consecutive towers and then non-increasing.</p> <p>Return the <strong>maximum possible sum</strong> of heights of a mountain-shaped tower arrangement.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [5,3,4,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights =&nbsp;[5,3,3,1,1]</code>, the peak is at index 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [6,5,3,9,2,7]</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights =&nbsp;[3,3,3,9,2,2]</code>, the peak is at index 3.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">heights = [3,2,5,5,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">18</span></p> <p><strong>Explanation:</strong></p> <p>We remove some bricks to make <code>heights = [2,2,5,5,2,2]</code>, the peak is at index 2 or 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == heights.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= heights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
TypeScript
function maximumSumOfHeights(maxHeights: number[]): number { let ans = 0; const n = maxHeights.length; for (let i = 0; i < n; ++i) { const x = maxHeights[i]; let [y, t] = [x, x]; for (let j = i - 1; ~j; --j) { y = Math.min(y, maxHeights[j]); t += y; } y = x; for (let j = i + 1; j < n; ++j) { y = Math.min(y, maxHeights[j]); t += y; } ans = Math.max(ans, t); } return ans; }
2,866
Beautiful Towers II
Medium
<p>You are given a <strong>0-indexed</strong> array <code>maxHeights</code> of <code>n</code> integers.</p> <p>You are tasked with building <code>n</code> towers in the coordinate line. The <code>i<sup>th</sup></code> tower is built at coordinate <code>i</code> and has a height of <code>heights[i]</code>.</p> <p>A configuration of towers is <strong>beautiful</strong> if the following conditions hold:</p> <ol> <li><code>1 &lt;= heights[i] &lt;= maxHeights[i]</code></li> <li><code>heights</code> is a <strong>mountain</strong> array.</li> </ol> <p>Array <code>heights</code> is a <strong>mountain</strong> if there exists an index <code>i</code> such that:</p> <ul> <li>For all <code>0 &lt; j &lt;= i</code>, <code>heights[j - 1] &lt;= heights[j]</code></li> <li>For all <code>i &lt;= k &lt; n - 1</code>, <code>heights[k + 1] &lt;= heights[k]</code></li> </ul> <p>Return <em>the <strong>maximum possible sum of heights</strong> of a beautiful configuration of towers</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> maxHeights = [5,3,4,1,1] <strong>Output:</strong> 13 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [5,3,3,1,1]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 0. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 13.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> maxHeights = [6,5,3,9,2,7] <strong>Output:</strong> 22 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [3,3,3,9,2,2]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 3. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 22.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maxHeights = [3,2,5,5,2,3] <strong>Output:</strong> 18 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [2,2,5,5,2,2]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 2. Note that, for this configuration, i = 3 can also be considered a peak. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 18. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == maxHeights.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= maxHeights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
C++
class Solution { public: long long maximumSumOfHeights(vector<int>& maxHeights) { int n = maxHeights.size(); stack<int> stk; vector<int> left(n, -1); vector<int> right(n, n); for (int i = 0; i < n; ++i) { int x = maxHeights[i]; while (!stk.empty() && maxHeights[stk.top()] > x) { stk.pop(); } if (!stk.empty()) { left[i] = stk.top(); } stk.push(i); } stk = stack<int>(); for (int i = n - 1; ~i; --i) { int x = maxHeights[i]; while (!stk.empty() && maxHeights[stk.top()] >= x) { stk.pop(); } if (!stk.empty()) { right[i] = stk.top(); } stk.push(i); } long long f[n], g[n]; for (int i = 0; i < n; ++i) { int x = maxHeights[i]; if (i && x >= maxHeights[i - 1]) { f[i] = f[i - 1] + x; } else { int j = left[i]; f[i] = 1LL * x * (i - j) + (j != -1 ? f[j] : 0); } } for (int i = n - 1; ~i; --i) { int x = maxHeights[i]; if (i < n - 1 && x >= maxHeights[i + 1]) { g[i] = g[i + 1] + x; } else { int j = right[i]; g[i] = 1LL * x * (j - i) + (j != n ? g[j] : 0); } } long long ans = 0; for (int i = 0; i < n; ++i) { ans = max(ans, f[i] + g[i] - maxHeights[i]); } return ans; } };
2,866
Beautiful Towers II
Medium
<p>You are given a <strong>0-indexed</strong> array <code>maxHeights</code> of <code>n</code> integers.</p> <p>You are tasked with building <code>n</code> towers in the coordinate line. The <code>i<sup>th</sup></code> tower is built at coordinate <code>i</code> and has a height of <code>heights[i]</code>.</p> <p>A configuration of towers is <strong>beautiful</strong> if the following conditions hold:</p> <ol> <li><code>1 &lt;= heights[i] &lt;= maxHeights[i]</code></li> <li><code>heights</code> is a <strong>mountain</strong> array.</li> </ol> <p>Array <code>heights</code> is a <strong>mountain</strong> if there exists an index <code>i</code> such that:</p> <ul> <li>For all <code>0 &lt; j &lt;= i</code>, <code>heights[j - 1] &lt;= heights[j]</code></li> <li>For all <code>i &lt;= k &lt; n - 1</code>, <code>heights[k + 1] &lt;= heights[k]</code></li> </ul> <p>Return <em>the <strong>maximum possible sum of heights</strong> of a beautiful configuration of towers</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> maxHeights = [5,3,4,1,1] <strong>Output:</strong> 13 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [5,3,3,1,1]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 0. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 13.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> maxHeights = [6,5,3,9,2,7] <strong>Output:</strong> 22 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [3,3,3,9,2,2]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 3. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 22.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maxHeights = [3,2,5,5,2,3] <strong>Output:</strong> 18 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [2,2,5,5,2,2]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 2. Note that, for this configuration, i = 3 can also be considered a peak. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 18. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == maxHeights.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= maxHeights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
Go
func maximumSumOfHeights(maxHeights []int) (ans int64) { n := len(maxHeights) stk := []int{} left := make([]int, n) right := make([]int, n) for i := range left { left[i] = -1 right[i] = n } for i, x := range maxHeights { for len(stk) > 0 && maxHeights[stk[len(stk)-1]] > x { stk = stk[:len(stk)-1] } if len(stk) > 0 { left[i] = stk[len(stk)-1] } stk = append(stk, i) } stk = []int{} for i := n - 1; i >= 0; i-- { x := maxHeights[i] for len(stk) > 0 && maxHeights[stk[len(stk)-1]] >= x { stk = stk[:len(stk)-1] } if len(stk) > 0 { right[i] = stk[len(stk)-1] } stk = append(stk, i) } f := make([]int64, n) g := make([]int64, n) for i, x := range maxHeights { if i > 0 && x >= maxHeights[i-1] { f[i] = f[i-1] + int64(x) } else { j := left[i] f[i] = int64(x) * int64(i-j) if j != -1 { f[i] += f[j] } } } for i := n - 1; i >= 0; i-- { x := maxHeights[i] if i < n-1 && x >= maxHeights[i+1] { g[i] = g[i+1] + int64(x) } else { j := right[i] g[i] = int64(x) * int64(j-i) if j != n { g[i] += g[j] } } } for i, x := range maxHeights { ans = max(ans, f[i]+g[i]-int64(x)) } return }
2,866
Beautiful Towers II
Medium
<p>You are given a <strong>0-indexed</strong> array <code>maxHeights</code> of <code>n</code> integers.</p> <p>You are tasked with building <code>n</code> towers in the coordinate line. The <code>i<sup>th</sup></code> tower is built at coordinate <code>i</code> and has a height of <code>heights[i]</code>.</p> <p>A configuration of towers is <strong>beautiful</strong> if the following conditions hold:</p> <ol> <li><code>1 &lt;= heights[i] &lt;= maxHeights[i]</code></li> <li><code>heights</code> is a <strong>mountain</strong> array.</li> </ol> <p>Array <code>heights</code> is a <strong>mountain</strong> if there exists an index <code>i</code> such that:</p> <ul> <li>For all <code>0 &lt; j &lt;= i</code>, <code>heights[j - 1] &lt;= heights[j]</code></li> <li>For all <code>i &lt;= k &lt; n - 1</code>, <code>heights[k + 1] &lt;= heights[k]</code></li> </ul> <p>Return <em>the <strong>maximum possible sum of heights</strong> of a beautiful configuration of towers</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> maxHeights = [5,3,4,1,1] <strong>Output:</strong> 13 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [5,3,3,1,1]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 0. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 13.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> maxHeights = [6,5,3,9,2,7] <strong>Output:</strong> 22 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [3,3,3,9,2,2]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 3. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 22.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maxHeights = [3,2,5,5,2,3] <strong>Output:</strong> 18 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [2,2,5,5,2,2]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 2. Note that, for this configuration, i = 3 can also be considered a peak. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 18. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == maxHeights.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= maxHeights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
Java
class Solution { public long maximumSumOfHeights(List<Integer> maxHeights) { int n = maxHeights.size(); Deque<Integer> stk = new ArrayDeque<>(); int[] left = new int[n]; int[] right = new int[n]; Arrays.fill(left, -1); Arrays.fill(right, n); for (int i = 0; i < n; ++i) { int x = maxHeights.get(i); while (!stk.isEmpty() && maxHeights.get(stk.peek()) > x) { stk.pop(); } if (!stk.isEmpty()) { left[i] = stk.peek(); } stk.push(i); } stk.clear(); for (int i = n - 1; i >= 0; --i) { int x = maxHeights.get(i); while (!stk.isEmpty() && maxHeights.get(stk.peek()) >= x) { stk.pop(); } if (!stk.isEmpty()) { right[i] = stk.peek(); } stk.push(i); } long[] f = new long[n]; long[] g = new long[n]; for (int i = 0; i < n; ++i) { int x = maxHeights.get(i); if (i > 0 && x >= maxHeights.get(i - 1)) { f[i] = f[i - 1] + x; } else { int j = left[i]; f[i] = 1L * x * (i - j) + (j >= 0 ? f[j] : 0); } } for (int i = n - 1; i >= 0; --i) { int x = maxHeights.get(i); if (i < n - 1 && x >= maxHeights.get(i + 1)) { g[i] = g[i + 1] + x; } else { int j = right[i]; g[i] = 1L * x * (j - i) + (j < n ? g[j] : 0); } } long ans = 0; for (int i = 0; i < n; ++i) { ans = Math.max(ans, f[i] + g[i] - maxHeights.get(i)); } return ans; } }
2,866
Beautiful Towers II
Medium
<p>You are given a <strong>0-indexed</strong> array <code>maxHeights</code> of <code>n</code> integers.</p> <p>You are tasked with building <code>n</code> towers in the coordinate line. The <code>i<sup>th</sup></code> tower is built at coordinate <code>i</code> and has a height of <code>heights[i]</code>.</p> <p>A configuration of towers is <strong>beautiful</strong> if the following conditions hold:</p> <ol> <li><code>1 &lt;= heights[i] &lt;= maxHeights[i]</code></li> <li><code>heights</code> is a <strong>mountain</strong> array.</li> </ol> <p>Array <code>heights</code> is a <strong>mountain</strong> if there exists an index <code>i</code> such that:</p> <ul> <li>For all <code>0 &lt; j &lt;= i</code>, <code>heights[j - 1] &lt;= heights[j]</code></li> <li>For all <code>i &lt;= k &lt; n - 1</code>, <code>heights[k + 1] &lt;= heights[k]</code></li> </ul> <p>Return <em>the <strong>maximum possible sum of heights</strong> of a beautiful configuration of towers</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> maxHeights = [5,3,4,1,1] <strong>Output:</strong> 13 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [5,3,3,1,1]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 0. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 13.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> maxHeights = [6,5,3,9,2,7] <strong>Output:</strong> 22 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [3,3,3,9,2,2]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 3. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 22.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maxHeights = [3,2,5,5,2,3] <strong>Output:</strong> 18 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [2,2,5,5,2,2]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 2. Note that, for this configuration, i = 3 can also be considered a peak. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 18. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == maxHeights.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= maxHeights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
Python
class Solution: def maximumSumOfHeights(self, maxHeights: List[int]) -> int: n = len(maxHeights) stk = [] left = [-1] * n for i, x in enumerate(maxHeights): while stk and maxHeights[stk[-1]] > x: stk.pop() if stk: left[i] = stk[-1] stk.append(i) stk = [] right = [n] * n for i in range(n - 1, -1, -1): x = maxHeights[i] while stk and maxHeights[stk[-1]] >= x: stk.pop() if stk: right[i] = stk[-1] stk.append(i) f = [0] * n for i, x in enumerate(maxHeights): if i and x >= maxHeights[i - 1]: f[i] = f[i - 1] + x else: j = left[i] f[i] = x * (i - j) + (f[j] if j != -1 else 0) g = [0] * n for i in range(n - 1, -1, -1): if i < n - 1 and maxHeights[i] >= maxHeights[i + 1]: g[i] = g[i + 1] + maxHeights[i] else: j = right[i] g[i] = maxHeights[i] * (j - i) + (g[j] if j != n else 0) return max(a + b - c for a, b, c in zip(f, g, maxHeights))
2,866
Beautiful Towers II
Medium
<p>You are given a <strong>0-indexed</strong> array <code>maxHeights</code> of <code>n</code> integers.</p> <p>You are tasked with building <code>n</code> towers in the coordinate line. The <code>i<sup>th</sup></code> tower is built at coordinate <code>i</code> and has a height of <code>heights[i]</code>.</p> <p>A configuration of towers is <strong>beautiful</strong> if the following conditions hold:</p> <ol> <li><code>1 &lt;= heights[i] &lt;= maxHeights[i]</code></li> <li><code>heights</code> is a <strong>mountain</strong> array.</li> </ol> <p>Array <code>heights</code> is a <strong>mountain</strong> if there exists an index <code>i</code> such that:</p> <ul> <li>For all <code>0 &lt; j &lt;= i</code>, <code>heights[j - 1] &lt;= heights[j]</code></li> <li>For all <code>i &lt;= k &lt; n - 1</code>, <code>heights[k + 1] &lt;= heights[k]</code></li> </ul> <p>Return <em>the <strong>maximum possible sum of heights</strong> of a beautiful configuration of towers</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> maxHeights = [5,3,4,1,1] <strong>Output:</strong> 13 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [5,3,3,1,1]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 0. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 13.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> maxHeights = [6,5,3,9,2,7] <strong>Output:</strong> 22 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [3,3,3,9,2,2]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 3. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 22.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> maxHeights = [3,2,5,5,2,3] <strong>Output:</strong> 18 <strong>Explanation:</strong> One beautiful configuration with a maximum sum is heights = [2,2,5,5,2,2]. This configuration is beautiful since: - 1 &lt;= heights[i] &lt;= maxHeights[i] - heights is a mountain of peak i = 2. Note that, for this configuration, i = 3 can also be considered a peak. It can be shown that there exists no other beautiful configuration with a sum of heights greater than 18. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == maxHeights.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= maxHeights[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Monotonic Stack
TypeScript
function maximumSumOfHeights(maxHeights: number[]): number { const n = maxHeights.length; const stk: number[] = []; const left: number[] = Array(n).fill(-1); const right: number[] = Array(n).fill(n); for (let i = 0; i < n; ++i) { const x = maxHeights[i]; while (stk.length && maxHeights[stk.at(-1)] > x) { stk.pop(); } if (stk.length) { left[i] = stk.at(-1); } stk.push(i); } stk.length = 0; for (let i = n - 1; ~i; --i) { const x = maxHeights[i]; while (stk.length && maxHeights[stk.at(-1)] >= x) { stk.pop(); } if (stk.length) { right[i] = stk.at(-1); } stk.push(i); } const f: number[] = Array(n).fill(0); const g: number[] = Array(n).fill(0); for (let i = 0; i < n; ++i) { const x = maxHeights[i]; if (i && x >= maxHeights[i - 1]) { f[i] = f[i - 1] + x; } else { const j = left[i]; f[i] = x * (i - j) + (j >= 0 ? f[j] : 0); } } for (let i = n - 1; ~i; --i) { const x = maxHeights[i]; if (i + 1 < n && x >= maxHeights[i + 1]) { g[i] = g[i + 1] + x; } else { const j = right[i]; g[i] = x * (j - i) + (j < n ? g[j] : 0); } } let ans = 0; for (let i = 0; i < n; ++i) { ans = Math.max(ans, f[i] + g[i] - maxHeights[i]); } return ans; }
2,867
Count Valid Paths in a Tree
Hard
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>1</code> to <code>n</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree.</p> <p>Return <em>the <strong>number of valid paths</strong> in the tree</em>.</p> <p>A path <code>(a, b)</code> is <strong>valid</strong> if there exists <strong>exactly one</strong> prime number among the node labels in the path from <code>a</code> to <code>b</code>.</p> <p><strong>Note</strong> that:</p> <ul> <li>The path <code>(a, b)</code> is a sequence of <strong>distinct</strong> nodes starting with node <code>a</code> and ending with node <code>b</code> such that every two adjacent nodes in the sequence share an edge in the tree.</li> <li>Path <code>(a, b)</code> and path <code>(b, a)</code> are considered the <strong>same</strong> and counted only <strong>once</strong>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2867.Count%20Valid%20Paths%20in%20a%20Tree/images/example1.png" style="width: 440px; height: 357px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[1,2],[1,3],[2,4],[2,5]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pairs with exactly one prime number on the path between them are: - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (2, 4) since the path from 2 to 4 contains prime number 2. It can be shown that there are only 4 valid paths. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2867.Count%20Valid%20Paths%20in%20a%20Tree/images/example2.png" style="width: 488px; height: 384px;" /> <pre> <strong>Input:</strong> n = 6, edges = [[1,2],[1,3],[2,4],[3,5],[3,6]] <strong>Output:</strong> 6 <strong>Explanation:</strong> The pairs with exactly one prime number on the path between them are: - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (1, 6) since the path from 1 to 6 contains prime number 3. - (2, 4) since the path from 2 to 4 contains prime number 2. - (3, 6) since the path from 3 to 6 contains prime number 3. It can be shown that there are only 6 valid paths. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>1 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n</code></li> <li>The input is generated such that <code>edges</code> represent a valid tree.</li> </ul>
Tree; Depth-First Search; Math; Dynamic Programming; Number Theory
C++
const int mx = 1e5 + 10; bool prime[mx + 1]; int init = []() { for (int i = 2; i <= mx; ++i) prime[i] = true; for (int i = 2; i <= mx; ++i) { if (prime[i]) { for (int j = i + i; j <= mx; j += i) { prime[j] = false; } } } return 0; }(); class UnionFind { public: UnionFind(int n) { p = vector<int>(n); size = vector<int>(n, 1); iota(p.begin(), p.end(), 0); } bool unite(int a, int b) { int pa = find(a), pb = find(b); if (pa == pb) { return false; } if (size[pa] > size[pb]) { p[pb] = pa; size[pa] += size[pb]; } else { p[pa] = pb; size[pb] += size[pa]; } return true; } int find(int x) { if (p[x] != x) { p[x] = find(p[x]); } return p[x]; } int getSize(int x) { return size[find(x)]; } private: vector<int> p, size; }; class Solution { public: long long countPaths(int n, vector<vector<int>>& edges) { vector<int> g[n + 1]; UnionFind uf(n + 1); for (auto& e : edges) { int u = e[0], v = e[1]; g[u].push_back(v); g[v].push_back(u); if (!prime[u] && !prime[v]) { uf.unite(u, v); } } long long ans = 0; for (int i = 1; i <= n; ++i) { if (prime[i]) { long long t = 0; for (int j : g[i]) { if (!prime[j]) { long long cnt = uf.getSize(j); ans += cnt; ans += cnt * t; t += cnt; } } } } return ans; } };
2,867
Count Valid Paths in a Tree
Hard
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>1</code> to <code>n</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree.</p> <p>Return <em>the <strong>number of valid paths</strong> in the tree</em>.</p> <p>A path <code>(a, b)</code> is <strong>valid</strong> if there exists <strong>exactly one</strong> prime number among the node labels in the path from <code>a</code> to <code>b</code>.</p> <p><strong>Note</strong> that:</p> <ul> <li>The path <code>(a, b)</code> is a sequence of <strong>distinct</strong> nodes starting with node <code>a</code> and ending with node <code>b</code> such that every two adjacent nodes in the sequence share an edge in the tree.</li> <li>Path <code>(a, b)</code> and path <code>(b, a)</code> are considered the <strong>same</strong> and counted only <strong>once</strong>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2867.Count%20Valid%20Paths%20in%20a%20Tree/images/example1.png" style="width: 440px; height: 357px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[1,2],[1,3],[2,4],[2,5]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pairs with exactly one prime number on the path between them are: - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (2, 4) since the path from 2 to 4 contains prime number 2. It can be shown that there are only 4 valid paths. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2867.Count%20Valid%20Paths%20in%20a%20Tree/images/example2.png" style="width: 488px; height: 384px;" /> <pre> <strong>Input:</strong> n = 6, edges = [[1,2],[1,3],[2,4],[3,5],[3,6]] <strong>Output:</strong> 6 <strong>Explanation:</strong> The pairs with exactly one prime number on the path between them are: - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (1, 6) since the path from 1 to 6 contains prime number 3. - (2, 4) since the path from 2 to 4 contains prime number 2. - (3, 6) since the path from 3 to 6 contains prime number 3. It can be shown that there are only 6 valid paths. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>1 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n</code></li> <li>The input is generated such that <code>edges</code> represent a valid tree.</li> </ul>
Tree; Depth-First Search; Math; Dynamic Programming; Number Theory
Go
const mx int = 1e5 + 10 var prime [mx]bool func init() { for i := 2; i < mx; i++ { prime[i] = true } for i := 2; i < mx; i++ { if prime[i] { for j := i + i; j < mx; j += i { prime[j] = false } } } } type unionFind struct { p, size []int } func newUnionFind(n int) *unionFind { p := make([]int, n) size := make([]int, n) for i := range p { p[i] = i size[i] = 1 } return &unionFind{p, size} } func (uf *unionFind) find(x int) int { if uf.p[x] != x { uf.p[x] = uf.find(uf.p[x]) } return uf.p[x] } func (uf *unionFind) union(a, b int) bool { pa, pb := uf.find(a), uf.find(b) if pa == pb { return false } if uf.size[pa] > uf.size[pb] { uf.p[pb] = pa uf.size[pa] += uf.size[pb] } else { uf.p[pa] = pb uf.size[pb] += uf.size[pa] } return true } func (uf *unionFind) getSize(x int) int { return uf.size[uf.find(x)] } func countPaths(n int, edges [][]int) (ans int64) { uf := newUnionFind(n + 1) g := make([][]int, n+1) for _, e := range edges { u, v := e[0], e[1] g[u] = append(g[u], v) g[v] = append(g[v], u) if !prime[u] && !prime[v] { uf.union(u, v) } } for i := 1; i <= n; i++ { if prime[i] { t := 0 for _, j := range g[i] { if !prime[j] { cnt := uf.getSize(j) ans += int64(cnt + cnt*t) t += cnt } } } } return }
2,867
Count Valid Paths in a Tree
Hard
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>1</code> to <code>n</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree.</p> <p>Return <em>the <strong>number of valid paths</strong> in the tree</em>.</p> <p>A path <code>(a, b)</code> is <strong>valid</strong> if there exists <strong>exactly one</strong> prime number among the node labels in the path from <code>a</code> to <code>b</code>.</p> <p><strong>Note</strong> that:</p> <ul> <li>The path <code>(a, b)</code> is a sequence of <strong>distinct</strong> nodes starting with node <code>a</code> and ending with node <code>b</code> such that every two adjacent nodes in the sequence share an edge in the tree.</li> <li>Path <code>(a, b)</code> and path <code>(b, a)</code> are considered the <strong>same</strong> and counted only <strong>once</strong>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2867.Count%20Valid%20Paths%20in%20a%20Tree/images/example1.png" style="width: 440px; height: 357px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[1,2],[1,3],[2,4],[2,5]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pairs with exactly one prime number on the path between them are: - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (2, 4) since the path from 2 to 4 contains prime number 2. It can be shown that there are only 4 valid paths. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2867.Count%20Valid%20Paths%20in%20a%20Tree/images/example2.png" style="width: 488px; height: 384px;" /> <pre> <strong>Input:</strong> n = 6, edges = [[1,2],[1,3],[2,4],[3,5],[3,6]] <strong>Output:</strong> 6 <strong>Explanation:</strong> The pairs with exactly one prime number on the path between them are: - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (1, 6) since the path from 1 to 6 contains prime number 3. - (2, 4) since the path from 2 to 4 contains prime number 2. - (3, 6) since the path from 3 to 6 contains prime number 3. It can be shown that there are only 6 valid paths. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>1 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n</code></li> <li>The input is generated such that <code>edges</code> represent a valid tree.</li> </ul>
Tree; Depth-First Search; Math; Dynamic Programming; Number Theory
Java
class PrimeTable { private final boolean[] prime; public PrimeTable(int n) { prime = new boolean[n + 1]; Arrays.fill(prime, true); prime[0] = false; prime[1] = false; for (int i = 2; i <= n; ++i) { if (prime[i]) { for (int j = i + i; j <= n; j += i) { prime[j] = false; } } } } public boolean isPrime(int x) { return prime[x]; } } class UnionFind { private final int[] p; private final int[] size; public UnionFind(int n) { p = new int[n]; size = new int[n]; for (int i = 0; i < n; ++i) { p[i] = i; size[i] = 1; } } public int find(int x) { if (p[x] != x) { p[x] = find(p[x]); } return p[x]; } public boolean union(int a, int b) { int pa = find(a), pb = find(b); if (pa == pb) { return false; } if (size[pa] > size[pb]) { p[pb] = pa; size[pa] += size[pb]; } else { p[pa] = pb; size[pb] += size[pa]; } return true; } public int size(int x) { return size[find(x)]; } } class Solution { private static final PrimeTable PT = new PrimeTable(100010); public long countPaths(int n, int[][] edges) { List<Integer>[] g = new List[n + 1]; Arrays.setAll(g, i -> new ArrayList<>()); UnionFind uf = new UnionFind(n + 1); for (int[] e : edges) { int u = e[0], v = e[1]; g[u].add(v); g[v].add(u); if (!PT.isPrime(u) && !PT.isPrime(v)) { uf.union(u, v); } } long ans = 0; for (int i = 1; i <= n; ++i) { if (PT.isPrime(i)) { long t = 0; for (int j : g[i]) { if (!PT.isPrime(j)) { long cnt = uf.size(j); ans += cnt; ans += cnt * t; t += cnt; } } } } return ans; } }
2,867
Count Valid Paths in a Tree
Hard
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>1</code> to <code>n</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree.</p> <p>Return <em>the <strong>number of valid paths</strong> in the tree</em>.</p> <p>A path <code>(a, b)</code> is <strong>valid</strong> if there exists <strong>exactly one</strong> prime number among the node labels in the path from <code>a</code> to <code>b</code>.</p> <p><strong>Note</strong> that:</p> <ul> <li>The path <code>(a, b)</code> is a sequence of <strong>distinct</strong> nodes starting with node <code>a</code> and ending with node <code>b</code> such that every two adjacent nodes in the sequence share an edge in the tree.</li> <li>Path <code>(a, b)</code> and path <code>(b, a)</code> are considered the <strong>same</strong> and counted only <strong>once</strong>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2867.Count%20Valid%20Paths%20in%20a%20Tree/images/example1.png" style="width: 440px; height: 357px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[1,2],[1,3],[2,4],[2,5]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pairs with exactly one prime number on the path between them are: - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (2, 4) since the path from 2 to 4 contains prime number 2. It can be shown that there are only 4 valid paths. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2867.Count%20Valid%20Paths%20in%20a%20Tree/images/example2.png" style="width: 488px; height: 384px;" /> <pre> <strong>Input:</strong> n = 6, edges = [[1,2],[1,3],[2,4],[3,5],[3,6]] <strong>Output:</strong> 6 <strong>Explanation:</strong> The pairs with exactly one prime number on the path between them are: - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (1, 6) since the path from 1 to 6 contains prime number 3. - (2, 4) since the path from 2 to 4 contains prime number 2. - (3, 6) since the path from 3 to 6 contains prime number 3. It can be shown that there are only 6 valid paths. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>1 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n</code></li> <li>The input is generated such that <code>edges</code> represent a valid tree.</li> </ul>
Tree; Depth-First Search; Math; Dynamic Programming; Number Theory
Python
class UnionFind: def __init__(self, n): self.p = list(range(n)) self.size = [1] * n def find(self, x): if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, a, b): pa, pb = self.find(a), self.find(b) if pa == pb: return False if self.size[pa] > self.size[pb]: self.p[pb] = pa self.size[pa] += self.size[pb] else: self.p[pa] = pb self.size[pb] += self.size[pa] return True mx = 10**5 + 10 prime = [True] * (mx + 1) prime[0] = prime[1] = False for i in range(2, mx + 1): if prime[i]: for j in range(i * i, mx + 1, i): prime[j] = False class Solution: def countPaths(self, n: int, edges: List[List[int]]) -> int: g = [[] for _ in range(n + 1)] uf = UnionFind(n + 1) for u, v in edges: g[u].append(v) g[v].append(u) if prime[u] + prime[v] == 0: uf.union(u, v) ans = 0 for i in range(1, n + 1): if prime[i]: t = 0 for j in g[i]: if not prime[j]: cnt = uf.size[uf.find(j)] ans += cnt ans += t * cnt t += cnt return ans
2,867
Count Valid Paths in a Tree
Hard
<p>There is an undirected tree with <code>n</code> nodes labeled from <code>1</code> to <code>n</code>. You are given the integer <code>n</code> and a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> indicates that there is an edge between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the tree.</p> <p>Return <em>the <strong>number of valid paths</strong> in the tree</em>.</p> <p>A path <code>(a, b)</code> is <strong>valid</strong> if there exists <strong>exactly one</strong> prime number among the node labels in the path from <code>a</code> to <code>b</code>.</p> <p><strong>Note</strong> that:</p> <ul> <li>The path <code>(a, b)</code> is a sequence of <strong>distinct</strong> nodes starting with node <code>a</code> and ending with node <code>b</code> such that every two adjacent nodes in the sequence share an edge in the tree.</li> <li>Path <code>(a, b)</code> and path <code>(b, a)</code> are considered the <strong>same</strong> and counted only <strong>once</strong>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2867.Count%20Valid%20Paths%20in%20a%20Tree/images/example1.png" style="width: 440px; height: 357px;" /> <pre> <strong>Input:</strong> n = 5, edges = [[1,2],[1,3],[2,4],[2,5]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pairs with exactly one prime number on the path between them are: - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (2, 4) since the path from 2 to 4 contains prime number 2. It can be shown that there are only 4 valid paths. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2800-2899/2867.Count%20Valid%20Paths%20in%20a%20Tree/images/example2.png" style="width: 488px; height: 384px;" /> <pre> <strong>Input:</strong> n = 6, edges = [[1,2],[1,3],[2,4],[3,5],[3,6]] <strong>Output:</strong> 6 <strong>Explanation:</strong> The pairs with exactly one prime number on the path between them are: - (1, 2) since the path from 1 to 2 contains prime number 2. - (1, 3) since the path from 1 to 3 contains prime number 3. - (1, 4) since the path from 1 to 4 contains prime number 2. - (1, 6) since the path from 1 to 6 contains prime number 3. - (2, 4) since the path from 2 to 4 contains prime number 2. - (3, 6) since the path from 3 to 6 contains prime number 3. It can be shown that there are only 6 valid paths. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>1 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n</code></li> <li>The input is generated such that <code>edges</code> represent a valid tree.</li> </ul>
Tree; Depth-First Search; Math; Dynamic Programming; Number Theory
TypeScript
const mx = 100010; const prime = Array(mx).fill(true); prime[0] = prime[1] = false; for (let i = 2; i <= mx; ++i) { if (prime[i]) { for (let j = i + i; j <= mx; j += i) { prime[j] = false; } } } class UnionFind { p: number[]; size: number[]; constructor(n: number) { this.p = Array(n) .fill(0) .map((_, i) => i); this.size = Array(n).fill(1); } find(x: number): number { if (this.p[x] !== x) { this.p[x] = this.find(this.p[x]); } return this.p[x]; } union(a: number, b: number): boolean { const [pa, pb] = [this.find(a), this.find(b)]; if (pa === pb) { return false; } if (this.size[pa] > this.size[pb]) { this.p[pb] = pa; this.size[pa] += this.size[pb]; } else { this.p[pa] = pb; this.size[pb] += this.size[pa]; } return true; } getSize(x: number): number { return this.size[this.find(x)]; } } function countPaths(n: number, edges: number[][]): number { const uf = new UnionFind(n + 1); const g: number[][] = Array(n + 1) .fill(0) .map(() => []); for (const [u, v] of edges) { g[u].push(v); g[v].push(u); if (!prime[u] && !prime[v]) { uf.union(u, v); } } let ans = 0; for (let i = 1; i <= n; ++i) { if (prime[i]) { let t = 0; for (let j of g[i]) { if (!prime[j]) { const cnt = uf.getSize(j); ans += cnt + t * cnt; t += cnt; } } } } return ans; }
2,868
The Wording Game
Hard
<p>Alice and Bob each have a <strong>lexicographically sorted</strong> array of strings named <code>a</code> and <code>b</code> respectively.</p> <p>They are playing a wording game with the following rules:</p> <ul> <li>On each turn, the current player should play a word from their list such that the new word is <strong>closely greater</strong> than the last played word; then it&#39;s the other player&#39;s turn.</li> <li>If a player can&#39;t play a word on their turn, they lose.</li> </ul> <p>Alice starts the game by playing her <strong>lexicographically </strong><strong>smallest </strong>word.</p> <p>Given <code>a</code> and <code>b</code>, return <code>true</code> <em>if Alice can win knowing that both players play their best, and</em> <code>false</code> <em>otherwise.</em></p> <p>A word <code>w</code> is <strong>closely greater</strong> than a word <code>z</code> if the following conditions are met:</p> <ul> <li><code>w</code> is <strong>lexicographically greater</strong> than <code>z</code>.</li> <li>If <code>w<sub>1</sub></code> is the first letter of <code>w</code> and <code>z<sub>1</sub></code> is the first letter of <code>z</code>, <code>w<sub>1</sub></code> should either be <strong>equal</strong> to <code>z<sub>1</sub></code> or be the <strong>letter after</strong> <code>z<sub>1</sub></code> in the alphabet.</li> <li>For example, the word <code>&quot;care&quot;</code> is closely greater than <code>&quot;book&quot;</code> and <code>&quot;car&quot;</code>, but is not closely greater than <code>&quot;ant&quot;</code> or <code>&quot;cook&quot;</code>.</li> </ul> <p>A string <code>s</code> is <b>lexicographically </b><strong>greater</strong> than a string <code>t</code> if in the first position where <code>s</code> and <code>t</code> differ, string <code>s</code> has a letter that appears later in the alphabet than the corresponding letter in <code>t</code>. If the first <code>min(s.length, t.length)</code> characters do not differ, then the longer string is the lexicographically greater one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = [&quot;avokado&quot;,&quot;dabar&quot;], b = [&quot;brazil&quot;] <strong>Output:</strong> false <strong>Explanation:</strong> Alice must start the game by playing the word &quot;avokado&quot; since it&#39;s her smallest word, then Bob plays his only word, &quot;brazil&quot;, which he can play because its first letter, &#39;b&#39;, is the letter after Alice&#39;s word&#39;s first letter, &#39;a&#39;. Alice can&#39;t play a word since the first letter of the only word left is not equal to &#39;b&#39; or the letter after &#39;b&#39;, &#39;c&#39;. So, Alice loses, and the game ends.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = [&quot;ananas&quot;,&quot;atlas&quot;,&quot;banana&quot;], b = [&quot;albatros&quot;,&quot;cikla&quot;,&quot;nogomet&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> Alice must start the game by playing the word &quot;ananas&quot;. Bob can&#39;t play a word since the only word he has that starts with the letter &#39;a&#39; or &#39;b&#39; is &quot;albatros&quot;, which is smaller than Alice&#39;s word. So Alice wins, and the game ends.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = [&quot;hrvatska&quot;,&quot;zastava&quot;], b = [&quot;bijeli&quot;,&quot;galeb&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> Alice must start the game by playing the word &quot;hrvatska&quot;. Bob can&#39;t play a word since the first letter of both of his words are smaller than the first letter of Alice&#39;s word, &#39;h&#39;. So Alice wins, and the game ends. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length &lt;= 10<sup>5</sup></code></li> <li><code>a[i]</code> and <code>b[i]</code> consist only of lowercase English letters.</li> <li><code>a</code> and <code>b</code> are <strong>lexicographically sorted</strong>.</li> <li>All the words in <code>a</code> and <code>b</code> combined are <strong>distinct</strong>.</li> <li>The sum of the lengths of all the words in <code>a</code> and <code>b</code> combined does not exceed <code>10<sup>6</sup></code>.</li> </ul>
Greedy; Array; Math; Two Pointers; String; Game Theory
C++
class Solution { public: bool canAliceWin(vector<string>& a, vector<string>& b) { int i = 1, j = 0, k = 1; string w = a[0]; while (1) { if (k) { if (j == b.size()) { return true; } if ((b[j][0] == w[0] && w < b[j]) || b[j][0] - w[0] == 1) { w = b[j]; k ^= 1; } ++j; } else { if (i == a.size()) { return false; } if ((a[i][0] == w[0] && w < a[i]) || a[i][0] - w[0] == 1) { w = a[i]; k ^= 1; } ++i; } } } };
2,868
The Wording Game
Hard
<p>Alice and Bob each have a <strong>lexicographically sorted</strong> array of strings named <code>a</code> and <code>b</code> respectively.</p> <p>They are playing a wording game with the following rules:</p> <ul> <li>On each turn, the current player should play a word from their list such that the new word is <strong>closely greater</strong> than the last played word; then it&#39;s the other player&#39;s turn.</li> <li>If a player can&#39;t play a word on their turn, they lose.</li> </ul> <p>Alice starts the game by playing her <strong>lexicographically </strong><strong>smallest </strong>word.</p> <p>Given <code>a</code> and <code>b</code>, return <code>true</code> <em>if Alice can win knowing that both players play their best, and</em> <code>false</code> <em>otherwise.</em></p> <p>A word <code>w</code> is <strong>closely greater</strong> than a word <code>z</code> if the following conditions are met:</p> <ul> <li><code>w</code> is <strong>lexicographically greater</strong> than <code>z</code>.</li> <li>If <code>w<sub>1</sub></code> is the first letter of <code>w</code> and <code>z<sub>1</sub></code> is the first letter of <code>z</code>, <code>w<sub>1</sub></code> should either be <strong>equal</strong> to <code>z<sub>1</sub></code> or be the <strong>letter after</strong> <code>z<sub>1</sub></code> in the alphabet.</li> <li>For example, the word <code>&quot;care&quot;</code> is closely greater than <code>&quot;book&quot;</code> and <code>&quot;car&quot;</code>, but is not closely greater than <code>&quot;ant&quot;</code> or <code>&quot;cook&quot;</code>.</li> </ul> <p>A string <code>s</code> is <b>lexicographically </b><strong>greater</strong> than a string <code>t</code> if in the first position where <code>s</code> and <code>t</code> differ, string <code>s</code> has a letter that appears later in the alphabet than the corresponding letter in <code>t</code>. If the first <code>min(s.length, t.length)</code> characters do not differ, then the longer string is the lexicographically greater one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = [&quot;avokado&quot;,&quot;dabar&quot;], b = [&quot;brazil&quot;] <strong>Output:</strong> false <strong>Explanation:</strong> Alice must start the game by playing the word &quot;avokado&quot; since it&#39;s her smallest word, then Bob plays his only word, &quot;brazil&quot;, which he can play because its first letter, &#39;b&#39;, is the letter after Alice&#39;s word&#39;s first letter, &#39;a&#39;. Alice can&#39;t play a word since the first letter of the only word left is not equal to &#39;b&#39; or the letter after &#39;b&#39;, &#39;c&#39;. So, Alice loses, and the game ends.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = [&quot;ananas&quot;,&quot;atlas&quot;,&quot;banana&quot;], b = [&quot;albatros&quot;,&quot;cikla&quot;,&quot;nogomet&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> Alice must start the game by playing the word &quot;ananas&quot;. Bob can&#39;t play a word since the only word he has that starts with the letter &#39;a&#39; or &#39;b&#39; is &quot;albatros&quot;, which is smaller than Alice&#39;s word. So Alice wins, and the game ends.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = [&quot;hrvatska&quot;,&quot;zastava&quot;], b = [&quot;bijeli&quot;,&quot;galeb&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> Alice must start the game by playing the word &quot;hrvatska&quot;. Bob can&#39;t play a word since the first letter of both of his words are smaller than the first letter of Alice&#39;s word, &#39;h&#39;. So Alice wins, and the game ends. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length &lt;= 10<sup>5</sup></code></li> <li><code>a[i]</code> and <code>b[i]</code> consist only of lowercase English letters.</li> <li><code>a</code> and <code>b</code> are <strong>lexicographically sorted</strong>.</li> <li>All the words in <code>a</code> and <code>b</code> combined are <strong>distinct</strong>.</li> <li>The sum of the lengths of all the words in <code>a</code> and <code>b</code> combined does not exceed <code>10<sup>6</sup></code>.</li> </ul>
Greedy; Array; Math; Two Pointers; String; Game Theory
Go
func canAliceWin(a []string, b []string) bool { i, j, k := 1, 0, 1 w := a[0] for { if k&1 == 1 { if j == len(b) { return true } if (b[j][0] == w[0] && w < b[j]) || b[j][0]-w[0] == 1 { w = b[j] k ^= 1 } j++ } else { if i == len(a) { return false } if (a[i][0] == w[0] && w < a[i]) || a[i][0]-w[0] == 1 { w = a[i] k ^= 1 } i++ } } }
2,868
The Wording Game
Hard
<p>Alice and Bob each have a <strong>lexicographically sorted</strong> array of strings named <code>a</code> and <code>b</code> respectively.</p> <p>They are playing a wording game with the following rules:</p> <ul> <li>On each turn, the current player should play a word from their list such that the new word is <strong>closely greater</strong> than the last played word; then it&#39;s the other player&#39;s turn.</li> <li>If a player can&#39;t play a word on their turn, they lose.</li> </ul> <p>Alice starts the game by playing her <strong>lexicographically </strong><strong>smallest </strong>word.</p> <p>Given <code>a</code> and <code>b</code>, return <code>true</code> <em>if Alice can win knowing that both players play their best, and</em> <code>false</code> <em>otherwise.</em></p> <p>A word <code>w</code> is <strong>closely greater</strong> than a word <code>z</code> if the following conditions are met:</p> <ul> <li><code>w</code> is <strong>lexicographically greater</strong> than <code>z</code>.</li> <li>If <code>w<sub>1</sub></code> is the first letter of <code>w</code> and <code>z<sub>1</sub></code> is the first letter of <code>z</code>, <code>w<sub>1</sub></code> should either be <strong>equal</strong> to <code>z<sub>1</sub></code> or be the <strong>letter after</strong> <code>z<sub>1</sub></code> in the alphabet.</li> <li>For example, the word <code>&quot;care&quot;</code> is closely greater than <code>&quot;book&quot;</code> and <code>&quot;car&quot;</code>, but is not closely greater than <code>&quot;ant&quot;</code> or <code>&quot;cook&quot;</code>.</li> </ul> <p>A string <code>s</code> is <b>lexicographically </b><strong>greater</strong> than a string <code>t</code> if in the first position where <code>s</code> and <code>t</code> differ, string <code>s</code> has a letter that appears later in the alphabet than the corresponding letter in <code>t</code>. If the first <code>min(s.length, t.length)</code> characters do not differ, then the longer string is the lexicographically greater one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = [&quot;avokado&quot;,&quot;dabar&quot;], b = [&quot;brazil&quot;] <strong>Output:</strong> false <strong>Explanation:</strong> Alice must start the game by playing the word &quot;avokado&quot; since it&#39;s her smallest word, then Bob plays his only word, &quot;brazil&quot;, which he can play because its first letter, &#39;b&#39;, is the letter after Alice&#39;s word&#39;s first letter, &#39;a&#39;. Alice can&#39;t play a word since the first letter of the only word left is not equal to &#39;b&#39; or the letter after &#39;b&#39;, &#39;c&#39;. So, Alice loses, and the game ends.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = [&quot;ananas&quot;,&quot;atlas&quot;,&quot;banana&quot;], b = [&quot;albatros&quot;,&quot;cikla&quot;,&quot;nogomet&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> Alice must start the game by playing the word &quot;ananas&quot;. Bob can&#39;t play a word since the only word he has that starts with the letter &#39;a&#39; or &#39;b&#39; is &quot;albatros&quot;, which is smaller than Alice&#39;s word. So Alice wins, and the game ends.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = [&quot;hrvatska&quot;,&quot;zastava&quot;], b = [&quot;bijeli&quot;,&quot;galeb&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> Alice must start the game by playing the word &quot;hrvatska&quot;. Bob can&#39;t play a word since the first letter of both of his words are smaller than the first letter of Alice&#39;s word, &#39;h&#39;. So Alice wins, and the game ends. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length &lt;= 10<sup>5</sup></code></li> <li><code>a[i]</code> and <code>b[i]</code> consist only of lowercase English letters.</li> <li><code>a</code> and <code>b</code> are <strong>lexicographically sorted</strong>.</li> <li>All the words in <code>a</code> and <code>b</code> combined are <strong>distinct</strong>.</li> <li>The sum of the lengths of all the words in <code>a</code> and <code>b</code> combined does not exceed <code>10<sup>6</sup></code>.</li> </ul>
Greedy; Array; Math; Two Pointers; String; Game Theory
Java
class Solution { public boolean canAliceWin(String[] a, String[] b) { int i = 1, j = 0; boolean k = true; String w = a[0]; while (true) { if (k) { if (j == b.length) { return true; } if ((b[j].charAt(0) == w.charAt(0) && w.compareTo(b[j]) < 0) || b[j].charAt(0) - w.charAt(0) == 1) { w = b[j]; k = !k; } ++j; } else { if (i == a.length) { return false; } if ((a[i].charAt(0) == w.charAt(0) && w.compareTo(a[i]) < 0) || a[i].charAt(0) - w.charAt(0) == 1) { w = a[i]; k = !k; } ++i; } } } }
2,868
The Wording Game
Hard
<p>Alice and Bob each have a <strong>lexicographically sorted</strong> array of strings named <code>a</code> and <code>b</code> respectively.</p> <p>They are playing a wording game with the following rules:</p> <ul> <li>On each turn, the current player should play a word from their list such that the new word is <strong>closely greater</strong> than the last played word; then it&#39;s the other player&#39;s turn.</li> <li>If a player can&#39;t play a word on their turn, they lose.</li> </ul> <p>Alice starts the game by playing her <strong>lexicographically </strong><strong>smallest </strong>word.</p> <p>Given <code>a</code> and <code>b</code>, return <code>true</code> <em>if Alice can win knowing that both players play their best, and</em> <code>false</code> <em>otherwise.</em></p> <p>A word <code>w</code> is <strong>closely greater</strong> than a word <code>z</code> if the following conditions are met:</p> <ul> <li><code>w</code> is <strong>lexicographically greater</strong> than <code>z</code>.</li> <li>If <code>w<sub>1</sub></code> is the first letter of <code>w</code> and <code>z<sub>1</sub></code> is the first letter of <code>z</code>, <code>w<sub>1</sub></code> should either be <strong>equal</strong> to <code>z<sub>1</sub></code> or be the <strong>letter after</strong> <code>z<sub>1</sub></code> in the alphabet.</li> <li>For example, the word <code>&quot;care&quot;</code> is closely greater than <code>&quot;book&quot;</code> and <code>&quot;car&quot;</code>, but is not closely greater than <code>&quot;ant&quot;</code> or <code>&quot;cook&quot;</code>.</li> </ul> <p>A string <code>s</code> is <b>lexicographically </b><strong>greater</strong> than a string <code>t</code> if in the first position where <code>s</code> and <code>t</code> differ, string <code>s</code> has a letter that appears later in the alphabet than the corresponding letter in <code>t</code>. If the first <code>min(s.length, t.length)</code> characters do not differ, then the longer string is the lexicographically greater one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = [&quot;avokado&quot;,&quot;dabar&quot;], b = [&quot;brazil&quot;] <strong>Output:</strong> false <strong>Explanation:</strong> Alice must start the game by playing the word &quot;avokado&quot; since it&#39;s her smallest word, then Bob plays his only word, &quot;brazil&quot;, which he can play because its first letter, &#39;b&#39;, is the letter after Alice&#39;s word&#39;s first letter, &#39;a&#39;. Alice can&#39;t play a word since the first letter of the only word left is not equal to &#39;b&#39; or the letter after &#39;b&#39;, &#39;c&#39;. So, Alice loses, and the game ends.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = [&quot;ananas&quot;,&quot;atlas&quot;,&quot;banana&quot;], b = [&quot;albatros&quot;,&quot;cikla&quot;,&quot;nogomet&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> Alice must start the game by playing the word &quot;ananas&quot;. Bob can&#39;t play a word since the only word he has that starts with the letter &#39;a&#39; or &#39;b&#39; is &quot;albatros&quot;, which is smaller than Alice&#39;s word. So Alice wins, and the game ends.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = [&quot;hrvatska&quot;,&quot;zastava&quot;], b = [&quot;bijeli&quot;,&quot;galeb&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> Alice must start the game by playing the word &quot;hrvatska&quot;. Bob can&#39;t play a word since the first letter of both of his words are smaller than the first letter of Alice&#39;s word, &#39;h&#39;. So Alice wins, and the game ends. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length &lt;= 10<sup>5</sup></code></li> <li><code>a[i]</code> and <code>b[i]</code> consist only of lowercase English letters.</li> <li><code>a</code> and <code>b</code> are <strong>lexicographically sorted</strong>.</li> <li>All the words in <code>a</code> and <code>b</code> combined are <strong>distinct</strong>.</li> <li>The sum of the lengths of all the words in <code>a</code> and <code>b</code> combined does not exceed <code>10<sup>6</sup></code>.</li> </ul>
Greedy; Array; Math; Two Pointers; String; Game Theory
Python
class Solution: def canAliceWin(self, a: List[str], b: List[str]) -> bool: i, j, k = 1, 0, 1 w = a[0] while 1: if k: if j == len(b): return True if (b[j][0] == w[0] and b[j] > w) or ord(b[j][0]) - ord(w[0]) == 1: w = b[j] k ^= 1 j += 1 else: if i == len(a): return False if (a[i][0] == w[0] and a[i] > w) or ord(a[i][0]) - ord(w[0]) == 1: w = a[i] k ^= 1 i += 1
2,868
The Wording Game
Hard
<p>Alice and Bob each have a <strong>lexicographically sorted</strong> array of strings named <code>a</code> and <code>b</code> respectively.</p> <p>They are playing a wording game with the following rules:</p> <ul> <li>On each turn, the current player should play a word from their list such that the new word is <strong>closely greater</strong> than the last played word; then it&#39;s the other player&#39;s turn.</li> <li>If a player can&#39;t play a word on their turn, they lose.</li> </ul> <p>Alice starts the game by playing her <strong>lexicographically </strong><strong>smallest </strong>word.</p> <p>Given <code>a</code> and <code>b</code>, return <code>true</code> <em>if Alice can win knowing that both players play their best, and</em> <code>false</code> <em>otherwise.</em></p> <p>A word <code>w</code> is <strong>closely greater</strong> than a word <code>z</code> if the following conditions are met:</p> <ul> <li><code>w</code> is <strong>lexicographically greater</strong> than <code>z</code>.</li> <li>If <code>w<sub>1</sub></code> is the first letter of <code>w</code> and <code>z<sub>1</sub></code> is the first letter of <code>z</code>, <code>w<sub>1</sub></code> should either be <strong>equal</strong> to <code>z<sub>1</sub></code> or be the <strong>letter after</strong> <code>z<sub>1</sub></code> in the alphabet.</li> <li>For example, the word <code>&quot;care&quot;</code> is closely greater than <code>&quot;book&quot;</code> and <code>&quot;car&quot;</code>, but is not closely greater than <code>&quot;ant&quot;</code> or <code>&quot;cook&quot;</code>.</li> </ul> <p>A string <code>s</code> is <b>lexicographically </b><strong>greater</strong> than a string <code>t</code> if in the first position where <code>s</code> and <code>t</code> differ, string <code>s</code> has a letter that appears later in the alphabet than the corresponding letter in <code>t</code>. If the first <code>min(s.length, t.length)</code> characters do not differ, then the longer string is the lexicographically greater one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = [&quot;avokado&quot;,&quot;dabar&quot;], b = [&quot;brazil&quot;] <strong>Output:</strong> false <strong>Explanation:</strong> Alice must start the game by playing the word &quot;avokado&quot; since it&#39;s her smallest word, then Bob plays his only word, &quot;brazil&quot;, which he can play because its first letter, &#39;b&#39;, is the letter after Alice&#39;s word&#39;s first letter, &#39;a&#39;. Alice can&#39;t play a word since the first letter of the only word left is not equal to &#39;b&#39; or the letter after &#39;b&#39;, &#39;c&#39;. So, Alice loses, and the game ends.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = [&quot;ananas&quot;,&quot;atlas&quot;,&quot;banana&quot;], b = [&quot;albatros&quot;,&quot;cikla&quot;,&quot;nogomet&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> Alice must start the game by playing the word &quot;ananas&quot;. Bob can&#39;t play a word since the only word he has that starts with the letter &#39;a&#39; or &#39;b&#39; is &quot;albatros&quot;, which is smaller than Alice&#39;s word. So Alice wins, and the game ends.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = [&quot;hrvatska&quot;,&quot;zastava&quot;], b = [&quot;bijeli&quot;,&quot;galeb&quot;] <strong>Output:</strong> true <strong>Explanation:</strong> Alice must start the game by playing the word &quot;hrvatska&quot;. Bob can&#39;t play a word since the first letter of both of his words are smaller than the first letter of Alice&#39;s word, &#39;h&#39;. So Alice wins, and the game ends. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a.length, b.length &lt;= 10<sup>5</sup></code></li> <li><code>a[i]</code> and <code>b[i]</code> consist only of lowercase English letters.</li> <li><code>a</code> and <code>b</code> are <strong>lexicographically sorted</strong>.</li> <li>All the words in <code>a</code> and <code>b</code> combined are <strong>distinct</strong>.</li> <li>The sum of the lengths of all the words in <code>a</code> and <code>b</code> combined does not exceed <code>10<sup>6</sup></code>.</li> </ul>
Greedy; Array; Math; Two Pointers; String; Game Theory
TypeScript
function canAliceWin(a: string[], b: string[]): boolean { let [i, j, k] = [1, 0, 1]; let w = a[0]; while (1) { if (k) { if (j === b.length) { return true; } if ((b[j][0] === w[0] && w < b[j]) || b[j].charCodeAt(0) - w.charCodeAt(0) === 1) { w = b[j]; k ^= 1; } ++j; } else { if (i === a.length) { return false; } if ((a[i][0] === w[0] && w < a[i]) || a[i].charCodeAt(0) - w.charCodeAt(0) === 1) { w = a[i]; k ^= 1; } ++i; } } }
2,869
Minimum Operations to Collect Elements
Easy
<p>You are given an array <code>nums</code> of positive integers and an integer <code>k</code>.</p> <p>In one operation, you can remove the last element of the array and add it to your collection.</p> <p>Return <em>the <strong>minimum number of operations</strong> needed to collect elements</em> <code>1, 2, ..., k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,5,4,2], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> After 4 operations, we collect elements 2, 4, 5, and 1, in this order. Our collection contains elements 1 and 2. Hence, the answer is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,5,4,2], k = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 5 operations, we collect elements 2, 4, 5, 1, and 3, in this order. Our collection contains elements 1 through 5. Hence, the answer is 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,5,3,1], k = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> After 4 operations, we collect elements 1, 3, 5, and 2, in this order. Our collection contains elements 1 through 3. Hence, the answer is 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> <li>The input is generated such that you can collect elements <code>1, 2, ..., k</code>.</li> </ul>
Bit Manipulation; Array; Hash Table
C++
class Solution { public: int minOperations(vector<int>& nums, int k) { int n = nums.size(); vector<bool> isAdded(n); int count = 0; for (int i = n - 1;; --i) { if (nums[i] > k || isAdded[nums[i] - 1]) { continue; } isAdded[nums[i] - 1] = true; if (++count == k) { return n - i; } } } };
2,869
Minimum Operations to Collect Elements
Easy
<p>You are given an array <code>nums</code> of positive integers and an integer <code>k</code>.</p> <p>In one operation, you can remove the last element of the array and add it to your collection.</p> <p>Return <em>the <strong>minimum number of operations</strong> needed to collect elements</em> <code>1, 2, ..., k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,5,4,2], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> After 4 operations, we collect elements 2, 4, 5, and 1, in this order. Our collection contains elements 1 and 2. Hence, the answer is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,5,4,2], k = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 5 operations, we collect elements 2, 4, 5, 1, and 3, in this order. Our collection contains elements 1 through 5. Hence, the answer is 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,5,3,1], k = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> After 4 operations, we collect elements 1, 3, 5, and 2, in this order. Our collection contains elements 1 through 3. Hence, the answer is 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> <li>The input is generated such that you can collect elements <code>1, 2, ..., k</code>.</li> </ul>
Bit Manipulation; Array; Hash Table
Go
func minOperations(nums []int, k int) int { isAdded := make([]bool, k) count := 0 n := len(nums) for i := n - 1; ; i-- { if nums[i] > k || isAdded[nums[i]-1] { continue } isAdded[nums[i]-1] = true count++ if count == k { return n - i } } }
2,869
Minimum Operations to Collect Elements
Easy
<p>You are given an array <code>nums</code> of positive integers and an integer <code>k</code>.</p> <p>In one operation, you can remove the last element of the array and add it to your collection.</p> <p>Return <em>the <strong>minimum number of operations</strong> needed to collect elements</em> <code>1, 2, ..., k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,5,4,2], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> After 4 operations, we collect elements 2, 4, 5, and 1, in this order. Our collection contains elements 1 and 2. Hence, the answer is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,5,4,2], k = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 5 operations, we collect elements 2, 4, 5, 1, and 3, in this order. Our collection contains elements 1 through 5. Hence, the answer is 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,5,3,1], k = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> After 4 operations, we collect elements 1, 3, 5, and 2, in this order. Our collection contains elements 1 through 3. Hence, the answer is 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> <li>The input is generated such that you can collect elements <code>1, 2, ..., k</code>.</li> </ul>
Bit Manipulation; Array; Hash Table
Java
class Solution { public int minOperations(List<Integer> nums, int k) { boolean[] isAdded = new boolean[k]; int n = nums.size(); int count = 0; for (int i = n - 1;; i--) { if (nums.get(i) > k || isAdded[nums.get(i) - 1]) { continue; } isAdded[nums.get(i) - 1] = true; count++; if (count == k) { return n - i; } } } }
2,869
Minimum Operations to Collect Elements
Easy
<p>You are given an array <code>nums</code> of positive integers and an integer <code>k</code>.</p> <p>In one operation, you can remove the last element of the array and add it to your collection.</p> <p>Return <em>the <strong>minimum number of operations</strong> needed to collect elements</em> <code>1, 2, ..., k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,5,4,2], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> After 4 operations, we collect elements 2, 4, 5, and 1, in this order. Our collection contains elements 1 and 2. Hence, the answer is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,5,4,2], k = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 5 operations, we collect elements 2, 4, 5, 1, and 3, in this order. Our collection contains elements 1 through 5. Hence, the answer is 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,5,3,1], k = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> After 4 operations, we collect elements 1, 3, 5, and 2, in this order. Our collection contains elements 1 through 3. Hence, the answer is 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> <li>The input is generated such that you can collect elements <code>1, 2, ..., k</code>.</li> </ul>
Bit Manipulation; Array; Hash Table
Python
class Solution: def minOperations(self, nums: List[int], k: int) -> int: is_added = [False] * k count = 0 n = len(nums) for i in range(n - 1, -1, -1): if nums[i] > k or is_added[nums[i] - 1]: continue is_added[nums[i] - 1] = True count += 1 if count == k: return n - i
2,869
Minimum Operations to Collect Elements
Easy
<p>You are given an array <code>nums</code> of positive integers and an integer <code>k</code>.</p> <p>In one operation, you can remove the last element of the array and add it to your collection.</p> <p>Return <em>the <strong>minimum number of operations</strong> needed to collect elements</em> <code>1, 2, ..., k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,5,4,2], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> After 4 operations, we collect elements 2, 4, 5, and 1, in this order. Our collection contains elements 1 and 2. Hence, the answer is 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,5,4,2], k = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> After 5 operations, we collect elements 2, 4, 5, 1, and 3, in this order. Our collection contains elements 1 through 5. Hence, the answer is 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,5,3,1], k = 3 <strong>Output:</strong> 4 <strong>Explanation:</strong> After 4 operations, we collect elements 1, 3, 5, and 2, in this order. Our collection contains elements 1 through 3. Hence, the answer is 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> <li>The input is generated such that you can collect elements <code>1, 2, ..., k</code>.</li> </ul>
Bit Manipulation; Array; Hash Table
TypeScript
function minOperations(nums: number[], k: number): number { const n = nums.length; const isAdded = Array(k).fill(false); let count = 0; for (let i = n - 1; ; --i) { if (nums[i] > k || isAdded[nums[i] - 1]) { continue; } isAdded[nums[i] - 1] = true; ++count; if (count === k) { return n - i; } } }
2,870
Minimum Number of Operations to Make Array Empty
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of positive integers.</p> <p>There are two types of operations that you can apply on the array <strong>any</strong> number of times:</p> <ul> <li>Choose <strong>two</strong> elements with <strong>equal</strong> values and <strong>delete</strong> them from the array.</li> <li>Choose <strong>three</strong> elements with <strong>equal</strong> values and <strong>delete</strong> them from the array.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations required to make the array empty, or </em><code>-1</code><em> if it is not possible</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,3,2,2,4,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can apply the following operations to make the array empty: - Apply the first operation on the elements at indices 0 and 3. The resulting array is nums = [3,3,2,4,2,3,4]. - Apply the first operation on the elements at indices 2 and 4. The resulting array is nums = [3,3,4,3,4]. - Apply the second operation on the elements at indices 0, 1, and 3. The resulting array is nums = [4,4]. - Apply the first operation on the elements at indices 0 and 1. The resulting array is nums = []. It can be shown that we cannot make the array empty in less than 4 operations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,2,2,3,3] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to empty the array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/description/" target="_blank">2244: Minimum Rounds to Complete All Tasks.</a></p>
Greedy; Array; Hash Table; Counting
C++
class Solution { public: int minOperations(vector<int>& nums) { unordered_map<int, int> count; for (int num : nums) { ++count[num]; } int ans = 0; for (auto& [_, c] : count) { if (c < 2) { return -1; } ans += (c + 2) / 3; } return ans; } };
2,870
Minimum Number of Operations to Make Array Empty
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of positive integers.</p> <p>There are two types of operations that you can apply on the array <strong>any</strong> number of times:</p> <ul> <li>Choose <strong>two</strong> elements with <strong>equal</strong> values and <strong>delete</strong> them from the array.</li> <li>Choose <strong>three</strong> elements with <strong>equal</strong> values and <strong>delete</strong> them from the array.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations required to make the array empty, or </em><code>-1</code><em> if it is not possible</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,3,2,2,4,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can apply the following operations to make the array empty: - Apply the first operation on the elements at indices 0 and 3. The resulting array is nums = [3,3,2,4,2,3,4]. - Apply the first operation on the elements at indices 2 and 4. The resulting array is nums = [3,3,4,3,4]. - Apply the second operation on the elements at indices 0, 1, and 3. The resulting array is nums = [4,4]. - Apply the first operation on the elements at indices 0 and 1. The resulting array is nums = []. It can be shown that we cannot make the array empty in less than 4 operations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,2,2,3,3] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to empty the array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/description/" target="_blank">2244: Minimum Rounds to Complete All Tasks.</a></p>
Greedy; Array; Hash Table; Counting
Go
func minOperations(nums []int) (ans int) { count := map[int]int{} for _, num := range nums { count[num]++ } for _, c := range count { if c < 2 { return -1 } ans += (c + 2) / 3 } return }
2,870
Minimum Number of Operations to Make Array Empty
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of positive integers.</p> <p>There are two types of operations that you can apply on the array <strong>any</strong> number of times:</p> <ul> <li>Choose <strong>two</strong> elements with <strong>equal</strong> values and <strong>delete</strong> them from the array.</li> <li>Choose <strong>three</strong> elements with <strong>equal</strong> values and <strong>delete</strong> them from the array.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations required to make the array empty, or </em><code>-1</code><em> if it is not possible</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,3,2,2,4,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can apply the following operations to make the array empty: - Apply the first operation on the elements at indices 0 and 3. The resulting array is nums = [3,3,2,4,2,3,4]. - Apply the first operation on the elements at indices 2 and 4. The resulting array is nums = [3,3,4,3,4]. - Apply the second operation on the elements at indices 0, 1, and 3. The resulting array is nums = [4,4]. - Apply the first operation on the elements at indices 0 and 1. The resulting array is nums = []. It can be shown that we cannot make the array empty in less than 4 operations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,2,2,3,3] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to empty the array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/description/" target="_blank">2244: Minimum Rounds to Complete All Tasks.</a></p>
Greedy; Array; Hash Table; Counting
Java
class Solution { public int minOperations(int[] nums) { Map<Integer, Integer> count = new HashMap<>(); for (int num : nums) { // count.put(num, count.getOrDefault(num, 0) + 1); count.merge(num, 1, Integer::sum); } int ans = 0; for (int c : count.values()) { if (c < 2) { return -1; } int r = c % 3; int d = c / 3; switch (r) { case (0) -> { ans += d; } default -> { ans += d + 1; } } } return ans; } }
2,870
Minimum Number of Operations to Make Array Empty
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of positive integers.</p> <p>There are two types of operations that you can apply on the array <strong>any</strong> number of times:</p> <ul> <li>Choose <strong>two</strong> elements with <strong>equal</strong> values and <strong>delete</strong> them from the array.</li> <li>Choose <strong>three</strong> elements with <strong>equal</strong> values and <strong>delete</strong> them from the array.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations required to make the array empty, or </em><code>-1</code><em> if it is not possible</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,3,2,2,4,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can apply the following operations to make the array empty: - Apply the first operation on the elements at indices 0 and 3. The resulting array is nums = [3,3,2,4,2,3,4]. - Apply the first operation on the elements at indices 2 and 4. The resulting array is nums = [3,3,4,3,4]. - Apply the second operation on the elements at indices 0, 1, and 3. The resulting array is nums = [4,4]. - Apply the first operation on the elements at indices 0 and 1. The resulting array is nums = []. It can be shown that we cannot make the array empty in less than 4 operations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,2,2,3,3] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to empty the array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/description/" target="_blank">2244: Minimum Rounds to Complete All Tasks.</a></p>
Greedy; Array; Hash Table; Counting
Python
class Solution: def minOperations(self, nums: List[int]) -> int: count = Counter(nums) ans = 0 for c in count.values(): if c == 1: return -1 ans += (c + 2) // 3 return ans
2,870
Minimum Number of Operations to Make Array Empty
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of positive integers.</p> <p>There are two types of operations that you can apply on the array <strong>any</strong> number of times:</p> <ul> <li>Choose <strong>two</strong> elements with <strong>equal</strong> values and <strong>delete</strong> them from the array.</li> <li>Choose <strong>three</strong> elements with <strong>equal</strong> values and <strong>delete</strong> them from the array.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations required to make the array empty, or </em><code>-1</code><em> if it is not possible</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,3,2,2,4,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can apply the following operations to make the array empty: - Apply the first operation on the elements at indices 0 and 3. The resulting array is nums = [3,3,2,4,2,3,4]. - Apply the first operation on the elements at indices 2 and 4. The resulting array is nums = [3,3,4,3,4]. - Apply the second operation on the elements at indices 0, 1, and 3. The resulting array is nums = [4,4]. - Apply the first operation on the elements at indices 0 and 1. The resulting array is nums = []. It can be shown that we cannot make the array empty in less than 4 operations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,2,2,3,3] <strong>Output:</strong> -1 <strong>Explanation:</strong> It is impossible to empty the array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/description/" target="_blank">2244: Minimum Rounds to Complete All Tasks.</a></p>
Greedy; Array; Hash Table; Counting
TypeScript
function minOperations(nums: number[]): number { const count: Map<number, number> = new Map(); for (const num of nums) { count.set(num, (count.get(num) ?? 0) + 1); } let ans = 0; for (const [_, c] of count) { if (c < 2) { return -1; } ans += ((c + 2) / 3) | 0; } return ans; }
2,871
Split Array Into Maximum Number of Subarrays
Medium
<p>You are given an array <code>nums</code> consisting of <strong>non-negative</strong> integers.</p> <p>We define the score of subarray <code>nums[l..r]</code> such that <code>l &lt;= r</code> as <code>nums[l] AND nums[l + 1] AND ... AND nums[r]</code> where <strong>AND</strong> is the bitwise <code>AND</code> operation.</p> <p>Consider splitting the array into one or more subarrays such that the following conditions are satisfied:</p> <ul> <li><strong>E</strong><strong>ach</strong> element of the array belongs to <strong>exactly</strong> one subarray.</li> <li>The sum of scores of the subarrays is the <strong>minimum</strong> possible.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of subarrays in a split that satisfies the conditions above.</em></p> <p>A <strong>subarray</strong> is a contiguous part of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,2,0,1,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can split the array into the following subarrays: - [1,0]. The score of this subarray is 1 AND 0 = 0. - [2,0]. The score of this subarray is 2 AND 0 = 0. - [1,2]. The score of this subarray is 1 AND 2 = 0. The sum of scores is 0 + 0 + 0 = 0, which is the minimum possible score that we can obtain. It can be shown that we cannot split the array into more than 3 subarrays with a total score of 0. So we return 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,7,1,3] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can split the array into one subarray: [5,7,1,3] with a score of 1, which is the minimum possible score that we can obtain. It can be shown that we cannot split the array into more than 1 subarray with a total score of 1. So we return 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Bit Manipulation; Array
C++
class Solution { public: int maxSubarrays(vector<int>& nums) { int score = -1, ans = 1; for (int num : nums) { score &= num; if (score == 0) { --score; ++ans; } } return ans == 1 ? 1 : ans - 1; } };
2,871
Split Array Into Maximum Number of Subarrays
Medium
<p>You are given an array <code>nums</code> consisting of <strong>non-negative</strong> integers.</p> <p>We define the score of subarray <code>nums[l..r]</code> such that <code>l &lt;= r</code> as <code>nums[l] AND nums[l + 1] AND ... AND nums[r]</code> where <strong>AND</strong> is the bitwise <code>AND</code> operation.</p> <p>Consider splitting the array into one or more subarrays such that the following conditions are satisfied:</p> <ul> <li><strong>E</strong><strong>ach</strong> element of the array belongs to <strong>exactly</strong> one subarray.</li> <li>The sum of scores of the subarrays is the <strong>minimum</strong> possible.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of subarrays in a split that satisfies the conditions above.</em></p> <p>A <strong>subarray</strong> is a contiguous part of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,2,0,1,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can split the array into the following subarrays: - [1,0]. The score of this subarray is 1 AND 0 = 0. - [2,0]. The score of this subarray is 2 AND 0 = 0. - [1,2]. The score of this subarray is 1 AND 2 = 0. The sum of scores is 0 + 0 + 0 = 0, which is the minimum possible score that we can obtain. It can be shown that we cannot split the array into more than 3 subarrays with a total score of 0. So we return 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,7,1,3] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can split the array into one subarray: [5,7,1,3] with a score of 1, which is the minimum possible score that we can obtain. It can be shown that we cannot split the array into more than 1 subarray with a total score of 1. So we return 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Bit Manipulation; Array
Go
func maxSubarrays(nums []int) int { ans, score := 1, -1 for _, num := range nums { score &= num if score == 0 { score-- ans++ } } if ans == 1 { return 1 } return ans - 1 }
2,871
Split Array Into Maximum Number of Subarrays
Medium
<p>You are given an array <code>nums</code> consisting of <strong>non-negative</strong> integers.</p> <p>We define the score of subarray <code>nums[l..r]</code> such that <code>l &lt;= r</code> as <code>nums[l] AND nums[l + 1] AND ... AND nums[r]</code> where <strong>AND</strong> is the bitwise <code>AND</code> operation.</p> <p>Consider splitting the array into one or more subarrays such that the following conditions are satisfied:</p> <ul> <li><strong>E</strong><strong>ach</strong> element of the array belongs to <strong>exactly</strong> one subarray.</li> <li>The sum of scores of the subarrays is the <strong>minimum</strong> possible.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of subarrays in a split that satisfies the conditions above.</em></p> <p>A <strong>subarray</strong> is a contiguous part of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,2,0,1,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can split the array into the following subarrays: - [1,0]. The score of this subarray is 1 AND 0 = 0. - [2,0]. The score of this subarray is 2 AND 0 = 0. - [1,2]. The score of this subarray is 1 AND 2 = 0. The sum of scores is 0 + 0 + 0 = 0, which is the minimum possible score that we can obtain. It can be shown that we cannot split the array into more than 3 subarrays with a total score of 0. So we return 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,7,1,3] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can split the array into one subarray: [5,7,1,3] with a score of 1, which is the minimum possible score that we can obtain. It can be shown that we cannot split the array into more than 1 subarray with a total score of 1. So we return 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Bit Manipulation; Array
Java
class Solution { public int maxSubarrays(int[] nums) { int score = -1; int ans = 1; for (int num : nums) { score &= num; if (score == 0) { ans++; score = -1; } } return ans == 1 ? 1 : ans - 1; } }
2,871
Split Array Into Maximum Number of Subarrays
Medium
<p>You are given an array <code>nums</code> consisting of <strong>non-negative</strong> integers.</p> <p>We define the score of subarray <code>nums[l..r]</code> such that <code>l &lt;= r</code> as <code>nums[l] AND nums[l + 1] AND ... AND nums[r]</code> where <strong>AND</strong> is the bitwise <code>AND</code> operation.</p> <p>Consider splitting the array into one or more subarrays such that the following conditions are satisfied:</p> <ul> <li><strong>E</strong><strong>ach</strong> element of the array belongs to <strong>exactly</strong> one subarray.</li> <li>The sum of scores of the subarrays is the <strong>minimum</strong> possible.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of subarrays in a split that satisfies the conditions above.</em></p> <p>A <strong>subarray</strong> is a contiguous part of an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,2,0,1,2] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can split the array into the following subarrays: - [1,0]. The score of this subarray is 1 AND 0 = 0. - [2,0]. The score of this subarray is 2 AND 0 = 0. - [1,2]. The score of this subarray is 1 AND 2 = 0. The sum of scores is 0 + 0 + 0 = 0, which is the minimum possible score that we can obtain. It can be shown that we cannot split the array into more than 3 subarrays with a total score of 0. So we return 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,7,1,3] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can split the array into one subarray: [5,7,1,3] with a score of 1, which is the minimum possible score that we can obtain. It can be shown that we cannot split the array into more than 1 subarray with a total score of 1. So we return 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Bit Manipulation; Array
Python
class Solution: def maxSubarrays(self, nums: List[int]) -> int: score, ans = -1, 1 for num in nums: score &= num if score == 0: score = -1 ans += 1 return 1 if ans == 1 else ans - 1