id
int64
1
3.65k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
3,070
Count Submatrices with Top-Left Element and Sum Less Than k
Medium
<p>You are given a <strong>0-indexed</strong> integer matrix <code>grid</code> and an integer <code>k</code>.</p> <p>Return <em>the <strong>number</strong> of <span data-keyword="submatrix">submatrices</span> that contain the top-left element of the</em> <code>grid</code>, <em>and have a sum less than or equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example1.png" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> grid = [[7,6,3],[6,6,1]], k = 18 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.</pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example21.png" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20 <strong>Output:</strong> 6 <strong>Explanation:</strong> There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length </code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 1000 </code></li> <li><code>0 &lt;= grid[i][j] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Matrix; Prefix Sum
Go
func countSubmatrices(grid [][]int, k int) (ans int) { s := make([][]int, len(grid)+1) for i := range s { s[i] = make([]int, len(grid[0])+1) } for i, row := range grid { for j, x := range row { s[i+1][j+1] = s[i+1][j] + s[i][j+1] - s[i][j] + x if s[i+1][j+1] <= k { ans++ } } } return }
3,070
Count Submatrices with Top-Left Element and Sum Less Than k
Medium
<p>You are given a <strong>0-indexed</strong> integer matrix <code>grid</code> and an integer <code>k</code>.</p> <p>Return <em>the <strong>number</strong> of <span data-keyword="submatrix">submatrices</span> that contain the top-left element of the</em> <code>grid</code>, <em>and have a sum less than or equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example1.png" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> grid = [[7,6,3],[6,6,1]], k = 18 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.</pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example21.png" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20 <strong>Output:</strong> 6 <strong>Explanation:</strong> There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length </code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 1000 </code></li> <li><code>0 &lt;= grid[i][j] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Matrix; Prefix Sum
Java
class Solution { public int countSubmatrices(int[][] grid, int k) { int m = grid.length, n = grid[0].length; int[][] s = new int[m + 1][n + 1]; int ans = 0; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + grid[i - 1][j - 1]; if (s[i][j] <= k) { ++ans; } } } return ans; } }
3,070
Count Submatrices with Top-Left Element and Sum Less Than k
Medium
<p>You are given a <strong>0-indexed</strong> integer matrix <code>grid</code> and an integer <code>k</code>.</p> <p>Return <em>the <strong>number</strong> of <span data-keyword="submatrix">submatrices</span> that contain the top-left element of the</em> <code>grid</code>, <em>and have a sum less than or equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example1.png" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> grid = [[7,6,3],[6,6,1]], k = 18 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.</pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example21.png" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20 <strong>Output:</strong> 6 <strong>Explanation:</strong> There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length </code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 1000 </code></li> <li><code>0 &lt;= grid[i][j] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Matrix; Prefix Sum
Python
class Solution: def countSubmatrices(self, grid: List[List[int]], k: int) -> int: s = [[0] * (len(grid[0]) + 1) for _ in range(len(grid) + 1)] ans = 0 for i, row in enumerate(grid, 1): for j, x in enumerate(row, 1): s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + x ans += s[i][j] <= k return ans
3,070
Count Submatrices with Top-Left Element and Sum Less Than k
Medium
<p>You are given a <strong>0-indexed</strong> integer matrix <code>grid</code> and an integer <code>k</code>.</p> <p>Return <em>the <strong>number</strong> of <span data-keyword="submatrix">submatrices</span> that contain the top-left element of the</em> <code>grid</code>, <em>and have a sum less than or equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example1.png" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> grid = [[7,6,3],[6,6,1]], k = 18 <strong>Output:</strong> 4 <strong>Explanation:</strong> There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.</pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3070.Count%20Submatrices%20with%20Top-Left%20Element%20and%20Sum%20Less%20Than%20k/images/example21.png" style="padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20 <strong>Output:</strong> 6 <strong>Explanation:</strong> There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length </code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= n, m &lt;= 1000 </code></li> <li><code>0 &lt;= grid[i][j] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Array; Matrix; Prefix Sum
TypeScript
function countSubmatrices(grid: number[][], k: number): number { const m = grid.length; const n = grid[0].length; const s: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); let ans: number = 0; for (let i = 1; i <= m; ++i) { for (let j = 1; j <= n; ++j) { s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + grid[i - 1][j - 1]; if (s[i][j] <= k) { ++ans; } } } return ans; }
3,071
Minimum Operations to Write the Letter Y on a Grid
Medium
<p>You are given a <strong>0-indexed</strong> <code>n x n</code> grid where <code>n</code> is odd, and <code>grid[r][c]</code> is <code>0</code>, <code>1</code>, or <code>2</code>.</p> <p>We say that a cell belongs to the Letter <strong>Y</strong> if it belongs to one of the following:</p> <ul> <li>The diagonal starting at the top-left cell and ending at the center cell of the grid.</li> <li>The diagonal starting at the top-right cell and ending at the center cell of the grid.</li> <li>The vertical line starting at the center cell and ending at the bottom border of the grid.</li> </ul> <p>The Letter <strong>Y</strong> is written on the grid if and only if:</p> <ul> <li>All values at cells belonging to the Y are equal.</li> <li>All values at cells not belonging to the Y are equal.</li> <li>The values at cells belonging to the Y are different from the values at cells not belonging to the Y.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations needed to write the letter Y on the grid given that in one operation you can change the value at any cell to</em> <code>0</code><em>,</em> <code>1</code><em>,</em> <em>or</em> <code>2</code><em>.</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/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y2.png" style="width: 461px; height: 121px;" /> <pre> <strong>Input:</strong> grid = [[1,2,2],[1,1,0],[0,1,0]] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0. It can be shown that 3 is the minimum number of operations needed to write Y on the grid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y3.png" style="width: 701px; height: 201px;" /> <pre> <strong>Input:</strong> grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]] <strong>Output:</strong> 12 <strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2. It can be shown that 12 is the minimum number of operations needed to write Y on the grid.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 49 </code></li> <li><code>n == grid.length == grid[i].length</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 2</code></li> <li><code>n</code> is odd.</li> </ul>
Array; Hash Table; Counting; Matrix
C++
class Solution { public: int minimumOperationsToWriteY(vector<vector<int>>& grid) { int n = grid.size(); int cnt1[3]{}; int cnt2[3]{}; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { bool a = i == j && i <= n / 2; bool b = i + j == n - 1 && i <= n / 2; bool c = j == n / 2 && i >= n / 2; if (a || b || c) { ++cnt1[grid[i][j]]; } else { ++cnt2[grid[i][j]]; } } } int ans = n * n; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (i != j) { ans = min(ans, n * n - cnt1[i] - cnt2[j]); } } } return ans; } };
3,071
Minimum Operations to Write the Letter Y on a Grid
Medium
<p>You are given a <strong>0-indexed</strong> <code>n x n</code> grid where <code>n</code> is odd, and <code>grid[r][c]</code> is <code>0</code>, <code>1</code>, or <code>2</code>.</p> <p>We say that a cell belongs to the Letter <strong>Y</strong> if it belongs to one of the following:</p> <ul> <li>The diagonal starting at the top-left cell and ending at the center cell of the grid.</li> <li>The diagonal starting at the top-right cell and ending at the center cell of the grid.</li> <li>The vertical line starting at the center cell and ending at the bottom border of the grid.</li> </ul> <p>The Letter <strong>Y</strong> is written on the grid if and only if:</p> <ul> <li>All values at cells belonging to the Y are equal.</li> <li>All values at cells not belonging to the Y are equal.</li> <li>The values at cells belonging to the Y are different from the values at cells not belonging to the Y.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations needed to write the letter Y on the grid given that in one operation you can change the value at any cell to</em> <code>0</code><em>,</em> <code>1</code><em>,</em> <em>or</em> <code>2</code><em>.</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/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y2.png" style="width: 461px; height: 121px;" /> <pre> <strong>Input:</strong> grid = [[1,2,2],[1,1,0],[0,1,0]] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0. It can be shown that 3 is the minimum number of operations needed to write Y on the grid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y3.png" style="width: 701px; height: 201px;" /> <pre> <strong>Input:</strong> grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]] <strong>Output:</strong> 12 <strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2. It can be shown that 12 is the minimum number of operations needed to write Y on the grid.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 49 </code></li> <li><code>n == grid.length == grid[i].length</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 2</code></li> <li><code>n</code> is odd.</li> </ul>
Array; Hash Table; Counting; Matrix
Go
func minimumOperationsToWriteY(grid [][]int) int { n := len(grid) cnt1 := [3]int{} cnt2 := [3]int{} for i, row := range grid { for j, x := range row { a := i == j && i <= n/2 b := i+j == n-1 && i <= n/2 c := j == n/2 && i >= n/2 if a || b || c { cnt1[x]++ } else { cnt2[x]++ } } } ans := n * n for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { if i != j { ans = min(ans, n*n-cnt1[i]-cnt2[j]) } } } return ans }
3,071
Minimum Operations to Write the Letter Y on a Grid
Medium
<p>You are given a <strong>0-indexed</strong> <code>n x n</code> grid where <code>n</code> is odd, and <code>grid[r][c]</code> is <code>0</code>, <code>1</code>, or <code>2</code>.</p> <p>We say that a cell belongs to the Letter <strong>Y</strong> if it belongs to one of the following:</p> <ul> <li>The diagonal starting at the top-left cell and ending at the center cell of the grid.</li> <li>The diagonal starting at the top-right cell and ending at the center cell of the grid.</li> <li>The vertical line starting at the center cell and ending at the bottom border of the grid.</li> </ul> <p>The Letter <strong>Y</strong> is written on the grid if and only if:</p> <ul> <li>All values at cells belonging to the Y are equal.</li> <li>All values at cells not belonging to the Y are equal.</li> <li>The values at cells belonging to the Y are different from the values at cells not belonging to the Y.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations needed to write the letter Y on the grid given that in one operation you can change the value at any cell to</em> <code>0</code><em>,</em> <code>1</code><em>,</em> <em>or</em> <code>2</code><em>.</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/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y2.png" style="width: 461px; height: 121px;" /> <pre> <strong>Input:</strong> grid = [[1,2,2],[1,1,0],[0,1,0]] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0. It can be shown that 3 is the minimum number of operations needed to write Y on the grid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y3.png" style="width: 701px; height: 201px;" /> <pre> <strong>Input:</strong> grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]] <strong>Output:</strong> 12 <strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2. It can be shown that 12 is the minimum number of operations needed to write Y on the grid.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 49 </code></li> <li><code>n == grid.length == grid[i].length</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 2</code></li> <li><code>n</code> is odd.</li> </ul>
Array; Hash Table; Counting; Matrix
Java
class Solution { public int minimumOperationsToWriteY(int[][] grid) { int n = grid.length; int[] cnt1 = new int[3]; int[] cnt2 = new int[3]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { boolean a = i == j && i <= n / 2; boolean b = i + j == n - 1 && i <= n / 2; boolean c = j == n / 2 && i >= n / 2; if (a || b || c) { ++cnt1[grid[i][j]]; } else { ++cnt2[grid[i][j]]; } } } int ans = n * n; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (i != j) { ans = Math.min(ans, n * n - cnt1[i] - cnt2[j]); } } } return ans; } }
3,071
Minimum Operations to Write the Letter Y on a Grid
Medium
<p>You are given a <strong>0-indexed</strong> <code>n x n</code> grid where <code>n</code> is odd, and <code>grid[r][c]</code> is <code>0</code>, <code>1</code>, or <code>2</code>.</p> <p>We say that a cell belongs to the Letter <strong>Y</strong> if it belongs to one of the following:</p> <ul> <li>The diagonal starting at the top-left cell and ending at the center cell of the grid.</li> <li>The diagonal starting at the top-right cell and ending at the center cell of the grid.</li> <li>The vertical line starting at the center cell and ending at the bottom border of the grid.</li> </ul> <p>The Letter <strong>Y</strong> is written on the grid if and only if:</p> <ul> <li>All values at cells belonging to the Y are equal.</li> <li>All values at cells not belonging to the Y are equal.</li> <li>The values at cells belonging to the Y are different from the values at cells not belonging to the Y.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations needed to write the letter Y on the grid given that in one operation you can change the value at any cell to</em> <code>0</code><em>,</em> <code>1</code><em>,</em> <em>or</em> <code>2</code><em>.</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/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y2.png" style="width: 461px; height: 121px;" /> <pre> <strong>Input:</strong> grid = [[1,2,2],[1,1,0],[0,1,0]] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0. It can be shown that 3 is the minimum number of operations needed to write Y on the grid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y3.png" style="width: 701px; height: 201px;" /> <pre> <strong>Input:</strong> grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]] <strong>Output:</strong> 12 <strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2. It can be shown that 12 is the minimum number of operations needed to write Y on the grid.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 49 </code></li> <li><code>n == grid.length == grid[i].length</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 2</code></li> <li><code>n</code> is odd.</li> </ul>
Array; Hash Table; Counting; Matrix
Python
class Solution: def minimumOperationsToWriteY(self, grid: List[List[int]]) -> int: n = len(grid) cnt1 = Counter() cnt2 = Counter() for i, row in enumerate(grid): for j, x in enumerate(row): a = i == j and i <= n // 2 b = i + j == n - 1 and i <= n // 2 c = j == n // 2 and i >= n // 2 if a or b or c: cnt1[x] += 1 else: cnt2[x] += 1 return min( n * n - cnt1[i] - cnt2[j] for i in range(3) for j in range(3) if i != j )
3,071
Minimum Operations to Write the Letter Y on a Grid
Medium
<p>You are given a <strong>0-indexed</strong> <code>n x n</code> grid where <code>n</code> is odd, and <code>grid[r][c]</code> is <code>0</code>, <code>1</code>, or <code>2</code>.</p> <p>We say that a cell belongs to the Letter <strong>Y</strong> if it belongs to one of the following:</p> <ul> <li>The diagonal starting at the top-left cell and ending at the center cell of the grid.</li> <li>The diagonal starting at the top-right cell and ending at the center cell of the grid.</li> <li>The vertical line starting at the center cell and ending at the bottom border of the grid.</li> </ul> <p>The Letter <strong>Y</strong> is written on the grid if and only if:</p> <ul> <li>All values at cells belonging to the Y are equal.</li> <li>All values at cells not belonging to the Y are equal.</li> <li>The values at cells belonging to the Y are different from the values at cells not belonging to the Y.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations needed to write the letter Y on the grid given that in one operation you can change the value at any cell to</em> <code>0</code><em>,</em> <code>1</code><em>,</em> <em>or</em> <code>2</code><em>.</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/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y2.png" style="width: 461px; height: 121px;" /> <pre> <strong>Input:</strong> grid = [[1,2,2],[1,1,0],[0,1,0]] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0. It can be shown that 3 is the minimum number of operations needed to write Y on the grid. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3071.Minimum%20Operations%20to%20Write%20the%20Letter%20Y%20on%20a%20Grid/images/y3.png" style="width: 701px; height: 201px;" /> <pre> <strong>Input:</strong> grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]] <strong>Output:</strong> 12 <strong>Explanation:</strong> We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2. It can be shown that 12 is the minimum number of operations needed to write Y on the grid.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 49 </code></li> <li><code>n == grid.length == grid[i].length</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 2</code></li> <li><code>n</code> is odd.</li> </ul>
Array; Hash Table; Counting; Matrix
TypeScript
function minimumOperationsToWriteY(grid: number[][]): number { const n = grid.length; const cnt1: number[] = Array(3).fill(0); const cnt2: number[] = Array(3).fill(0); for (let i = 0; i < n; ++i) { for (let j = 0; j < n; ++j) { const a = i === j && i <= n >> 1; const b = i + j === n - 1 && i <= n >> 1; const c = j === n >> 1 && i >= n >> 1; if (a || b || c) { ++cnt1[grid[i][j]]; } else { ++cnt2[grid[i][j]]; } } } let ans = n * n; for (let i = 0; i < 3; ++i) { for (let j = 0; j < 3; ++j) { if (i !== j) { ans = Math.min(ans, n * n - cnt1[i] - cnt2[j]); } } } return ans; }
3,072
Distribute Elements Into Two Arrays II
Hard
<p>You are given a <strong>1-indexed</strong> array of integers <code>nums</code> of length <code>n</code>.</p> <p>We define a function <code>greaterCount</code> such that <code>greaterCount(arr, val)</code> returns the number of elements in <code>arr</code> that are <strong>strictly greater</strong> than <code>val</code>.</p> <p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p> <ul> <li>If <code>greaterCount(arr1, nums[i]) &gt; greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr1</code>.</li> <li>If <code>greaterCount(arr1, nums[i]) &lt; greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr2</code>.</li> <li>If <code>greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to the array with a <strong>lesser</strong> number of elements.</li> <li>If there is still a tie, append <code>nums[i]</code> to <code>arr1</code>.</li> </ul> <p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p> <p>Return <em>the integer array</em> <code>result</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3,3] <strong>Output:</strong> [2,3,1,3] <strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1]. In the 3<sup>rd</sup> operation, the number of elements greater than 3 is zero in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1. In the 4<sup>th</sup> operation, the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser, hence, append nums[4] to arr2. After 4 operations, arr1 = [2,3] and arr2 = [1,3]. Hence, the array result formed by concatenation is [2,3,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,14,3,1,2] <strong>Output:</strong> [5,3,1,2,14] <strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [14]. In the 3<sup>rd</sup> operation, the number of elements greater than 3 is one in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1. In the 4<sup>th</sup> operation, the number of elements greater than 1 is greater in arr1 than arr2 (2 &gt; 1). Hence, append nums[4] to arr1. In the 5<sup>th</sup> operation, the number of elements greater than 2 is greater in arr1 than arr2 (2 &gt; 1). Hence, append nums[5] to arr1. After 5 operations, arr1 = [5,3,1,2] and arr2 = [14]. Hence, the array result formed by concatenation is [5,3,1,2,14]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3] <strong>Output:</strong> [3,3,3,3] <strong>Explanation:</strong> At the end of 4 operations, arr1 = [3,3] and arr2 = [3,3]. Hence, the array result formed by concatenation is [3,3,3,3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Binary Indexed Tree; Segment Tree; Array; Simulation
C++
class BinaryIndexedTree { private: int n; vector<int> c; public: BinaryIndexedTree(int n) : n(n) , c(n + 1) {} void update(int x, int delta) { for (; x <= n; x += x & -x) { c[x] += delta; } } int query(int x) { int s = 0; for (; x > 0; x -= x & -x) { s += c[x]; } return s; } }; class Solution { public: vector<int> resultArray(vector<int>& nums) { vector<int> st = nums; sort(st.begin(), st.end()); int n = st.size(); BinaryIndexedTree tree1(n + 1); BinaryIndexedTree tree2(n + 1); tree1.update(distance(st.begin(), lower_bound(st.begin(), st.end(), nums[0])) + 1, 1); tree2.update(distance(st.begin(), lower_bound(st.begin(), st.end(), nums[1])) + 1, 1); vector<int> arr1 = {nums[0]}; vector<int> arr2 = {nums[1]}; for (int k = 2; k < n; ++k) { int x = distance(st.begin(), lower_bound(st.begin(), st.end(), nums[k])) + 1; int a = arr1.size() - tree1.query(x); int b = arr2.size() - tree2.query(x); if (a > b) { arr1.push_back(nums[k]); tree1.update(x, 1); } else if (a < b) { arr2.push_back(nums[k]); tree2.update(x, 1); } else if (arr1.size() <= arr2.size()) { arr1.push_back(nums[k]); tree1.update(x, 1); } else { arr2.push_back(nums[k]); tree2.update(x, 1); } } arr1.insert(arr1.end(), arr2.begin(), arr2.end()); return arr1; } };
3,072
Distribute Elements Into Two Arrays II
Hard
<p>You are given a <strong>1-indexed</strong> array of integers <code>nums</code> of length <code>n</code>.</p> <p>We define a function <code>greaterCount</code> such that <code>greaterCount(arr, val)</code> returns the number of elements in <code>arr</code> that are <strong>strictly greater</strong> than <code>val</code>.</p> <p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p> <ul> <li>If <code>greaterCount(arr1, nums[i]) &gt; greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr1</code>.</li> <li>If <code>greaterCount(arr1, nums[i]) &lt; greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr2</code>.</li> <li>If <code>greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to the array with a <strong>lesser</strong> number of elements.</li> <li>If there is still a tie, append <code>nums[i]</code> to <code>arr1</code>.</li> </ul> <p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p> <p>Return <em>the integer array</em> <code>result</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3,3] <strong>Output:</strong> [2,3,1,3] <strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1]. In the 3<sup>rd</sup> operation, the number of elements greater than 3 is zero in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1. In the 4<sup>th</sup> operation, the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser, hence, append nums[4] to arr2. After 4 operations, arr1 = [2,3] and arr2 = [1,3]. Hence, the array result formed by concatenation is [2,3,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,14,3,1,2] <strong>Output:</strong> [5,3,1,2,14] <strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [14]. In the 3<sup>rd</sup> operation, the number of elements greater than 3 is one in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1. In the 4<sup>th</sup> operation, the number of elements greater than 1 is greater in arr1 than arr2 (2 &gt; 1). Hence, append nums[4] to arr1. In the 5<sup>th</sup> operation, the number of elements greater than 2 is greater in arr1 than arr2 (2 &gt; 1). Hence, append nums[5] to arr1. After 5 operations, arr1 = [5,3,1,2] and arr2 = [14]. Hence, the array result formed by concatenation is [5,3,1,2,14]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3] <strong>Output:</strong> [3,3,3,3] <strong>Explanation:</strong> At the end of 4 operations, arr1 = [3,3] and arr2 = [3,3]. Hence, the array result formed by concatenation is [3,3,3,3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Binary Indexed Tree; Segment Tree; Array; Simulation
Go
type BinaryIndexedTree struct { n int c []int } func NewBinaryIndexedTree(n int) *BinaryIndexedTree { return &BinaryIndexedTree{n: n, c: make([]int, n+1)} } func (bit *BinaryIndexedTree) update(x, delta int) { for ; x <= bit.n; x += x & -x { bit.c[x] += delta } } func (bit *BinaryIndexedTree) query(x int) int { s := 0 for ; x > 0; x -= x & -x { s += bit.c[x] } return s } func resultArray(nums []int) []int { st := make([]int, len(nums)) copy(st, nums) sort.Ints(st) n := len(st) tree1 := NewBinaryIndexedTree(n + 1) tree2 := NewBinaryIndexedTree(n + 1) tree1.update(sort.SearchInts(st, nums[0])+1, 1) tree2.update(sort.SearchInts(st, nums[1])+1, 1) arr1 := []int{nums[0]} arr2 := []int{nums[1]} for _, x := range nums[2:] { i := sort.SearchInts(st, x) + 1 a := len(arr1) - tree1.query(i) b := len(arr2) - tree2.query(i) if a > b { arr1 = append(arr1, x) tree1.update(i, 1) } else if a < b { arr2 = append(arr2, x) tree2.update(i, 1) } else if len(arr1) <= len(arr2) { arr1 = append(arr1, x) tree1.update(i, 1) } else { arr2 = append(arr2, x) tree2.update(i, 1) } } arr1 = append(arr1, arr2...) return arr1 }
3,072
Distribute Elements Into Two Arrays II
Hard
<p>You are given a <strong>1-indexed</strong> array of integers <code>nums</code> of length <code>n</code>.</p> <p>We define a function <code>greaterCount</code> such that <code>greaterCount(arr, val)</code> returns the number of elements in <code>arr</code> that are <strong>strictly greater</strong> than <code>val</code>.</p> <p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p> <ul> <li>If <code>greaterCount(arr1, nums[i]) &gt; greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr1</code>.</li> <li>If <code>greaterCount(arr1, nums[i]) &lt; greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr2</code>.</li> <li>If <code>greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to the array with a <strong>lesser</strong> number of elements.</li> <li>If there is still a tie, append <code>nums[i]</code> to <code>arr1</code>.</li> </ul> <p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p> <p>Return <em>the integer array</em> <code>result</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3,3] <strong>Output:</strong> [2,3,1,3] <strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1]. In the 3<sup>rd</sup> operation, the number of elements greater than 3 is zero in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1. In the 4<sup>th</sup> operation, the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser, hence, append nums[4] to arr2. After 4 operations, arr1 = [2,3] and arr2 = [1,3]. Hence, the array result formed by concatenation is [2,3,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,14,3,1,2] <strong>Output:</strong> [5,3,1,2,14] <strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [14]. In the 3<sup>rd</sup> operation, the number of elements greater than 3 is one in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1. In the 4<sup>th</sup> operation, the number of elements greater than 1 is greater in arr1 than arr2 (2 &gt; 1). Hence, append nums[4] to arr1. In the 5<sup>th</sup> operation, the number of elements greater than 2 is greater in arr1 than arr2 (2 &gt; 1). Hence, append nums[5] to arr1. After 5 operations, arr1 = [5,3,1,2] and arr2 = [14]. Hence, the array result formed by concatenation is [5,3,1,2,14]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3] <strong>Output:</strong> [3,3,3,3] <strong>Explanation:</strong> At the end of 4 operations, arr1 = [3,3] and arr2 = [3,3]. Hence, the array result formed by concatenation is [3,3,3,3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Binary Indexed Tree; Segment Tree; Array; Simulation
Java
class BinaryIndexedTree { private int n; private int[] c; public BinaryIndexedTree(int n) { this.n = n; this.c = new int[n + 1]; } public void update(int x, int delta) { for (; x <= n; x += x & -x) { c[x] += delta; } } public int query(int x) { int s = 0; for (; x > 0; x -= x & -x) { s += c[x]; } return s; } } class Solution { public int[] resultArray(int[] nums) { int[] st = nums.clone(); Arrays.sort(st); int n = st.length; BinaryIndexedTree tree1 = new BinaryIndexedTree(n + 1); BinaryIndexedTree tree2 = new BinaryIndexedTree(n + 1); tree1.update(Arrays.binarySearch(st, nums[0]) + 1, 1); tree2.update(Arrays.binarySearch(st, nums[1]) + 1, 1); int[] arr1 = new int[n]; int[] arr2 = new int[n]; arr1[0] = nums[0]; arr2[0] = nums[1]; int i = 1, j = 1; for (int k = 2; k < n; ++k) { int x = Arrays.binarySearch(st, nums[k]) + 1; int a = i - tree1.query(x); int b = j - tree2.query(x); if (a > b) { arr1[i++] = nums[k]; tree1.update(x, 1); } else if (a < b) { arr2[j++] = nums[k]; tree2.update(x, 1); } else if (i <= j) { arr1[i++] = nums[k]; tree1.update(x, 1); } else { arr2[j++] = nums[k]; tree2.update(x, 1); } } for (int k = 0; k < j; ++k) { arr1[i++] = arr2[k]; } return arr1; } }
3,072
Distribute Elements Into Two Arrays II
Hard
<p>You are given a <strong>1-indexed</strong> array of integers <code>nums</code> of length <code>n</code>.</p> <p>We define a function <code>greaterCount</code> such that <code>greaterCount(arr, val)</code> returns the number of elements in <code>arr</code> that are <strong>strictly greater</strong> than <code>val</code>.</p> <p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p> <ul> <li>If <code>greaterCount(arr1, nums[i]) &gt; greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr1</code>.</li> <li>If <code>greaterCount(arr1, nums[i]) &lt; greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr2</code>.</li> <li>If <code>greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to the array with a <strong>lesser</strong> number of elements.</li> <li>If there is still a tie, append <code>nums[i]</code> to <code>arr1</code>.</li> </ul> <p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p> <p>Return <em>the integer array</em> <code>result</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3,3] <strong>Output:</strong> [2,3,1,3] <strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1]. In the 3<sup>rd</sup> operation, the number of elements greater than 3 is zero in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1. In the 4<sup>th</sup> operation, the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser, hence, append nums[4] to arr2. After 4 operations, arr1 = [2,3] and arr2 = [1,3]. Hence, the array result formed by concatenation is [2,3,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,14,3,1,2] <strong>Output:</strong> [5,3,1,2,14] <strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [14]. In the 3<sup>rd</sup> operation, the number of elements greater than 3 is one in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1. In the 4<sup>th</sup> operation, the number of elements greater than 1 is greater in arr1 than arr2 (2 &gt; 1). Hence, append nums[4] to arr1. In the 5<sup>th</sup> operation, the number of elements greater than 2 is greater in arr1 than arr2 (2 &gt; 1). Hence, append nums[5] to arr1. After 5 operations, arr1 = [5,3,1,2] and arr2 = [14]. Hence, the array result formed by concatenation is [5,3,1,2,14]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3] <strong>Output:</strong> [3,3,3,3] <strong>Explanation:</strong> At the end of 4 operations, arr1 = [3,3] and arr2 = [3,3]. Hence, the array result formed by concatenation is [3,3,3,3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Binary Indexed Tree; Segment Tree; Array; Simulation
Python
class BinaryIndexedTree: __slots__ = "n", "c" def __init__(self, n: int): self.n = n self.c = [0] * (n + 1) def update(self, x: int, delta: int) -> None: while x <= self.n: self.c[x] += delta x += x & -x def query(self, x: int) -> int: s = 0 while x: s += self.c[x] x -= x & -x return s class Solution: def resultArray(self, nums: List[int]) -> List[int]: st = sorted(set(nums)) m = len(st) tree1 = BinaryIndexedTree(m + 1) tree2 = BinaryIndexedTree(m + 1) tree1.update(bisect_left(st, nums[0]) + 1, 1) tree2.update(bisect_left(st, nums[1]) + 1, 1) arr1 = [nums[0]] arr2 = [nums[1]] for x in nums[2:]: i = bisect_left(st, x) + 1 a = len(arr1) - tree1.query(i) b = len(arr2) - tree2.query(i) if a > b: arr1.append(x) tree1.update(i, 1) elif a < b: arr2.append(x) tree2.update(i, 1) elif len(arr1) <= len(arr2): arr1.append(x) tree1.update(i, 1) else: arr2.append(x) tree2.update(i, 1) return arr1 + arr2
3,072
Distribute Elements Into Two Arrays II
Hard
<p>You are given a <strong>1-indexed</strong> array of integers <code>nums</code> of length <code>n</code>.</p> <p>We define a function <code>greaterCount</code> such that <code>greaterCount(arr, val)</code> returns the number of elements in <code>arr</code> that are <strong>strictly greater</strong> than <code>val</code>.</p> <p>You need to distribute all the elements of <code>nums</code> between two arrays <code>arr1</code> and <code>arr2</code> using <code>n</code> operations. In the first operation, append <code>nums[1]</code> to <code>arr1</code>. In the second operation, append <code>nums[2]</code> to <code>arr2</code>. Afterwards, in the <code>i<sup>th</sup></code> operation:</p> <ul> <li>If <code>greaterCount(arr1, nums[i]) &gt; greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr1</code>.</li> <li>If <code>greaterCount(arr1, nums[i]) &lt; greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to <code>arr2</code>.</li> <li>If <code>greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])</code>, append <code>nums[i]</code> to the array with a <strong>lesser</strong> number of elements.</li> <li>If there is still a tie, append <code>nums[i]</code> to <code>arr1</code>.</li> </ul> <p>The array <code>result</code> is formed by concatenating the arrays <code>arr1</code> and <code>arr2</code>. For example, if <code>arr1 == [1,2,3]</code> and <code>arr2 == [4,5,6]</code>, then <code>result = [1,2,3,4,5,6]</code>.</p> <p>Return <em>the integer array</em> <code>result</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,3,3] <strong>Output:</strong> [2,3,1,3] <strong>Explanation:</strong> After the first 2 operations, arr1 = [2] and arr2 = [1]. In the 3<sup>rd</sup> operation, the number of elements greater than 3 is zero in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1. In the 4<sup>th</sup> operation, the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser, hence, append nums[4] to arr2. After 4 operations, arr1 = [2,3] and arr2 = [1,3]. Hence, the array result formed by concatenation is [2,3,1,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,14,3,1,2] <strong>Output:</strong> [5,3,1,2,14] <strong>Explanation:</strong> After the first 2 operations, arr1 = [5] and arr2 = [14]. In the 3<sup>rd</sup> operation, the number of elements greater than 3 is one in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1. In the 4<sup>th</sup> operation, the number of elements greater than 1 is greater in arr1 than arr2 (2 &gt; 1). Hence, append nums[4] to arr1. In the 5<sup>th</sup> operation, the number of elements greater than 2 is greater in arr1 than arr2 (2 &gt; 1). Hence, append nums[5] to arr1. After 5 operations, arr1 = [5,3,1,2] and arr2 = [14]. Hence, the array result formed by concatenation is [5,3,1,2,14]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3] <strong>Output:</strong> [3,3,3,3] <strong>Explanation:</strong> At the end of 4 operations, arr1 = [3,3] and arr2 = [3,3]. Hence, the array result formed by concatenation is [3,3,3,3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Binary Indexed Tree; Segment Tree; Array; Simulation
TypeScript
class BinaryIndexedTree { private n: number; private c: number[]; constructor(n: number) { this.n = n; this.c = Array(n + 1).fill(0); } update(x: number, delta: number): void { for (; x <= this.n; x += x & -x) { this.c[x] += delta; } } query(x: number): number { let s = 0; for (; x > 0; x -= x & -x) { s += this.c[x]; } return s; } } function resultArray(nums: number[]): number[] { const st: number[] = nums.slice().sort((a, b) => a - b); const n: number = st.length; const search = (x: number): number => { let [l, r] = [0, n]; while (l < r) { const mid = (l + r) >> 1; if (st[mid] >= x) { r = mid; } else { l = mid + 1; } } return l; }; const tree1: BinaryIndexedTree = new BinaryIndexedTree(n + 1); const tree2: BinaryIndexedTree = new BinaryIndexedTree(n + 1); tree1.update(search(nums[0]) + 1, 1); tree2.update(search(nums[1]) + 1, 1); const arr1: number[] = [nums[0]]; const arr2: number[] = [nums[1]]; for (const x of nums.slice(2)) { const i: number = search(x) + 1; const a: number = arr1.length - tree1.query(i); const b: number = arr2.length - tree2.query(i); if (a > b) { arr1.push(x); tree1.update(i, 1); } else if (a < b) { arr2.push(x); tree2.update(i, 1); } else if (arr1.length <= arr2.length) { arr1.push(x); tree1.update(i, 1); } else { arr2.push(x); tree2.update(i, 1); } } return arr1.concat(arr2); }
3,073
Maximum Increasing Triplet Value
Medium
<p>Given an array <code>nums</code>, return <em>the <strong>maximum value</strong> of a triplet</em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code> <em>and</em> <code>nums[i] &lt; nums[j] &lt; nums[k]</code>.</p> <p>The <strong>value</strong> of a triplet <code>(i, j, k)</code> is <code>nums[i] - nums[j] + nums[k]</code>.</p> <div id="gtx-trans" style="position: absolute; left: 274px; top: 102px;"> <div class="gtx-trans-icon"> </div> </div> <p>&nbsp;</p> <p><strong class="example">Example 1: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [5,6,9] </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">8 </span></p> <p><strong>Explanation: </strong> We only have one choice for an increasing triplet and that is choosing all three elements. The value of this triplet would be <code>5 - 6 + 9 = 8</code>.</p> </div> <p><strong class="example">Example 2: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,5,3,6] </span></p> <p><strong>Output:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p> <p><strong>Explanation: </strong> There are only two increasing triplets:</p> <p><code>(0, 1, 3)</code>: The value of this triplet is <code>nums[0] - nums[1] + nums[3] = 1 - 5 + 6 = 2</code>.</p> <p><code>(0, 2, 3)</code>: The value of this triplet is <code>nums[0] - nums[2] + nums[3] = 1 - 3 + 6 = 4</code>.</p> <p>Thus the answer would be <code>4</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>The input is generated such that at least one triplet meets the given condition.</li> </ul>
Array; Ordered Set
C++
class Solution { public: int maximumTripletValue(vector<int>& nums) { int n = nums.size(); vector<int> right(n, nums.back()); for (int i = n - 2; ~i; --i) { right[i] = max(nums[i], right[i + 1]); } set<int> ts; ts.insert(nums[0]); int ans = 0; for (int j = 1; j < n - 1; ++j) { if (right[j + 1] > nums[j]) { auto it = ts.lower_bound(nums[j]); if (it != ts.begin()) { --it; ans = max(ans, *it - nums[j] + right[j + 1]); } } ts.insert(nums[j]); } return ans; } };
3,073
Maximum Increasing Triplet Value
Medium
<p>Given an array <code>nums</code>, return <em>the <strong>maximum value</strong> of a triplet</em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code> <em>and</em> <code>nums[i] &lt; nums[j] &lt; nums[k]</code>.</p> <p>The <strong>value</strong> of a triplet <code>(i, j, k)</code> is <code>nums[i] - nums[j] + nums[k]</code>.</p> <div id="gtx-trans" style="position: absolute; left: 274px; top: 102px;"> <div class="gtx-trans-icon"> </div> </div> <p>&nbsp;</p> <p><strong class="example">Example 1: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [5,6,9] </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">8 </span></p> <p><strong>Explanation: </strong> We only have one choice for an increasing triplet and that is choosing all three elements. The value of this triplet would be <code>5 - 6 + 9 = 8</code>.</p> </div> <p><strong class="example">Example 2: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,5,3,6] </span></p> <p><strong>Output:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p> <p><strong>Explanation: </strong> There are only two increasing triplets:</p> <p><code>(0, 1, 3)</code>: The value of this triplet is <code>nums[0] - nums[1] + nums[3] = 1 - 5 + 6 = 2</code>.</p> <p><code>(0, 2, 3)</code>: The value of this triplet is <code>nums[0] - nums[2] + nums[3] = 1 - 3 + 6 = 4</code>.</p> <p>Thus the answer would be <code>4</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>The input is generated such that at least one triplet meets the given condition.</li> </ul>
Array; Ordered Set
Go
func maximumTripletValue(nums []int) (ans int) { n := len(nums) right := make([]int, n) right[n-1] = nums[n-1] for i := n - 2; i >= 0; i-- { right[i] = max(nums[i], right[i+1]) } ts := treemap.NewWithIntComparator() ts.Put(nums[0], nil) for j := 1; j < n-1; j++ { if right[j+1] > nums[j] { val, _ := ts.Floor(nums[j] - 1) if val != nil { ans = max(ans, val.(int)-nums[j]+right[j+1]) } } ts.Put(nums[j], nil) } return }
3,073
Maximum Increasing Triplet Value
Medium
<p>Given an array <code>nums</code>, return <em>the <strong>maximum value</strong> of a triplet</em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code> <em>and</em> <code>nums[i] &lt; nums[j] &lt; nums[k]</code>.</p> <p>The <strong>value</strong> of a triplet <code>(i, j, k)</code> is <code>nums[i] - nums[j] + nums[k]</code>.</p> <div id="gtx-trans" style="position: absolute; left: 274px; top: 102px;"> <div class="gtx-trans-icon"> </div> </div> <p>&nbsp;</p> <p><strong class="example">Example 1: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [5,6,9] </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">8 </span></p> <p><strong>Explanation: </strong> We only have one choice for an increasing triplet and that is choosing all three elements. The value of this triplet would be <code>5 - 6 + 9 = 8</code>.</p> </div> <p><strong class="example">Example 2: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,5,3,6] </span></p> <p><strong>Output:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p> <p><strong>Explanation: </strong> There are only two increasing triplets:</p> <p><code>(0, 1, 3)</code>: The value of this triplet is <code>nums[0] - nums[1] + nums[3] = 1 - 5 + 6 = 2</code>.</p> <p><code>(0, 2, 3)</code>: The value of this triplet is <code>nums[0] - nums[2] + nums[3] = 1 - 3 + 6 = 4</code>.</p> <p>Thus the answer would be <code>4</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>The input is generated such that at least one triplet meets the given condition.</li> </ul>
Array; Ordered Set
Java
class Solution { public int maximumTripletValue(int[] nums) { int n = nums.length; int[] right = new int[n]; right[n - 1] = nums[n - 1]; for (int i = n - 2; i >= 0; --i) { right[i] = Math.max(nums[i], right[i + 1]); } TreeSet<Integer> ts = new TreeSet<>(); ts.add(nums[0]); int ans = 0; for (int j = 1; j < n - 1; ++j) { if (right[j + 1] > nums[j]) { Integer it = ts.lower(nums[j]); if (it != null) { ans = Math.max(ans, it - nums[j] + right[j + 1]); } } ts.add(nums[j]); } return ans; } }
3,073
Maximum Increasing Triplet Value
Medium
<p>Given an array <code>nums</code>, return <em>the <strong>maximum value</strong> of a triplet</em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code> <em>and</em> <code>nums[i] &lt; nums[j] &lt; nums[k]</code>.</p> <p>The <strong>value</strong> of a triplet <code>(i, j, k)</code> is <code>nums[i] - nums[j] + nums[k]</code>.</p> <div id="gtx-trans" style="position: absolute; left: 274px; top: 102px;"> <div class="gtx-trans-icon"> </div> </div> <p>&nbsp;</p> <p><strong class="example">Example 1: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [5,6,9] </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">8 </span></p> <p><strong>Explanation: </strong> We only have one choice for an increasing triplet and that is choosing all three elements. The value of this triplet would be <code>5 - 6 + 9 = 8</code>.</p> </div> <p><strong class="example">Example 2: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,5,3,6] </span></p> <p><strong>Output:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p> <p><strong>Explanation: </strong> There are only two increasing triplets:</p> <p><code>(0, 1, 3)</code>: The value of this triplet is <code>nums[0] - nums[1] + nums[3] = 1 - 5 + 6 = 2</code>.</p> <p><code>(0, 2, 3)</code>: The value of this triplet is <code>nums[0] - nums[2] + nums[3] = 1 - 3 + 6 = 4</code>.</p> <p>Thus the answer would be <code>4</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>The input is generated such that at least one triplet meets the given condition.</li> </ul>
Array; Ordered Set
Python
class Solution: def maximumTripletValue(self, nums: List[int]) -> int: n = len(nums) right = [nums[-1]] * n for i in range(n - 2, -1, -1): right[i] = max(nums[i], right[i + 1]) sl = SortedList([nums[0]]) ans = 0 for j in range(1, n - 1): if right[j + 1] > nums[j]: i = sl.bisect_left(nums[j]) - 1 if i >= 0: ans = max(ans, sl[i] - nums[j] + right[j + 1]) sl.add(nums[j]) return ans
3,073
Maximum Increasing Triplet Value
Medium
<p>Given an array <code>nums</code>, return <em>the <strong>maximum value</strong> of a triplet</em> <code>(i, j, k)</code> <em>such that</em> <code>i &lt; j &lt; k</code> <em>and</em> <code>nums[i] &lt; nums[j] &lt; nums[k]</code>.</p> <p>The <strong>value</strong> of a triplet <code>(i, j, k)</code> is <code>nums[i] - nums[j] + nums[k]</code>.</p> <div id="gtx-trans" style="position: absolute; left: 274px; top: 102px;"> <div class="gtx-trans-icon"> </div> </div> <p>&nbsp;</p> <p><strong class="example">Example 1: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [5,6,9] </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">8 </span></p> <p><strong>Explanation: </strong> We only have one choice for an increasing triplet and that is choosing all three elements. The value of this triplet would be <code>5 - 6 + 9 = 8</code>.</p> </div> <p><strong class="example">Example 2: </strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,5,3,6] </span></p> <p><strong>Output:</strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p> <p><strong>Explanation: </strong> There are only two increasing triplets:</p> <p><code>(0, 1, 3)</code>: The value of this triplet is <code>nums[0] - nums[1] + nums[3] = 1 - 5 + 6 = 2</code>.</p> <p><code>(0, 2, 3)</code>: The value of this triplet is <code>nums[0] - nums[2] + nums[3] = 1 - 3 + 6 = 4</code>.</p> <p>Thus the answer would be <code>4</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>The input is generated such that at least one triplet meets the given condition.</li> </ul>
Array; Ordered Set
TypeScript
function maximumTripletValue(nums: number[]): number { const n = nums.length; const right: number[] = Array(n).fill(nums[n - 1]); for (let i = n - 2; ~i; --i) { right[i] = Math.max(nums[i], right[i + 1]); } const ts = new TreeSet<number>(); ts.add(nums[0]); let ans = 0; for (let j = 1; j < n - 1; ++j) { if (right[j + 1] > nums[j]) { const val = ts.lower(nums[j]); if (val !== undefined) { ans = Math.max(ans, val - nums[j] + right[j + 1]); } } ts.add(nums[j]); } return ans; } type Compare<T> = (lhs: T, rhs: T) => number; class RBTreeNode<T = number> { data: T; count: number; left: RBTreeNode<T> | null; right: RBTreeNode<T> | null; parent: RBTreeNode<T> | null; color: number; constructor(data: T) { this.data = data; this.left = this.right = this.parent = null; this.color = 0; this.count = 1; } sibling(): RBTreeNode<T> | null { if (!this.parent) return null; // sibling null if no parent return this.isOnLeft() ? this.parent.right : this.parent.left; } isOnLeft(): boolean { return this === this.parent!.left; } hasRedChild(): boolean { return ( Boolean(this.left && this.left.color === 0) || Boolean(this.right && this.right.color === 0) ); } } class RBTree<T> { root: RBTreeNode<T> | null; lt: (l: T, r: T) => boolean; constructor(compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0)) { this.root = null; this.lt = (l: T, r: T) => compare(l, r) < 0; } rotateLeft(pt: RBTreeNode<T>): void { const right = pt.right!; pt.right = right.left; if (pt.right) pt.right.parent = pt; right.parent = pt.parent; if (!pt.parent) this.root = right; else if (pt === pt.parent.left) pt.parent.left = right; else pt.parent.right = right; right.left = pt; pt.parent = right; } rotateRight(pt: RBTreeNode<T>): void { const left = pt.left!; pt.left = left.right; if (pt.left) pt.left.parent = pt; left.parent = pt.parent; if (!pt.parent) this.root = left; else if (pt === pt.parent.left) pt.parent.left = left; else pt.parent.right = left; left.right = pt; pt.parent = left; } swapColor(p1: RBTreeNode<T>, p2: RBTreeNode<T>): void { const tmp = p1.color; p1.color = p2.color; p2.color = tmp; } swapData(p1: RBTreeNode<T>, p2: RBTreeNode<T>): void { const tmp = p1.data; p1.data = p2.data; p2.data = tmp; } fixAfterInsert(pt: RBTreeNode<T>): void { let parent = null; let grandParent = null; while (pt !== this.root && pt.color !== 1 && pt.parent?.color === 0) { parent = pt.parent; grandParent = pt.parent.parent; /* Case : A Parent of pt is left child of Grand-parent of pt */ if (parent === grandParent?.left) { const uncle = grandParent.right; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if (uncle && uncle.color === 0) { grandParent.color = 0; parent.color = 1; uncle.color = 1; pt = grandParent; } else { /* Case : 2 pt is right child of its parent Left-rotation required */ if (pt === parent.right) { this.rotateLeft(parent); pt = parent; parent = pt.parent; } /* Case : 3 pt is left child of its parent Right-rotation required */ this.rotateRight(grandParent); this.swapColor(parent!, grandParent); pt = parent!; } } else { /* Case : B Parent of pt is right child of Grand-parent of pt */ const uncle = grandParent!.left; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if (uncle != null && uncle.color === 0) { grandParent!.color = 0; parent.color = 1; uncle.color = 1; pt = grandParent!; } else { /* Case : 2 pt is left child of its parent Right-rotation required */ if (pt === parent.left) { this.rotateRight(parent); pt = parent; parent = pt.parent; } /* Case : 3 pt is right child of its parent Left-rotation required */ this.rotateLeft(grandParent!); this.swapColor(parent!, grandParent!); pt = parent!; } } } this.root!.color = 1; } delete(val: T): boolean { const node = this.find(val); if (!node) return false; node.count--; if (!node.count) this.deleteNode(node); return true; } deleteAll(val: T): boolean { const node = this.find(val); if (!node) return false; this.deleteNode(node); return true; } deleteNode(v: RBTreeNode<T>): void { const u = BSTreplace(v); // True when u and v are both black const uvBlack = (u === null || u.color === 1) && v.color === 1; const parent = v.parent!; if (!u) { // u is null therefore v is leaf if (v === this.root) this.root = null; // v is root, making root null else { if (uvBlack) { // u and v both black // v is leaf, fix double black at v this.fixDoubleBlack(v); } else { // u or v is red if (v.sibling()) { // sibling is not null, make it red" v.sibling()!.color = 0; } } // delete v from the tree if (v.isOnLeft()) parent.left = null; else parent.right = null; } return; } if (!v.left || !v.right) { // v has 1 child if (v === this.root) { // v is root, assign the value of u to v, and delete u v.data = u.data; v.left = v.right = null; } else { // Detach v from tree and move u up if (v.isOnLeft()) parent.left = u; else parent.right = u; u.parent = parent; if (uvBlack) this.fixDoubleBlack(u); // u and v both black, fix double black at u else u.color = 1; // u or v red, color u black } return; } // v has 2 children, swap data with successor and recurse this.swapData(u, v); this.deleteNode(u); // find node that replaces a deleted node in BST function BSTreplace(x: RBTreeNode<T>): RBTreeNode<T> | null { // when node have 2 children if (x.left && x.right) return successor(x.right); // when leaf if (!x.left && !x.right) return null; // when single child return x.left ?? x.right; } // find node that do not have a left child // in the subtree of the given node function successor(x: RBTreeNode<T>): RBTreeNode<T> { let temp = x; while (temp.left) temp = temp.left; return temp; } } fixDoubleBlack(x: RBTreeNode<T>): void { if (x === this.root) return; // Reached root const sibling = x.sibling(); const parent = x.parent!; if (!sibling) { // No sibiling, double black pushed up this.fixDoubleBlack(parent); } else { if (sibling.color === 0) { // Sibling red parent.color = 0; sibling.color = 1; if (sibling.isOnLeft()) this.rotateRight(parent); // left case else this.rotateLeft(parent); // right case this.fixDoubleBlack(x); } else { // Sibling black if (sibling.hasRedChild()) { // at least 1 red children if (sibling.left && sibling.left.color === 0) { if (sibling.isOnLeft()) { // left left sibling.left.color = sibling.color; sibling.color = parent.color; this.rotateRight(parent); } else { // right left sibling.left.color = parent.color; this.rotateRight(sibling); this.rotateLeft(parent); } } else { if (sibling.isOnLeft()) { // left right sibling.right!.color = parent.color; this.rotateLeft(sibling); this.rotateRight(parent); } else { // right right sibling.right!.color = sibling.color; sibling.color = parent.color; this.rotateLeft(parent); } } parent.color = 1; } else { // 2 black children sibling.color = 0; if (parent.color === 1) this.fixDoubleBlack(parent); else parent.color = 1; } } } } insert(data: T): boolean { // search for a position to insert let parent = this.root; while (parent) { if (this.lt(data, parent.data)) { if (!parent.left) break; else parent = parent.left; } else if (this.lt(parent.data, data)) { if (!parent.right) break; else parent = parent.right; } else break; } // insert node into parent const node = new RBTreeNode(data); if (!parent) this.root = node; else if (this.lt(node.data, parent.data)) parent.left = node; else if (this.lt(parent.data, node.data)) parent.right = node; else { parent.count++; return false; } node.parent = parent; this.fixAfterInsert(node); return true; } find(data: T): RBTreeNode<T> | null { let p = this.root; while (p) { if (this.lt(data, p.data)) { p = p.left; } else if (this.lt(p.data, data)) { p = p.right; } else break; } return p ?? null; } *inOrder(root: RBTreeNode<T> = this.root!): Generator<T, undefined, void> { if (!root) return; for (const v of this.inOrder(root.left!)) yield v; yield root.data; for (const v of this.inOrder(root.right!)) yield v; } *reverseInOrder(root: RBTreeNode<T> = this.root!): Generator<T, undefined, void> { if (!root) return; for (const v of this.reverseInOrder(root.right!)) yield v; yield root.data; for (const v of this.reverseInOrder(root.left!)) yield v; } } class TreeSet<T = number> { _size: number; tree: RBTree<T>; compare: Compare<T>; constructor( collection: T[] | Compare<T> = [], compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0), ) { if (typeof collection === 'function') { compare = collection; collection = []; } this._size = 0; this.compare = compare; this.tree = new RBTree(compare); for (const val of collection) this.add(val); } size(): number { return this._size; } has(val: T): boolean { return !!this.tree.find(val); } add(val: T): boolean { const successful = this.tree.insert(val); this._size += successful ? 1 : 0; return successful; } delete(val: T): boolean { const deleted = this.tree.deleteAll(val); this._size -= deleted ? 1 : 0; return deleted; } ceil(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(p.data, val) >= 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } floor(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(val, p.data) >= 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } higher(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(val, p.data) < 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } lower(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(p.data, val) < 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } first(): T | undefined { return this.tree.inOrder().next().value; } last(): T | undefined { return this.tree.reverseInOrder().next().value; } shift(): T | undefined { const first = this.first(); if (first === undefined) return undefined; this.delete(first); return first; } pop(): T | undefined { const last = this.last(); if (last === undefined) return undefined; this.delete(last); return last; } *[Symbol.iterator](): Generator<T, void, void> { for (const val of this.values()) yield val; } *keys(): Generator<T, void, void> { for (const val of this.values()) yield val; } *values(): Generator<T, undefined, void> { for (const val of this.tree.inOrder()) yield val; return undefined; } /** * Return a generator for reverse order traversing the set */ *rvalues(): Generator<T, undefined, void> { for (const val of this.tree.reverseInOrder()) yield val; return undefined; } }
3,074
Apple Redistribution into Boxes
Easy
<p>You are given an array <code>apple</code> of size <code>n</code> and an array <code>capacity</code> of size <code>m</code>.</p> <p>There are <code>n</code> packs where the <code>i<sup>th</sup></code> pack contains <code>apple[i]</code> apples. There are <code>m</code> boxes as well, and the <code>i<sup>th</sup></code> box has a capacity of <code>capacity[i]</code> apples.</p> <p>Return <em>the <strong>minimum</strong> number of boxes you need to select to redistribute these </em><code>n</code><em> packs of apples into boxes</em>.</p> <p><strong>Note</strong> that, apples from the same pack can be distributed into different boxes.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> apple = [1,3,2], capacity = [4,3,1,5,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> We will use boxes with capacities 4 and 5. It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> apple = [5,5,5], capacity = [2,4,2,7] <strong>Output:</strong> 4 <strong>Explanation:</strong> We will need to use all the boxes. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == apple.length &lt;= 50</code></li> <li><code>1 &lt;= m == capacity.length &lt;= 50</code></li> <li><code>1 &lt;= apple[i], capacity[i] &lt;= 50</code></li> <li>The input is generated such that it&#39;s possible to redistribute packs of apples into boxes.</li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: int minimumBoxes(vector<int>& apple, vector<int>& capacity) { sort(capacity.rbegin(), capacity.rend()); int s = accumulate(apple.begin(), apple.end(), 0); for (int i = 1;; ++i) { s -= capacity[i - 1]; if (s <= 0) { return i; } } } };
3,074
Apple Redistribution into Boxes
Easy
<p>You are given an array <code>apple</code> of size <code>n</code> and an array <code>capacity</code> of size <code>m</code>.</p> <p>There are <code>n</code> packs where the <code>i<sup>th</sup></code> pack contains <code>apple[i]</code> apples. There are <code>m</code> boxes as well, and the <code>i<sup>th</sup></code> box has a capacity of <code>capacity[i]</code> apples.</p> <p>Return <em>the <strong>minimum</strong> number of boxes you need to select to redistribute these </em><code>n</code><em> packs of apples into boxes</em>.</p> <p><strong>Note</strong> that, apples from the same pack can be distributed into different boxes.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> apple = [1,3,2], capacity = [4,3,1,5,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> We will use boxes with capacities 4 and 5. It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> apple = [5,5,5], capacity = [2,4,2,7] <strong>Output:</strong> 4 <strong>Explanation:</strong> We will need to use all the boxes. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == apple.length &lt;= 50</code></li> <li><code>1 &lt;= m == capacity.length &lt;= 50</code></li> <li><code>1 &lt;= apple[i], capacity[i] &lt;= 50</code></li> <li>The input is generated such that it&#39;s possible to redistribute packs of apples into boxes.</li> </ul>
Greedy; Array; Sorting
Go
func minimumBoxes(apple []int, capacity []int) int { sort.Ints(capacity) s := 0 for _, x := range apple { s += x } for i := 1; ; i++ { s -= capacity[len(capacity)-i] if s <= 0 { return i } } }
3,074
Apple Redistribution into Boxes
Easy
<p>You are given an array <code>apple</code> of size <code>n</code> and an array <code>capacity</code> of size <code>m</code>.</p> <p>There are <code>n</code> packs where the <code>i<sup>th</sup></code> pack contains <code>apple[i]</code> apples. There are <code>m</code> boxes as well, and the <code>i<sup>th</sup></code> box has a capacity of <code>capacity[i]</code> apples.</p> <p>Return <em>the <strong>minimum</strong> number of boxes you need to select to redistribute these </em><code>n</code><em> packs of apples into boxes</em>.</p> <p><strong>Note</strong> that, apples from the same pack can be distributed into different boxes.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> apple = [1,3,2], capacity = [4,3,1,5,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> We will use boxes with capacities 4 and 5. It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> apple = [5,5,5], capacity = [2,4,2,7] <strong>Output:</strong> 4 <strong>Explanation:</strong> We will need to use all the boxes. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == apple.length &lt;= 50</code></li> <li><code>1 &lt;= m == capacity.length &lt;= 50</code></li> <li><code>1 &lt;= apple[i], capacity[i] &lt;= 50</code></li> <li>The input is generated such that it&#39;s possible to redistribute packs of apples into boxes.</li> </ul>
Greedy; Array; Sorting
Java
class Solution { public int minimumBoxes(int[] apple, int[] capacity) { Arrays.sort(capacity); int s = 0; for (int x : apple) { s += x; } for (int i = 1, n = capacity.length;; ++i) { s -= capacity[n - i]; if (s <= 0) { return i; } } } }
3,074
Apple Redistribution into Boxes
Easy
<p>You are given an array <code>apple</code> of size <code>n</code> and an array <code>capacity</code> of size <code>m</code>.</p> <p>There are <code>n</code> packs where the <code>i<sup>th</sup></code> pack contains <code>apple[i]</code> apples. There are <code>m</code> boxes as well, and the <code>i<sup>th</sup></code> box has a capacity of <code>capacity[i]</code> apples.</p> <p>Return <em>the <strong>minimum</strong> number of boxes you need to select to redistribute these </em><code>n</code><em> packs of apples into boxes</em>.</p> <p><strong>Note</strong> that, apples from the same pack can be distributed into different boxes.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> apple = [1,3,2], capacity = [4,3,1,5,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> We will use boxes with capacities 4 and 5. It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> apple = [5,5,5], capacity = [2,4,2,7] <strong>Output:</strong> 4 <strong>Explanation:</strong> We will need to use all the boxes. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == apple.length &lt;= 50</code></li> <li><code>1 &lt;= m == capacity.length &lt;= 50</code></li> <li><code>1 &lt;= apple[i], capacity[i] &lt;= 50</code></li> <li>The input is generated such that it&#39;s possible to redistribute packs of apples into boxes.</li> </ul>
Greedy; Array; Sorting
Python
class Solution: def minimumBoxes(self, apple: List[int], capacity: List[int]) -> int: capacity.sort(reverse=True) s = sum(apple) for i, c in enumerate(capacity, 1): s -= c if s <= 0: return i
3,074
Apple Redistribution into Boxes
Easy
<p>You are given an array <code>apple</code> of size <code>n</code> and an array <code>capacity</code> of size <code>m</code>.</p> <p>There are <code>n</code> packs where the <code>i<sup>th</sup></code> pack contains <code>apple[i]</code> apples. There are <code>m</code> boxes as well, and the <code>i<sup>th</sup></code> box has a capacity of <code>capacity[i]</code> apples.</p> <p>Return <em>the <strong>minimum</strong> number of boxes you need to select to redistribute these </em><code>n</code><em> packs of apples into boxes</em>.</p> <p><strong>Note</strong> that, apples from the same pack can be distributed into different boxes.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> apple = [1,3,2], capacity = [4,3,1,5,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> We will use boxes with capacities 4 and 5. It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> apple = [5,5,5], capacity = [2,4,2,7] <strong>Output:</strong> 4 <strong>Explanation:</strong> We will need to use all the boxes. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == apple.length &lt;= 50</code></li> <li><code>1 &lt;= m == capacity.length &lt;= 50</code></li> <li><code>1 &lt;= apple[i], capacity[i] &lt;= 50</code></li> <li>The input is generated such that it&#39;s possible to redistribute packs of apples into boxes.</li> </ul>
Greedy; Array; Sorting
TypeScript
function minimumBoxes(apple: number[], capacity: number[]): number { capacity.sort((a, b) => b - a); let s = apple.reduce((acc, cur) => acc + cur, 0); for (let i = 1; ; ++i) { s -= capacity[i - 1]; if (s <= 0) { return i; } } }
3,075
Maximize Happiness of Selected Children
Medium
<p>You are given an array <code>happiness</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p> <p>There are <code>n</code> children standing in a queue, where the <code>i<sup>th</sup></code> child has <strong>happiness value</strong> <code>happiness[i]</code>. You want to select <code>k</code> children from these <code>n</code> children in <code>k</code> turns.</p> <p>In each turn, when you select a child, the <strong>happiness value</strong> of all the children that have <strong>not</strong> been selected till now decreases by <code>1</code>. Note that the happiness value <strong>cannot</strong> become negative and gets decremented <strong>only</strong> if it is positive.</p> <p>Return <em>the <strong>maximum</strong> sum of the happiness values of the selected children you can achieve by selecting </em><code>k</code> <em>children</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> happiness = [1,2,3], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can pick 2 children in the following way: - Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1]. - Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0. The sum of the happiness values of the selected children is 3 + 1 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> happiness = [1,1,1,1], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can pick 2 children in the following way: - Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0]. - Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0]. The sum of the happiness values of the selected children is 1 + 0 = 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> happiness = [2,3,4,5], k = 1 <strong>Output:</strong> 5 <strong>Explanation:</strong> We can pick 1 child in the following way: - Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3]. The sum of the happiness values of the selected children is 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == happiness.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= happiness[i] &lt;= 10<sup>8</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: long long maximumHappinessSum(vector<int>& happiness, int k) { sort(happiness.rbegin(), happiness.rend()); long long ans = 0; for (int i = 0, n = happiness.size(); i < k; ++i) { int x = happiness[i] - i; ans += max(x, 0); } return ans; } };
3,075
Maximize Happiness of Selected Children
Medium
<p>You are given an array <code>happiness</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p> <p>There are <code>n</code> children standing in a queue, where the <code>i<sup>th</sup></code> child has <strong>happiness value</strong> <code>happiness[i]</code>. You want to select <code>k</code> children from these <code>n</code> children in <code>k</code> turns.</p> <p>In each turn, when you select a child, the <strong>happiness value</strong> of all the children that have <strong>not</strong> been selected till now decreases by <code>1</code>. Note that the happiness value <strong>cannot</strong> become negative and gets decremented <strong>only</strong> if it is positive.</p> <p>Return <em>the <strong>maximum</strong> sum of the happiness values of the selected children you can achieve by selecting </em><code>k</code> <em>children</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> happiness = [1,2,3], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can pick 2 children in the following way: - Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1]. - Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0. The sum of the happiness values of the selected children is 3 + 1 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> happiness = [1,1,1,1], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can pick 2 children in the following way: - Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0]. - Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0]. The sum of the happiness values of the selected children is 1 + 0 = 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> happiness = [2,3,4,5], k = 1 <strong>Output:</strong> 5 <strong>Explanation:</strong> We can pick 1 child in the following way: - Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3]. The sum of the happiness values of the selected children is 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == happiness.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= happiness[i] &lt;= 10<sup>8</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array; Sorting
Go
func maximumHappinessSum(happiness []int, k int) (ans int64) { sort.Ints(happiness) for i := 0; i < k; i++ { x := happiness[len(happiness)-i-1] - i ans += int64(max(x, 0)) } return }
3,075
Maximize Happiness of Selected Children
Medium
<p>You are given an array <code>happiness</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p> <p>There are <code>n</code> children standing in a queue, where the <code>i<sup>th</sup></code> child has <strong>happiness value</strong> <code>happiness[i]</code>. You want to select <code>k</code> children from these <code>n</code> children in <code>k</code> turns.</p> <p>In each turn, when you select a child, the <strong>happiness value</strong> of all the children that have <strong>not</strong> been selected till now decreases by <code>1</code>. Note that the happiness value <strong>cannot</strong> become negative and gets decremented <strong>only</strong> if it is positive.</p> <p>Return <em>the <strong>maximum</strong> sum of the happiness values of the selected children you can achieve by selecting </em><code>k</code> <em>children</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> happiness = [1,2,3], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can pick 2 children in the following way: - Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1]. - Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0. The sum of the happiness values of the selected children is 3 + 1 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> happiness = [1,1,1,1], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can pick 2 children in the following way: - Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0]. - Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0]. The sum of the happiness values of the selected children is 1 + 0 = 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> happiness = [2,3,4,5], k = 1 <strong>Output:</strong> 5 <strong>Explanation:</strong> We can pick 1 child in the following way: - Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3]. The sum of the happiness values of the selected children is 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == happiness.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= happiness[i] &lt;= 10<sup>8</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array; Sorting
Java
class Solution { public long maximumHappinessSum(int[] happiness, int k) { Arrays.sort(happiness); long ans = 0; for (int i = 0, n = happiness.length; i < k; ++i) { int x = happiness[n - i - 1] - i; ans += Math.max(x, 0); } return ans; } }
3,075
Maximize Happiness of Selected Children
Medium
<p>You are given an array <code>happiness</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p> <p>There are <code>n</code> children standing in a queue, where the <code>i<sup>th</sup></code> child has <strong>happiness value</strong> <code>happiness[i]</code>. You want to select <code>k</code> children from these <code>n</code> children in <code>k</code> turns.</p> <p>In each turn, when you select a child, the <strong>happiness value</strong> of all the children that have <strong>not</strong> been selected till now decreases by <code>1</code>. Note that the happiness value <strong>cannot</strong> become negative and gets decremented <strong>only</strong> if it is positive.</p> <p>Return <em>the <strong>maximum</strong> sum of the happiness values of the selected children you can achieve by selecting </em><code>k</code> <em>children</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> happiness = [1,2,3], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can pick 2 children in the following way: - Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1]. - Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0. The sum of the happiness values of the selected children is 3 + 1 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> happiness = [1,1,1,1], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can pick 2 children in the following way: - Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0]. - Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0]. The sum of the happiness values of the selected children is 1 + 0 = 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> happiness = [2,3,4,5], k = 1 <strong>Output:</strong> 5 <strong>Explanation:</strong> We can pick 1 child in the following way: - Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3]. The sum of the happiness values of the selected children is 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == happiness.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= happiness[i] &lt;= 10<sup>8</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array; Sorting
Python
class Solution: def maximumHappinessSum(self, happiness: List[int], k: int) -> int: happiness.sort(reverse=True) ans = 0 for i, x in enumerate(happiness[:k]): x -= i ans += max(x, 0) return ans
3,075
Maximize Happiness of Selected Children
Medium
<p>You are given an array <code>happiness</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p> <p>There are <code>n</code> children standing in a queue, where the <code>i<sup>th</sup></code> child has <strong>happiness value</strong> <code>happiness[i]</code>. You want to select <code>k</code> children from these <code>n</code> children in <code>k</code> turns.</p> <p>In each turn, when you select a child, the <strong>happiness value</strong> of all the children that have <strong>not</strong> been selected till now decreases by <code>1</code>. Note that the happiness value <strong>cannot</strong> become negative and gets decremented <strong>only</strong> if it is positive.</p> <p>Return <em>the <strong>maximum</strong> sum of the happiness values of the selected children you can achieve by selecting </em><code>k</code> <em>children</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> happiness = [1,2,3], k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> We can pick 2 children in the following way: - Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1]. - Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0. The sum of the happiness values of the selected children is 3 + 1 = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> happiness = [1,1,1,1], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can pick 2 children in the following way: - Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0]. - Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0]. The sum of the happiness values of the selected children is 1 + 0 = 1. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> happiness = [2,3,4,5], k = 1 <strong>Output:</strong> 5 <strong>Explanation:</strong> We can pick 1 child in the following way: - Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3]. The sum of the happiness values of the selected children is 5. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == happiness.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= happiness[i] &lt;= 10<sup>8</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array; Sorting
TypeScript
function maximumHappinessSum(happiness: number[], k: number): number { happiness.sort((a, b) => b - a); let ans = 0; for (let i = 0; i < k; ++i) { const x = happiness[i] - i; ans += Math.max(x, 0); } return ans; }
3,076
Shortest Uncommon Substring in an Array
Medium
<p>You are given an array <code>arr</code> of size <code>n</code> consisting of <strong>non-empty</strong> strings.</p> <p>Find a string array <code>answer</code> of size <code>n</code> such that:</p> <ul> <li><code>answer[i]</code> is the <strong>shortest</strong> <span data-keyword="substring">substring</span> of <code>arr[i]</code> that does <strong>not</strong> occur as a substring in any other string in <code>arr</code>. If multiple such substrings exist, <code>answer[i]</code> should be the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span>. And if no such substring exists, <code>answer[i]</code> should be an empty string.</li> </ul> <p>Return <em>the array </em><code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [&quot;cab&quot;,&quot;ad&quot;,&quot;bad&quot;,&quot;c&quot;] <strong>Output:</strong> [&quot;ab&quot;,&quot;&quot;,&quot;ba&quot;,&quot;&quot;] <strong>Explanation:</strong> We have the following: - For the string &quot;cab&quot;, the shortest substring that does not occur in any other string is either &quot;ca&quot; or &quot;ab&quot;, we choose the lexicographically smaller substring, which is &quot;ab&quot;. - For the string &quot;ad&quot;, there is no substring that does not occur in any other string. - For the string &quot;bad&quot;, the shortest substring that does not occur in any other string is &quot;ba&quot;. - For the string &quot;c&quot;, there is no substring that does not occur in any other string. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [&quot;abc&quot;,&quot;bcd&quot;,&quot;abcd&quot;] <strong>Output:</strong> [&quot;&quot;,&quot;&quot;,&quot;abcd&quot;] <strong>Explanation:</strong> We have the following: - For the string &quot;abc&quot;, there is no substring that does not occur in any other string. - For the string &quot;bcd&quot;, there is no substring that does not occur in any other string. - For the string &quot;abcd&quot;, the shortest substring that does not occur in any other string is &quot;abcd&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == arr.length</code></li> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= arr[i].length &lt;= 20</code></li> <li><code>arr[i]</code> consists only of lowercase English letters.</li> </ul>
Trie; Array; Hash Table; String
C++
class Solution { public: vector<string> shortestSubstrings(vector<string>& arr) { int n = arr.size(); vector<string> ans(n); for (int i = 0; i < n; ++i) { int m = arr[i].size(); for (int j = 1; j <= m && ans[i].empty(); ++j) { for (int l = 0; l <= m - j; ++l) { string sub = arr[i].substr(l, j); if (ans[i].empty() || sub < ans[i]) { bool ok = true; for (int k = 0; k < n && ok; ++k) { if (k != i && arr[k].find(sub) != string::npos) { ok = false; } } if (ok) { ans[i] = sub; } } } } } return ans; } };
3,076
Shortest Uncommon Substring in an Array
Medium
<p>You are given an array <code>arr</code> of size <code>n</code> consisting of <strong>non-empty</strong> strings.</p> <p>Find a string array <code>answer</code> of size <code>n</code> such that:</p> <ul> <li><code>answer[i]</code> is the <strong>shortest</strong> <span data-keyword="substring">substring</span> of <code>arr[i]</code> that does <strong>not</strong> occur as a substring in any other string in <code>arr</code>. If multiple such substrings exist, <code>answer[i]</code> should be the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span>. And if no such substring exists, <code>answer[i]</code> should be an empty string.</li> </ul> <p>Return <em>the array </em><code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [&quot;cab&quot;,&quot;ad&quot;,&quot;bad&quot;,&quot;c&quot;] <strong>Output:</strong> [&quot;ab&quot;,&quot;&quot;,&quot;ba&quot;,&quot;&quot;] <strong>Explanation:</strong> We have the following: - For the string &quot;cab&quot;, the shortest substring that does not occur in any other string is either &quot;ca&quot; or &quot;ab&quot;, we choose the lexicographically smaller substring, which is &quot;ab&quot;. - For the string &quot;ad&quot;, there is no substring that does not occur in any other string. - For the string &quot;bad&quot;, the shortest substring that does not occur in any other string is &quot;ba&quot;. - For the string &quot;c&quot;, there is no substring that does not occur in any other string. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [&quot;abc&quot;,&quot;bcd&quot;,&quot;abcd&quot;] <strong>Output:</strong> [&quot;&quot;,&quot;&quot;,&quot;abcd&quot;] <strong>Explanation:</strong> We have the following: - For the string &quot;abc&quot;, there is no substring that does not occur in any other string. - For the string &quot;bcd&quot;, there is no substring that does not occur in any other string. - For the string &quot;abcd&quot;, the shortest substring that does not occur in any other string is &quot;abcd&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == arr.length</code></li> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= arr[i].length &lt;= 20</code></li> <li><code>arr[i]</code> consists only of lowercase English letters.</li> </ul>
Trie; Array; Hash Table; String
Go
func shortestSubstrings(arr []string) []string { ans := make([]string, len(arr)) for i, s := range arr { m := len(s) for j := 1; j <= m && len(ans[i]) == 0; j++ { for l := 0; l <= m-j; l++ { sub := s[l : l+j] if len(ans[i]) == 0 || ans[i] > sub { ok := true for k, t := range arr { if k != i && strings.Contains(t, sub) { ok = false break } } if ok { ans[i] = sub } } } } } return ans }
3,076
Shortest Uncommon Substring in an Array
Medium
<p>You are given an array <code>arr</code> of size <code>n</code> consisting of <strong>non-empty</strong> strings.</p> <p>Find a string array <code>answer</code> of size <code>n</code> such that:</p> <ul> <li><code>answer[i]</code> is the <strong>shortest</strong> <span data-keyword="substring">substring</span> of <code>arr[i]</code> that does <strong>not</strong> occur as a substring in any other string in <code>arr</code>. If multiple such substrings exist, <code>answer[i]</code> should be the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span>. And if no such substring exists, <code>answer[i]</code> should be an empty string.</li> </ul> <p>Return <em>the array </em><code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [&quot;cab&quot;,&quot;ad&quot;,&quot;bad&quot;,&quot;c&quot;] <strong>Output:</strong> [&quot;ab&quot;,&quot;&quot;,&quot;ba&quot;,&quot;&quot;] <strong>Explanation:</strong> We have the following: - For the string &quot;cab&quot;, the shortest substring that does not occur in any other string is either &quot;ca&quot; or &quot;ab&quot;, we choose the lexicographically smaller substring, which is &quot;ab&quot;. - For the string &quot;ad&quot;, there is no substring that does not occur in any other string. - For the string &quot;bad&quot;, the shortest substring that does not occur in any other string is &quot;ba&quot;. - For the string &quot;c&quot;, there is no substring that does not occur in any other string. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [&quot;abc&quot;,&quot;bcd&quot;,&quot;abcd&quot;] <strong>Output:</strong> [&quot;&quot;,&quot;&quot;,&quot;abcd&quot;] <strong>Explanation:</strong> We have the following: - For the string &quot;abc&quot;, there is no substring that does not occur in any other string. - For the string &quot;bcd&quot;, there is no substring that does not occur in any other string. - For the string &quot;abcd&quot;, the shortest substring that does not occur in any other string is &quot;abcd&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == arr.length</code></li> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= arr[i].length &lt;= 20</code></li> <li><code>arr[i]</code> consists only of lowercase English letters.</li> </ul>
Trie; Array; Hash Table; String
Java
class Solution { public String[] shortestSubstrings(String[] arr) { int n = arr.length; String[] ans = new String[n]; Arrays.fill(ans, ""); for (int i = 0; i < n; ++i) { int m = arr[i].length(); for (int j = 1; j <= m && ans[i].isEmpty(); ++j) { for (int l = 0; l <= m - j; ++l) { String sub = arr[i].substring(l, l + j); if (ans[i].isEmpty() || sub.compareTo(ans[i]) < 0) { boolean ok = true; for (int k = 0; k < n && ok; ++k) { if (k != i && arr[k].contains(sub)) { ok = false; } } if (ok) { ans[i] = sub; } } } } } return ans; } }
3,076
Shortest Uncommon Substring in an Array
Medium
<p>You are given an array <code>arr</code> of size <code>n</code> consisting of <strong>non-empty</strong> strings.</p> <p>Find a string array <code>answer</code> of size <code>n</code> such that:</p> <ul> <li><code>answer[i]</code> is the <strong>shortest</strong> <span data-keyword="substring">substring</span> of <code>arr[i]</code> that does <strong>not</strong> occur as a substring in any other string in <code>arr</code>. If multiple such substrings exist, <code>answer[i]</code> should be the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span>. And if no such substring exists, <code>answer[i]</code> should be an empty string.</li> </ul> <p>Return <em>the array </em><code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [&quot;cab&quot;,&quot;ad&quot;,&quot;bad&quot;,&quot;c&quot;] <strong>Output:</strong> [&quot;ab&quot;,&quot;&quot;,&quot;ba&quot;,&quot;&quot;] <strong>Explanation:</strong> We have the following: - For the string &quot;cab&quot;, the shortest substring that does not occur in any other string is either &quot;ca&quot; or &quot;ab&quot;, we choose the lexicographically smaller substring, which is &quot;ab&quot;. - For the string &quot;ad&quot;, there is no substring that does not occur in any other string. - For the string &quot;bad&quot;, the shortest substring that does not occur in any other string is &quot;ba&quot;. - For the string &quot;c&quot;, there is no substring that does not occur in any other string. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [&quot;abc&quot;,&quot;bcd&quot;,&quot;abcd&quot;] <strong>Output:</strong> [&quot;&quot;,&quot;&quot;,&quot;abcd&quot;] <strong>Explanation:</strong> We have the following: - For the string &quot;abc&quot;, there is no substring that does not occur in any other string. - For the string &quot;bcd&quot;, there is no substring that does not occur in any other string. - For the string &quot;abcd&quot;, the shortest substring that does not occur in any other string is &quot;abcd&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == arr.length</code></li> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= arr[i].length &lt;= 20</code></li> <li><code>arr[i]</code> consists only of lowercase English letters.</li> </ul>
Trie; Array; Hash Table; String
Python
class Solution: def shortestSubstrings(self, arr: List[str]) -> List[str]: ans = [""] * len(arr) for i, s in enumerate(arr): m = len(s) for j in range(1, m + 1): for l in range(m - j + 1): sub = s[l : l + j] if not ans[i] or ans[i] > sub: if all(k == i or sub not in t for k, t in enumerate(arr)): ans[i] = sub if ans[i]: break return ans
3,076
Shortest Uncommon Substring in an Array
Medium
<p>You are given an array <code>arr</code> of size <code>n</code> consisting of <strong>non-empty</strong> strings.</p> <p>Find a string array <code>answer</code> of size <code>n</code> such that:</p> <ul> <li><code>answer[i]</code> is the <strong>shortest</strong> <span data-keyword="substring">substring</span> of <code>arr[i]</code> that does <strong>not</strong> occur as a substring in any other string in <code>arr</code>. If multiple such substrings exist, <code>answer[i]</code> should be the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span>. And if no such substring exists, <code>answer[i]</code> should be an empty string.</li> </ul> <p>Return <em>the array </em><code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [&quot;cab&quot;,&quot;ad&quot;,&quot;bad&quot;,&quot;c&quot;] <strong>Output:</strong> [&quot;ab&quot;,&quot;&quot;,&quot;ba&quot;,&quot;&quot;] <strong>Explanation:</strong> We have the following: - For the string &quot;cab&quot;, the shortest substring that does not occur in any other string is either &quot;ca&quot; or &quot;ab&quot;, we choose the lexicographically smaller substring, which is &quot;ab&quot;. - For the string &quot;ad&quot;, there is no substring that does not occur in any other string. - For the string &quot;bad&quot;, the shortest substring that does not occur in any other string is &quot;ba&quot;. - For the string &quot;c&quot;, there is no substring that does not occur in any other string. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [&quot;abc&quot;,&quot;bcd&quot;,&quot;abcd&quot;] <strong>Output:</strong> [&quot;&quot;,&quot;&quot;,&quot;abcd&quot;] <strong>Explanation:</strong> We have the following: - For the string &quot;abc&quot;, there is no substring that does not occur in any other string. - For the string &quot;bcd&quot;, there is no substring that does not occur in any other string. - For the string &quot;abcd&quot;, the shortest substring that does not occur in any other string is &quot;abcd&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == arr.length</code></li> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= arr[i].length &lt;= 20</code></li> <li><code>arr[i]</code> consists only of lowercase English letters.</li> </ul>
Trie; Array; Hash Table; String
TypeScript
function shortestSubstrings(arr: string[]): string[] { const n: number = arr.length; const ans: string[] = Array(n).fill(''); for (let i = 0; i < n; ++i) { const m: number = arr[i].length; for (let j = 1; j <= m && ans[i] === ''; ++j) { for (let l = 0; l <= m - j; ++l) { const sub: string = arr[i].slice(l, l + j); if (ans[i] === '' || sub.localeCompare(ans[i]) < 0) { let ok: boolean = true; for (let k = 0; k < n && ok; ++k) { if (k !== i && arr[k].includes(sub)) { ok = false; } } if (ok) { ans[i] = sub; } } } } } return ans; }
3,077
Maximum Strength of K Disjoint Subarrays
Hard
<p>You are given an array of integers <code>nums</code> with length <code>n</code>, and a positive <strong>odd</strong> integer <code>k</code>.</p> <p>Select exactly <b><code>k</code></b> disjoint <span data-keyword="subarray-nonempty">subarrays</span> <b><code>sub<sub>1</sub>, sub<sub>2</sub>, ..., sub<sub>k</sub></code></b> from <code>nums</code> such that the last element of <code>sub<sub>i</sub></code> appears before the first element of <code>sub<sub>{i+1}</sub></code> for all <code>1 &lt;= i &lt;= k-1</code>. The goal is to maximize their combined strength.</p> <p>The strength of the selected subarrays is defined as:</p> <p><code>strength = k * sum(sub<sub>1</sub>)- (k - 1) * sum(sub<sub>2</sub>) + (k - 2) * sum(sub<sub>3</sub>) - ... - 2 * sum(sub<sub>{k-1}</sub>) + sum(sub<sub>k</sub>)</code></p> <p>where <b><code>sum(sub<sub>i</sub>)</code></b> is the sum of the elements in the <code>i</code>-th subarray.</p> <p>Return the <strong>maximum</strong> possible strength that can be obtained from selecting exactly <b><code>k</code></b> disjoint subarrays from <code>nums</code>.</p> <p><strong>Note</strong> that the chosen subarrays <strong>don&#39;t</strong> need to cover the entire array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,-1,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p>The best possible way to select 3 subarrays is: nums[0..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p> <p><code>strength = 3 * (1 + 2 + 3) - 2 * (-1) + 2 = 22</code></p> <p>&nbsp;</p> <p><strong class="example">Example 2:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [12,-2,-2,-2,-2], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">64</span></p> <p><strong>Explanation:</strong></p> <p>The only possible way to select 5 disjoint subarrays is: nums[0..0], nums[1..1], nums[2..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p> <p><code>strength = 5 * 12 - 4 * (-2) + 3 * (-2) - 2 * (-2) + (-2) = 64</code></p> <p><strong class="example">Example 3:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3], k = </span>1</p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The best possible way to select 1 subarray is: nums[0..0]. The strength is -1.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>1 &lt;= n * k &lt;= 10<sup>6</sup></code></li> <li><code>k</code> is odd.</li> </ul>
Array; Dynamic Programming; Prefix Sum
C++
class Solution { public: long long maximumStrength(vector<int>& nums, int k) { int n = nums.size(); long long f[n + 1][k + 1][2]; memset(f, -0x3f3f3f3f3f3f3f3f, sizeof(f)); f[0][0][0] = 0; for (int i = 1; i <= n; i++) { int x = nums[i - 1]; for (int j = 0; j <= k; j++) { long long sign = (j & 1) == 1 ? 1 : -1; long long val = sign * x * (k - j + 1); f[i][j][0] = max(f[i - 1][j][0], f[i - 1][j][1]); f[i][j][1] = max(f[i][j][1], f[i - 1][j][1] + val); if (j > 0) { long long t = max(f[i - 1][j - 1][0], f[i - 1][j - 1][1]) + val; f[i][j][1] = max(f[i][j][1], t); } } } return max(f[n][k][0], f[n][k][1]); } };
3,077
Maximum Strength of K Disjoint Subarrays
Hard
<p>You are given an array of integers <code>nums</code> with length <code>n</code>, and a positive <strong>odd</strong> integer <code>k</code>.</p> <p>Select exactly <b><code>k</code></b> disjoint <span data-keyword="subarray-nonempty">subarrays</span> <b><code>sub<sub>1</sub>, sub<sub>2</sub>, ..., sub<sub>k</sub></code></b> from <code>nums</code> such that the last element of <code>sub<sub>i</sub></code> appears before the first element of <code>sub<sub>{i+1}</sub></code> for all <code>1 &lt;= i &lt;= k-1</code>. The goal is to maximize their combined strength.</p> <p>The strength of the selected subarrays is defined as:</p> <p><code>strength = k * sum(sub<sub>1</sub>)- (k - 1) * sum(sub<sub>2</sub>) + (k - 2) * sum(sub<sub>3</sub>) - ... - 2 * sum(sub<sub>{k-1}</sub>) + sum(sub<sub>k</sub>)</code></p> <p>where <b><code>sum(sub<sub>i</sub>)</code></b> is the sum of the elements in the <code>i</code>-th subarray.</p> <p>Return the <strong>maximum</strong> possible strength that can be obtained from selecting exactly <b><code>k</code></b> disjoint subarrays from <code>nums</code>.</p> <p><strong>Note</strong> that the chosen subarrays <strong>don&#39;t</strong> need to cover the entire array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,-1,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p>The best possible way to select 3 subarrays is: nums[0..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p> <p><code>strength = 3 * (1 + 2 + 3) - 2 * (-1) + 2 = 22</code></p> <p>&nbsp;</p> <p><strong class="example">Example 2:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [12,-2,-2,-2,-2], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">64</span></p> <p><strong>Explanation:</strong></p> <p>The only possible way to select 5 disjoint subarrays is: nums[0..0], nums[1..1], nums[2..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p> <p><code>strength = 5 * 12 - 4 * (-2) + 3 * (-2) - 2 * (-2) + (-2) = 64</code></p> <p><strong class="example">Example 3:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3], k = </span>1</p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The best possible way to select 1 subarray is: nums[0..0]. The strength is -1.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>1 &lt;= n * k &lt;= 10<sup>6</sup></code></li> <li><code>k</code> is odd.</li> </ul>
Array; Dynamic Programming; Prefix Sum
Go
func maximumStrength(nums []int, k int) int64 { n := len(nums) f := make([][][]int64, n+1) const inf int64 = math.MinInt64 / 2 for i := range f { f[i] = make([][]int64, k+1) for j := range f[i] { f[i][j] = []int64{inf, inf} } } f[0][0][0] = 0 for i := 1; i <= n; i++ { x := nums[i-1] for j := 0; j <= k; j++ { sign := int64(-1) if j&1 == 1 { sign = 1 } val := sign * int64(x) * int64(k-j+1) f[i][j][0] = max(f[i-1][j][0], f[i-1][j][1]) f[i][j][1] = max(f[i][j][1], f[i-1][j][1]+val) if j > 0 { t := max(f[i-1][j-1][0], f[i-1][j-1][1]) + val f[i][j][1] = max(f[i][j][1], t) } } } return max(f[n][k][0], f[n][k][1]) }
3,077
Maximum Strength of K Disjoint Subarrays
Hard
<p>You are given an array of integers <code>nums</code> with length <code>n</code>, and a positive <strong>odd</strong> integer <code>k</code>.</p> <p>Select exactly <b><code>k</code></b> disjoint <span data-keyword="subarray-nonempty">subarrays</span> <b><code>sub<sub>1</sub>, sub<sub>2</sub>, ..., sub<sub>k</sub></code></b> from <code>nums</code> such that the last element of <code>sub<sub>i</sub></code> appears before the first element of <code>sub<sub>{i+1}</sub></code> for all <code>1 &lt;= i &lt;= k-1</code>. The goal is to maximize their combined strength.</p> <p>The strength of the selected subarrays is defined as:</p> <p><code>strength = k * sum(sub<sub>1</sub>)- (k - 1) * sum(sub<sub>2</sub>) + (k - 2) * sum(sub<sub>3</sub>) - ... - 2 * sum(sub<sub>{k-1}</sub>) + sum(sub<sub>k</sub>)</code></p> <p>where <b><code>sum(sub<sub>i</sub>)</code></b> is the sum of the elements in the <code>i</code>-th subarray.</p> <p>Return the <strong>maximum</strong> possible strength that can be obtained from selecting exactly <b><code>k</code></b> disjoint subarrays from <code>nums</code>.</p> <p><strong>Note</strong> that the chosen subarrays <strong>don&#39;t</strong> need to cover the entire array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,-1,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p>The best possible way to select 3 subarrays is: nums[0..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p> <p><code>strength = 3 * (1 + 2 + 3) - 2 * (-1) + 2 = 22</code></p> <p>&nbsp;</p> <p><strong class="example">Example 2:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [12,-2,-2,-2,-2], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">64</span></p> <p><strong>Explanation:</strong></p> <p>The only possible way to select 5 disjoint subarrays is: nums[0..0], nums[1..1], nums[2..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p> <p><code>strength = 5 * 12 - 4 * (-2) + 3 * (-2) - 2 * (-2) + (-2) = 64</code></p> <p><strong class="example">Example 3:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3], k = </span>1</p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The best possible way to select 1 subarray is: nums[0..0]. The strength is -1.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>1 &lt;= n * k &lt;= 10<sup>6</sup></code></li> <li><code>k</code> is odd.</li> </ul>
Array; Dynamic Programming; Prefix Sum
Java
class Solution { public long maximumStrength(int[] nums, int k) { int n = nums.length; long[][][] f = new long[n + 1][k + 1][2]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= k; j++) { Arrays.fill(f[i][j], Long.MIN_VALUE / 2); } } f[0][0][0] = 0; for (int i = 1; i <= n; i++) { int x = nums[i - 1]; for (int j = 0; j <= k; j++) { long sign = (j & 1) == 1 ? 1 : -1; long val = sign * x * (k - j + 1); f[i][j][0] = Math.max(f[i - 1][j][0], f[i - 1][j][1]); f[i][j][1] = Math.max(f[i][j][1], f[i - 1][j][1] + val); if (j > 0) { long t = Math.max(f[i - 1][j - 1][0], f[i - 1][j - 1][1]) + val; f[i][j][1] = Math.max(f[i][j][1], t); } } } return Math.max(f[n][k][0], f[n][k][1]); } }
3,077
Maximum Strength of K Disjoint Subarrays
Hard
<p>You are given an array of integers <code>nums</code> with length <code>n</code>, and a positive <strong>odd</strong> integer <code>k</code>.</p> <p>Select exactly <b><code>k</code></b> disjoint <span data-keyword="subarray-nonempty">subarrays</span> <b><code>sub<sub>1</sub>, sub<sub>2</sub>, ..., sub<sub>k</sub></code></b> from <code>nums</code> such that the last element of <code>sub<sub>i</sub></code> appears before the first element of <code>sub<sub>{i+1}</sub></code> for all <code>1 &lt;= i &lt;= k-1</code>. The goal is to maximize their combined strength.</p> <p>The strength of the selected subarrays is defined as:</p> <p><code>strength = k * sum(sub<sub>1</sub>)- (k - 1) * sum(sub<sub>2</sub>) + (k - 2) * sum(sub<sub>3</sub>) - ... - 2 * sum(sub<sub>{k-1}</sub>) + sum(sub<sub>k</sub>)</code></p> <p>where <b><code>sum(sub<sub>i</sub>)</code></b> is the sum of the elements in the <code>i</code>-th subarray.</p> <p>Return the <strong>maximum</strong> possible strength that can be obtained from selecting exactly <b><code>k</code></b> disjoint subarrays from <code>nums</code>.</p> <p><strong>Note</strong> that the chosen subarrays <strong>don&#39;t</strong> need to cover the entire array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,-1,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p>The best possible way to select 3 subarrays is: nums[0..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p> <p><code>strength = 3 * (1 + 2 + 3) - 2 * (-1) + 2 = 22</code></p> <p>&nbsp;</p> <p><strong class="example">Example 2:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [12,-2,-2,-2,-2], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">64</span></p> <p><strong>Explanation:</strong></p> <p>The only possible way to select 5 disjoint subarrays is: nums[0..0], nums[1..1], nums[2..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p> <p><code>strength = 5 * 12 - 4 * (-2) + 3 * (-2) - 2 * (-2) + (-2) = 64</code></p> <p><strong class="example">Example 3:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3], k = </span>1</p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The best possible way to select 1 subarray is: nums[0..0]. The strength is -1.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>1 &lt;= n * k &lt;= 10<sup>6</sup></code></li> <li><code>k</code> is odd.</li> </ul>
Array; Dynamic Programming; Prefix Sum
Python
class Solution: def maximumStrength(self, nums: List[int], k: int) -> int: n = len(nums) f = [[[-inf, -inf] for _ in range(k + 1)] for _ in range(n + 1)] f[0][0][0] = 0 for i, x in enumerate(nums, 1): for j in range(k + 1): sign = 1 if j & 1 else -1 f[i][j][0] = max(f[i - 1][j][0], f[i - 1][j][1]) f[i][j][1] = max(f[i][j][1], f[i - 1][j][1] + sign * x * (k - j + 1)) if j: f[i][j][1] = max( f[i][j][1], max(f[i - 1][j - 1]) + sign * x * (k - j + 1) ) return max(f[n][k])
3,077
Maximum Strength of K Disjoint Subarrays
Hard
<p>You are given an array of integers <code>nums</code> with length <code>n</code>, and a positive <strong>odd</strong> integer <code>k</code>.</p> <p>Select exactly <b><code>k</code></b> disjoint <span data-keyword="subarray-nonempty">subarrays</span> <b><code>sub<sub>1</sub>, sub<sub>2</sub>, ..., sub<sub>k</sub></code></b> from <code>nums</code> such that the last element of <code>sub<sub>i</sub></code> appears before the first element of <code>sub<sub>{i+1}</sub></code> for all <code>1 &lt;= i &lt;= k-1</code>. The goal is to maximize their combined strength.</p> <p>The strength of the selected subarrays is defined as:</p> <p><code>strength = k * sum(sub<sub>1</sub>)- (k - 1) * sum(sub<sub>2</sub>) + (k - 2) * sum(sub<sub>3</sub>) - ... - 2 * sum(sub<sub>{k-1}</sub>) + sum(sub<sub>k</sub>)</code></p> <p>where <b><code>sum(sub<sub>i</sub>)</code></b> is the sum of the elements in the <code>i</code>-th subarray.</p> <p>Return the <strong>maximum</strong> possible strength that can be obtained from selecting exactly <b><code>k</code></b> disjoint subarrays from <code>nums</code>.</p> <p><strong>Note</strong> that the chosen subarrays <strong>don&#39;t</strong> need to cover the entire array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,-1,2], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">22</span></p> <p><strong>Explanation:</strong></p> <p>The best possible way to select 3 subarrays is: nums[0..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p> <p><code>strength = 3 * (1 + 2 + 3) - 2 * (-1) + 2 = 22</code></p> <p>&nbsp;</p> <p><strong class="example">Example 2:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [12,-2,-2,-2,-2], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">64</span></p> <p><strong>Explanation:</strong></p> <p>The only possible way to select 5 disjoint subarrays is: nums[0..0], nums[1..1], nums[2..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:</p> <p><code>strength = 5 * 12 - 4 * (-2) + 3 * (-2) - 2 * (-2) + (-2) = 64</code></p> <p><strong class="example">Example 3:</strong></p> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,-3], k = </span>1</p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The best possible way to select 1 subarray is: nums[0..0]. The strength is -1.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> <li><code>1 &lt;= n * k &lt;= 10<sup>6</sup></code></li> <li><code>k</code> is odd.</li> </ul>
Array; Dynamic Programming; Prefix Sum
TypeScript
function maximumStrength(nums: number[], k: number): number { const n: number = nums.length; const f: number[][][] = Array.from({ length: n + 1 }, () => Array.from({ length: k + 1 }, () => [-Infinity, -Infinity]), ); f[0][0][0] = 0; for (let i = 1; i <= n; i++) { const x: number = nums[i - 1]; for (let j = 0; j <= k; j++) { const sign: number = (j & 1) === 1 ? 1 : -1; const val: number = sign * x * (k - j + 1); f[i][j][0] = Math.max(f[i - 1][j][0], f[i - 1][j][1]); f[i][j][1] = Math.max(f[i][j][1], f[i - 1][j][1] + val); if (j > 0) { f[i][j][1] = Math.max(f[i][j][1], Math.max(...f[i - 1][j - 1]) + val); } } } return Math.max(...f[n][k]); }
3,078
Match Alphanumerical Pattern in Matrix I
Medium
<p>You are given a 2D integer matrix <code>board</code> and a 2D character matrix <code>pattern</code>. Where <code>0 &lt;= board[r][c] &lt;= 9</code> and each element of <code>pattern</code> is either a digit or a lowercase English letter.</p> <p>Your task is to find a <span data-keyword="submatrix">submatrix</span> of <code>board</code> that <strong>matches</strong> <code>pattern</code>.</p> <p>An integer matrix <code>part</code> matches <code>pattern</code> if we can replace cells containing letters in <code>pattern</code> with some digits (each <strong>distinct</strong> letter with a <strong>unique</strong> digit) in such a way that the resulting matrix becomes identical to the integer matrix <code>part</code>. In other words,</p> <ul> <li>The matrices have identical dimensions.</li> <li>If <code>pattern[r][c]</code> is a digit, then <code>part[r][c]</code> must be the <strong>same</strong> digit.</li> <li>If <code>pattern[r][c]</code> is a letter <code>x</code>: <ul> <li>For every <code>pattern[i][j] == x</code>, <code>part[i][j]</code> must be the <strong>same</strong> as <code>part[r][c]</code>.</li> <li>For every <code>pattern[i][j] != x</code>, <code>part[i][j]</code> must be <strong>different</strong> than <code>part[r][c]</code>.<span style="display: none;"> </span></li> </ul> </li> </ul> <p>Return <em>an array of length </em><code>2</code><em> containing the row number and column number of the upper-left corner of a submatrix of </em><code>board</code><em> which matches </em><code>pattern</code><em>. If there is more than one such submatrix, return the coordinates of the submatrix with the lowest row index, and in case there is still a tie, return the coordinates of the submatrix with the lowest column index. If there are no suitable answers, return</em> <code>[-1, -1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">1</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,2,2],[2,2,3],[2,3,3]], pattern = [&quot;ab&quot;,&quot;bb&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0]</span></p> <p><strong>Explanation:</strong> If we consider this mapping: <code>&quot;a&quot; -&gt; 1</code> and <code>&quot;b&quot; -&gt; 2</code>; the submatrix with the upper-left corner <code>(0,0)</code> is a match as outlined in the matrix above.</p> <p>Note that the submatrix with the upper-left corner (1,1) is also a match but since it comes after the other one, we return <code>[0,0]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">3</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">4</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,1,2],[3,3,4],[6,6,6]], pattern = [&quot;ab&quot;,&quot;66&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1]</span></p> <p><strong>Explanation:</strong> If we consider this mapping: <code>&quot;a&quot; -&gt; 3</code> and <code>&quot;b&quot; -&gt; 4</code>; the submatrix with the upper-left corner <code>(1,1)</code> is a match as outlined in the matrix above.</p> <p>Note that since the corresponding values of <code>&quot;a&quot;</code> and <code>&quot;b&quot;</code> must differ, the submatrix with the upper-left corner <code>(1,0)</code> is not a match. Hence, we return <code>[1,1]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,2],[2,1]], pattern = [&quot;xx&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p> <p><strong>Explanation:</strong> Since the values of the matched submatrix must be the same, there is no match. Hence, we return <code>[-1,-1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= board.length &lt;= 50</code></li> <li><code>1 &lt;= board[i].length &lt;= 50</code></li> <li><code>0 &lt;= board[i][j] &lt;= 9</code></li> <li><code>1 &lt;= pattern.length &lt;= 50</code></li> <li><code>1 &lt;= pattern[i].length &lt;= 50</code></li> <li><code>pattern[i][j]</code> is either a digit represented as a string or a lowercase English letter.</li> </ul>
Array; Hash Table; String; Matrix
C++
class Solution { public: vector<int> findPattern(vector<vector<int>>& board, vector<string>& pattern) { int m = board.size(), n = board[0].size(); int r = pattern.size(), c = pattern[0].size(); auto check = [&](int i, int j) { vector<int> d1(26, -1); vector<int> d2(10, -1); for (int a = 0; a < r; ++a) { for (int b = 0; b < c; ++b) { int x = i + a, y = j + b; if (isdigit(pattern[a][b])) { int v = pattern[a][b] - '0'; if (v != board[x][y]) { return false; } } else { int v = pattern[a][b] - 'a'; if (d1[v] != -1 && d1[v] != board[x][y]) { return false; } if (d2[board[x][y]] != -1 && d2[board[x][y]] != v) { return false; } d1[v] = board[x][y]; d2[board[x][y]] = v; } } } return true; }; for (int i = 0; i < m - r + 1; ++i) { for (int j = 0; j < n - c + 1; ++j) { if (check(i, j)) { return {i, j}; } } } return {-1, -1}; } };
3,078
Match Alphanumerical Pattern in Matrix I
Medium
<p>You are given a 2D integer matrix <code>board</code> and a 2D character matrix <code>pattern</code>. Where <code>0 &lt;= board[r][c] &lt;= 9</code> and each element of <code>pattern</code> is either a digit or a lowercase English letter.</p> <p>Your task is to find a <span data-keyword="submatrix">submatrix</span> of <code>board</code> that <strong>matches</strong> <code>pattern</code>.</p> <p>An integer matrix <code>part</code> matches <code>pattern</code> if we can replace cells containing letters in <code>pattern</code> with some digits (each <strong>distinct</strong> letter with a <strong>unique</strong> digit) in such a way that the resulting matrix becomes identical to the integer matrix <code>part</code>. In other words,</p> <ul> <li>The matrices have identical dimensions.</li> <li>If <code>pattern[r][c]</code> is a digit, then <code>part[r][c]</code> must be the <strong>same</strong> digit.</li> <li>If <code>pattern[r][c]</code> is a letter <code>x</code>: <ul> <li>For every <code>pattern[i][j] == x</code>, <code>part[i][j]</code> must be the <strong>same</strong> as <code>part[r][c]</code>.</li> <li>For every <code>pattern[i][j] != x</code>, <code>part[i][j]</code> must be <strong>different</strong> than <code>part[r][c]</code>.<span style="display: none;"> </span></li> </ul> </li> </ul> <p>Return <em>an array of length </em><code>2</code><em> containing the row number and column number of the upper-left corner of a submatrix of </em><code>board</code><em> which matches </em><code>pattern</code><em>. If there is more than one such submatrix, return the coordinates of the submatrix with the lowest row index, and in case there is still a tie, return the coordinates of the submatrix with the lowest column index. If there are no suitable answers, return</em> <code>[-1, -1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">1</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,2,2],[2,2,3],[2,3,3]], pattern = [&quot;ab&quot;,&quot;bb&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0]</span></p> <p><strong>Explanation:</strong> If we consider this mapping: <code>&quot;a&quot; -&gt; 1</code> and <code>&quot;b&quot; -&gt; 2</code>; the submatrix with the upper-left corner <code>(0,0)</code> is a match as outlined in the matrix above.</p> <p>Note that the submatrix with the upper-left corner (1,1) is also a match but since it comes after the other one, we return <code>[0,0]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">3</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">4</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,1,2],[3,3,4],[6,6,6]], pattern = [&quot;ab&quot;,&quot;66&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1]</span></p> <p><strong>Explanation:</strong> If we consider this mapping: <code>&quot;a&quot; -&gt; 3</code> and <code>&quot;b&quot; -&gt; 4</code>; the submatrix with the upper-left corner <code>(1,1)</code> is a match as outlined in the matrix above.</p> <p>Note that since the corresponding values of <code>&quot;a&quot;</code> and <code>&quot;b&quot;</code> must differ, the submatrix with the upper-left corner <code>(1,0)</code> is not a match. Hence, we return <code>[1,1]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,2],[2,1]], pattern = [&quot;xx&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p> <p><strong>Explanation:</strong> Since the values of the matched submatrix must be the same, there is no match. Hence, we return <code>[-1,-1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= board.length &lt;= 50</code></li> <li><code>1 &lt;= board[i].length &lt;= 50</code></li> <li><code>0 &lt;= board[i][j] &lt;= 9</code></li> <li><code>1 &lt;= pattern.length &lt;= 50</code></li> <li><code>1 &lt;= pattern[i].length &lt;= 50</code></li> <li><code>pattern[i][j]</code> is either a digit represented as a string or a lowercase English letter.</li> </ul>
Array; Hash Table; String; Matrix
Go
func findPattern(board [][]int, pattern []string) []int { m, n := len(board), len(board[0]) r, c := len(pattern), len(pattern[0]) check := func(i, j int) bool { d1 := [26]int{} d2 := [10]int{} for a := 0; a < r; a++ { for b := 0; b < c; b++ { x, y := i+a, j+b if pattern[a][b] >= '0' && pattern[a][b] <= '9' { v := int(pattern[a][b] - '0') if v != board[x][y] { return false } } else { v := int(pattern[a][b] - 'a') if d1[v] > 0 && d1[v]-1 != board[x][y] { return false } if d2[board[x][y]] > 0 && d2[board[x][y]]-1 != v { return false } d1[v] = board[x][y] + 1 d2[board[x][y]] = v + 1 } } } return true } for i := 0; i < m-r+1; i++ { for j := 0; j < n-c+1; j++ { if check(i, j) { return []int{i, j} } } } return []int{-1, -1} }
3,078
Match Alphanumerical Pattern in Matrix I
Medium
<p>You are given a 2D integer matrix <code>board</code> and a 2D character matrix <code>pattern</code>. Where <code>0 &lt;= board[r][c] &lt;= 9</code> and each element of <code>pattern</code> is either a digit or a lowercase English letter.</p> <p>Your task is to find a <span data-keyword="submatrix">submatrix</span> of <code>board</code> that <strong>matches</strong> <code>pattern</code>.</p> <p>An integer matrix <code>part</code> matches <code>pattern</code> if we can replace cells containing letters in <code>pattern</code> with some digits (each <strong>distinct</strong> letter with a <strong>unique</strong> digit) in such a way that the resulting matrix becomes identical to the integer matrix <code>part</code>. In other words,</p> <ul> <li>The matrices have identical dimensions.</li> <li>If <code>pattern[r][c]</code> is a digit, then <code>part[r][c]</code> must be the <strong>same</strong> digit.</li> <li>If <code>pattern[r][c]</code> is a letter <code>x</code>: <ul> <li>For every <code>pattern[i][j] == x</code>, <code>part[i][j]</code> must be the <strong>same</strong> as <code>part[r][c]</code>.</li> <li>For every <code>pattern[i][j] != x</code>, <code>part[i][j]</code> must be <strong>different</strong> than <code>part[r][c]</code>.<span style="display: none;"> </span></li> </ul> </li> </ul> <p>Return <em>an array of length </em><code>2</code><em> containing the row number and column number of the upper-left corner of a submatrix of </em><code>board</code><em> which matches </em><code>pattern</code><em>. If there is more than one such submatrix, return the coordinates of the submatrix with the lowest row index, and in case there is still a tie, return the coordinates of the submatrix with the lowest column index. If there are no suitable answers, return</em> <code>[-1, -1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">1</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,2,2],[2,2,3],[2,3,3]], pattern = [&quot;ab&quot;,&quot;bb&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0]</span></p> <p><strong>Explanation:</strong> If we consider this mapping: <code>&quot;a&quot; -&gt; 1</code> and <code>&quot;b&quot; -&gt; 2</code>; the submatrix with the upper-left corner <code>(0,0)</code> is a match as outlined in the matrix above.</p> <p>Note that the submatrix with the upper-left corner (1,1) is also a match but since it comes after the other one, we return <code>[0,0]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">3</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">4</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,1,2],[3,3,4],[6,6,6]], pattern = [&quot;ab&quot;,&quot;66&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1]</span></p> <p><strong>Explanation:</strong> If we consider this mapping: <code>&quot;a&quot; -&gt; 3</code> and <code>&quot;b&quot; -&gt; 4</code>; the submatrix with the upper-left corner <code>(1,1)</code> is a match as outlined in the matrix above.</p> <p>Note that since the corresponding values of <code>&quot;a&quot;</code> and <code>&quot;b&quot;</code> must differ, the submatrix with the upper-left corner <code>(1,0)</code> is not a match. Hence, we return <code>[1,1]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,2],[2,1]], pattern = [&quot;xx&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p> <p><strong>Explanation:</strong> Since the values of the matched submatrix must be the same, there is no match. Hence, we return <code>[-1,-1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= board.length &lt;= 50</code></li> <li><code>1 &lt;= board[i].length &lt;= 50</code></li> <li><code>0 &lt;= board[i][j] &lt;= 9</code></li> <li><code>1 &lt;= pattern.length &lt;= 50</code></li> <li><code>1 &lt;= pattern[i].length &lt;= 50</code></li> <li><code>pattern[i][j]</code> is either a digit represented as a string or a lowercase English letter.</li> </ul>
Array; Hash Table; String; Matrix
Java
class Solution { public int[] findPattern(int[][] board, String[] pattern) { int m = board.length, n = board[0].length; int r = pattern.length, c = pattern[0].length(); for (int i = 0; i < m - r + 1; ++i) { for (int j = 0; j < n - c + 1; ++j) { if (check(board, pattern, i, j)) { return new int[] {i, j}; } } } return new int[] {-1, -1}; } private boolean check(int[][] board, String[] pattern, int i, int j) { int[] d1 = new int[26]; int[] d2 = new int[10]; Arrays.fill(d1, -1); Arrays.fill(d2, -1); for (int a = 0; a < pattern.length; ++a) { for (int b = 0; b < pattern[0].length(); ++b) { int x = i + a, y = j + b; if (Character.isDigit(pattern[a].charAt(b))) { int v = pattern[a].charAt(b) - '0'; if (v != board[x][y]) { return false; } } else { int v = pattern[a].charAt(b) - 'a'; if (d1[v] != -1 && d1[v] != board[x][y]) { return false; } if (d2[board[x][y]] != -1 && d2[board[x][y]] != v) { return false; } d1[v] = board[x][y]; d2[board[x][y]] = v; } } } return true; } }
3,078
Match Alphanumerical Pattern in Matrix I
Medium
<p>You are given a 2D integer matrix <code>board</code> and a 2D character matrix <code>pattern</code>. Where <code>0 &lt;= board[r][c] &lt;= 9</code> and each element of <code>pattern</code> is either a digit or a lowercase English letter.</p> <p>Your task is to find a <span data-keyword="submatrix">submatrix</span> of <code>board</code> that <strong>matches</strong> <code>pattern</code>.</p> <p>An integer matrix <code>part</code> matches <code>pattern</code> if we can replace cells containing letters in <code>pattern</code> with some digits (each <strong>distinct</strong> letter with a <strong>unique</strong> digit) in such a way that the resulting matrix becomes identical to the integer matrix <code>part</code>. In other words,</p> <ul> <li>The matrices have identical dimensions.</li> <li>If <code>pattern[r][c]</code> is a digit, then <code>part[r][c]</code> must be the <strong>same</strong> digit.</li> <li>If <code>pattern[r][c]</code> is a letter <code>x</code>: <ul> <li>For every <code>pattern[i][j] == x</code>, <code>part[i][j]</code> must be the <strong>same</strong> as <code>part[r][c]</code>.</li> <li>For every <code>pattern[i][j] != x</code>, <code>part[i][j]</code> must be <strong>different</strong> than <code>part[r][c]</code>.<span style="display: none;"> </span></li> </ul> </li> </ul> <p>Return <em>an array of length </em><code>2</code><em> containing the row number and column number of the upper-left corner of a submatrix of </em><code>board</code><em> which matches </em><code>pattern</code><em>. If there is more than one such submatrix, return the coordinates of the submatrix with the lowest row index, and in case there is still a tie, return the coordinates of the submatrix with the lowest column index. If there are no suitable answers, return</em> <code>[-1, -1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">1</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,2,2],[2,2,3],[2,3,3]], pattern = [&quot;ab&quot;,&quot;bb&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0]</span></p> <p><strong>Explanation:</strong> If we consider this mapping: <code>&quot;a&quot; -&gt; 1</code> and <code>&quot;b&quot; -&gt; 2</code>; the submatrix with the upper-left corner <code>(0,0)</code> is a match as outlined in the matrix above.</p> <p>Note that the submatrix with the upper-left corner (1,1) is also a match but since it comes after the other one, we return <code>[0,0]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">3</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">4</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,1,2],[3,3,4],[6,6,6]], pattern = [&quot;ab&quot;,&quot;66&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1]</span></p> <p><strong>Explanation:</strong> If we consider this mapping: <code>&quot;a&quot; -&gt; 3</code> and <code>&quot;b&quot; -&gt; 4</code>; the submatrix with the upper-left corner <code>(1,1)</code> is a match as outlined in the matrix above.</p> <p>Note that since the corresponding values of <code>&quot;a&quot;</code> and <code>&quot;b&quot;</code> must differ, the submatrix with the upper-left corner <code>(1,0)</code> is not a match. Hence, we return <code>[1,1]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,2],[2,1]], pattern = [&quot;xx&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p> <p><strong>Explanation:</strong> Since the values of the matched submatrix must be the same, there is no match. Hence, we return <code>[-1,-1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= board.length &lt;= 50</code></li> <li><code>1 &lt;= board[i].length &lt;= 50</code></li> <li><code>0 &lt;= board[i][j] &lt;= 9</code></li> <li><code>1 &lt;= pattern.length &lt;= 50</code></li> <li><code>1 &lt;= pattern[i].length &lt;= 50</code></li> <li><code>pattern[i][j]</code> is either a digit represented as a string or a lowercase English letter.</li> </ul>
Array; Hash Table; String; Matrix
Python
class Solution: def findPattern(self, board: List[List[int]], pattern: List[str]) -> List[int]: def check(i: int, j: int) -> bool: d1 = {} d2 = {} for a in range(r): for b in range(c): x, y = i + a, j + b if pattern[a][b].isdigit(): if int(pattern[a][b]) != board[x][y]: return False else: if pattern[a][b] in d1 and d1[pattern[a][b]] != board[x][y]: return False if board[x][y] in d2 and d2[board[x][y]] != pattern[a][b]: return False d1[pattern[a][b]] = board[x][y] d2[board[x][y]] = pattern[a][b] return True m, n = len(board), len(board[0]) r, c = len(pattern), len(pattern[0]) for i in range(m - r + 1): for j in range(n - c + 1): if check(i, j): return [i, j] return [-1, -1]
3,078
Match Alphanumerical Pattern in Matrix I
Medium
<p>You are given a 2D integer matrix <code>board</code> and a 2D character matrix <code>pattern</code>. Where <code>0 &lt;= board[r][c] &lt;= 9</code> and each element of <code>pattern</code> is either a digit or a lowercase English letter.</p> <p>Your task is to find a <span data-keyword="submatrix">submatrix</span> of <code>board</code> that <strong>matches</strong> <code>pattern</code>.</p> <p>An integer matrix <code>part</code> matches <code>pattern</code> if we can replace cells containing letters in <code>pattern</code> with some digits (each <strong>distinct</strong> letter with a <strong>unique</strong> digit) in such a way that the resulting matrix becomes identical to the integer matrix <code>part</code>. In other words,</p> <ul> <li>The matrices have identical dimensions.</li> <li>If <code>pattern[r][c]</code> is a digit, then <code>part[r][c]</code> must be the <strong>same</strong> digit.</li> <li>If <code>pattern[r][c]</code> is a letter <code>x</code>: <ul> <li>For every <code>pattern[i][j] == x</code>, <code>part[i][j]</code> must be the <strong>same</strong> as <code>part[r][c]</code>.</li> <li>For every <code>pattern[i][j] != x</code>, <code>part[i][j]</code> must be <strong>different</strong> than <code>part[r][c]</code>.<span style="display: none;"> </span></li> </ul> </li> </ul> <p>Return <em>an array of length </em><code>2</code><em> containing the row number and column number of the upper-left corner of a submatrix of </em><code>board</code><em> which matches </em><code>pattern</code><em>. If there is more than one such submatrix, return the coordinates of the submatrix with the lowest row index, and in case there is still a tie, return the coordinates of the submatrix with the lowest column index. If there are no suitable answers, return</em> <code>[-1, -1]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">1</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,2,2],[2,2,3],[2,3,3]], pattern = [&quot;ab&quot;,&quot;bb&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0]</span></p> <p><strong>Explanation:</strong> If we consider this mapping: <code>&quot;a&quot; -&gt; 1</code> and <code>&quot;b&quot; -&gt; 2</code>; the submatrix with the upper-left corner <code>(0,0)</code> is a match as outlined in the matrix above.</p> <p>Note that the submatrix with the upper-left corner (1,1) is also a match but since it comes after the other one, we return <code>[0,0]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">3</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">3</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">4</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td> <td style="padding: 5px 10px; border: 1px solid red; --darkreader-inline-border-top: #b30000; --darkreader-inline-border-right: #b30000; --darkreader-inline-border-bottom: #b30000; --darkreader-inline-border-left: #b30000;">6</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">a</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">b</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">6</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,1,2],[3,3,4],[6,6,6]], pattern = [&quot;ab&quot;,&quot;66&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1]</span></p> <p><strong>Explanation:</strong> If we consider this mapping: <code>&quot;a&quot; -&gt; 3</code> and <code>&quot;b&quot; -&gt; 4</code>; the submatrix with the upper-left corner <code>(1,1)</code> is a match as outlined in the matrix above.</p> <p>Note that since the corresponding values of <code>&quot;a&quot;</code> and <code>&quot;b&quot;</code> must differ, the submatrix with the upper-left corner <code>(1,0)</code> is not a match. Hence, we return <code>[1,1]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div style="display:flex; flex-wrap: wrap; align-items: flex-start; gap: 12px;"> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> </tr> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">2</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">1</td> </tr> </tbody> </table> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td> <td style="padding: 5px 10px; border: 1px solid black; --darkreader-inline-border-top: #8c8273; --darkreader-inline-border-right: #8c8273; --darkreader-inline-border-bottom: #8c8273; --darkreader-inline-border-left: #8c8273;">x</td> </tr> </tbody> </table> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">board = [[1,2],[2,1]], pattern = [&quot;xx&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1]</span></p> <p><strong>Explanation:</strong> Since the values of the matched submatrix must be the same, there is no match. Hence, we return <code>[-1,-1]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= board.length &lt;= 50</code></li> <li><code>1 &lt;= board[i].length &lt;= 50</code></li> <li><code>0 &lt;= board[i][j] &lt;= 9</code></li> <li><code>1 &lt;= pattern.length &lt;= 50</code></li> <li><code>1 &lt;= pattern[i].length &lt;= 50</code></li> <li><code>pattern[i][j]</code> is either a digit represented as a string or a lowercase English letter.</li> </ul>
Array; Hash Table; String; Matrix
TypeScript
function findPattern(board: number[][], pattern: string[]): number[] { const m: number = board.length; const n: number = board[0].length; const r: number = pattern.length; const c: number = pattern[0].length; const check = (i: number, j: number): boolean => { const d1: number[] = Array(26).fill(-1); const d2: number[] = Array(10).fill(-1); for (let a = 0; a < r; ++a) { for (let b = 0; b < c; ++b) { const x: number = i + a; const y: number = j + b; if (!isNaN(Number(pattern[a][b]))) { const v: number = Number(pattern[a][b]); if (v !== board[x][y]) { return false; } } else { const v: number = pattern[a].charCodeAt(b) - 'a'.charCodeAt(0); if (d1[v] !== -1 && d1[v] !== board[x][y]) { return false; } if (d2[board[x][y]] !== -1 && d2[board[x][y]] !== v) { return false; } d1[v] = board[x][y]; d2[board[x][y]] = v; } } } return true; }; for (let i = 0; i < m - r + 1; ++i) { for (let j = 0; j < n - c + 1; ++j) { if (check(i, j)) { return [i, j]; } } } return [-1, -1]; }
3,079
Find the Sum of Encrypted Integers
Easy
<p>You are given an integer array <code>nums</code> containing <strong>positive</strong> integers. We define a function <code>encrypt</code> such that <code>encrypt(x)</code> replaces <strong>every</strong> digit in <code>x</code> with the <strong>largest</strong> digit in <code>x</code>. For example, <code>encrypt(523) = 555</code> and <code>encrypt(213) = 333</code>.</p> <p>Return <em>the <strong>sum </strong>of encrypted elements</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,3]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> The encrypted elements are&nbsp;<code>[1,2,3]</code>. The sum of encrypted elements is <code>1 + 2 + 3 == 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [10,21,31]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">66</span></p> <p><strong>Explanation:</strong> The encrypted elements are <code>[11,22,33]</code>. The sum of encrypted elements is <code>11 + 22 + 33 == 66</code>.</p> </div> <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;= 1000</code></li> </ul>
Array; Math
C++
class Solution { public: int sumOfEncryptedInt(vector<int>& nums) { auto encrypt = [&](int x) { int mx = 0, p = 0; for (; x; x /= 10) { mx = max(mx, x % 10); p = p * 10 + 1; } return mx * p; }; int ans = 0; for (int x : nums) { ans += encrypt(x); } return ans; } };
3,079
Find the Sum of Encrypted Integers
Easy
<p>You are given an integer array <code>nums</code> containing <strong>positive</strong> integers. We define a function <code>encrypt</code> such that <code>encrypt(x)</code> replaces <strong>every</strong> digit in <code>x</code> with the <strong>largest</strong> digit in <code>x</code>. For example, <code>encrypt(523) = 555</code> and <code>encrypt(213) = 333</code>.</p> <p>Return <em>the <strong>sum </strong>of encrypted elements</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,3]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> The encrypted elements are&nbsp;<code>[1,2,3]</code>. The sum of encrypted elements is <code>1 + 2 + 3 == 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [10,21,31]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">66</span></p> <p><strong>Explanation:</strong> The encrypted elements are <code>[11,22,33]</code>. The sum of encrypted elements is <code>11 + 22 + 33 == 66</code>.</p> </div> <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;= 1000</code></li> </ul>
Array; Math
Go
func sumOfEncryptedInt(nums []int) (ans int) { encrypt := func(x int) int { mx, p := 0, 0 for ; x > 0; x /= 10 { mx = max(mx, x%10) p = p*10 + 1 } return mx * p } for _, x := range nums { ans += encrypt(x) } return }
3,079
Find the Sum of Encrypted Integers
Easy
<p>You are given an integer array <code>nums</code> containing <strong>positive</strong> integers. We define a function <code>encrypt</code> such that <code>encrypt(x)</code> replaces <strong>every</strong> digit in <code>x</code> with the <strong>largest</strong> digit in <code>x</code>. For example, <code>encrypt(523) = 555</code> and <code>encrypt(213) = 333</code>.</p> <p>Return <em>the <strong>sum </strong>of encrypted elements</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,3]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> The encrypted elements are&nbsp;<code>[1,2,3]</code>. The sum of encrypted elements is <code>1 + 2 + 3 == 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [10,21,31]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">66</span></p> <p><strong>Explanation:</strong> The encrypted elements are <code>[11,22,33]</code>. The sum of encrypted elements is <code>11 + 22 + 33 == 66</code>.</p> </div> <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;= 1000</code></li> </ul>
Array; Math
Java
class Solution { public int sumOfEncryptedInt(int[] nums) { int ans = 0; for (int x : nums) { ans += encrypt(x); } return ans; } private int encrypt(int x) { int mx = 0, p = 0; for (; x > 0; x /= 10) { mx = Math.max(mx, x % 10); p = p * 10 + 1; } return mx * p; } }
3,079
Find the Sum of Encrypted Integers
Easy
<p>You are given an integer array <code>nums</code> containing <strong>positive</strong> integers. We define a function <code>encrypt</code> such that <code>encrypt(x)</code> replaces <strong>every</strong> digit in <code>x</code> with the <strong>largest</strong> digit in <code>x</code>. For example, <code>encrypt(523) = 555</code> and <code>encrypt(213) = 333</code>.</p> <p>Return <em>the <strong>sum </strong>of encrypted elements</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,3]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> The encrypted elements are&nbsp;<code>[1,2,3]</code>. The sum of encrypted elements is <code>1 + 2 + 3 == 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [10,21,31]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">66</span></p> <p><strong>Explanation:</strong> The encrypted elements are <code>[11,22,33]</code>. The sum of encrypted elements is <code>11 + 22 + 33 == 66</code>.</p> </div> <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;= 1000</code></li> </ul>
Array; Math
Python
class Solution: def sumOfEncryptedInt(self, nums: List[int]) -> int: def encrypt(x: int) -> int: mx = p = 0 while x: x, v = divmod(x, 10) mx = max(mx, v) p = p * 10 + 1 return mx * p return sum(encrypt(x) for x in nums)
3,079
Find the Sum of Encrypted Integers
Easy
<p>You are given an integer array <code>nums</code> containing <strong>positive</strong> integers. We define a function <code>encrypt</code> such that <code>encrypt(x)</code> replaces <strong>every</strong> digit in <code>x</code> with the <strong>largest</strong> digit in <code>x</code>. For example, <code>encrypt(523) = 555</code> and <code>encrypt(213) = 333</code>.</p> <p>Return <em>the <strong>sum </strong>of encrypted elements</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,3]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> The encrypted elements are&nbsp;<code>[1,2,3]</code>. The sum of encrypted elements is <code>1 + 2 + 3 == 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [10,21,31]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">66</span></p> <p><strong>Explanation:</strong> The encrypted elements are <code>[11,22,33]</code>. The sum of encrypted elements is <code>11 + 22 + 33 == 66</code>.</p> </div> <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;= 1000</code></li> </ul>
Array; Math
TypeScript
function sumOfEncryptedInt(nums: number[]): number { const encrypt = (x: number): number => { let [mx, p] = [0, 0]; for (; x > 0; x = Math.floor(x / 10)) { mx = Math.max(mx, x % 10); p = p * 10 + 1; } return mx * p; }; return nums.reduce((acc, x) => acc + encrypt(x), 0); }
3,080
Mark Elements on Array by Performing Queries
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of size <code>n</code> consisting of positive integers.</p> <p>You are also given a 2D array <code>queries</code> of size <code>m</code> where <code>queries[i] = [index<sub>i</sub>, k<sub>i</sub>]</code>.</p> <p>Initially all elements of the array are <strong>unmarked</strong>.</p> <p>You need to apply <code>m</code> queries on the array in order, where on the <code>i<sup>th</sup></code> query you do the following:</p> <ul> <li>Mark the element at index <code>index<sub>i</sub></code> if it is not already marked.</li> <li>Then mark <code>k<sub>i</sub></code> unmarked elements in the array with the <strong>smallest</strong> values. If multiple such elements exist, mark the ones with the smallest indices. And if less than <code>k<sub>i</sub></code> unmarked elements exist, then mark all of them.</li> </ul> <p>Return <em>an array answer of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>sum</strong> of unmarked elements in the array after the </em><code>i<sup>th</sup></code><em> query</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,2,1,2,3,1], queries = [[1,2],[3,3],[4,2]]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[8,3,0]</span></p> <p><strong>Explanation:</strong></p> <p>We do the following queries on the array:</p> <ul> <li>Mark the element at index <code>1</code>, and <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,2,<u><strong>1</strong></u>,2,3,1]</code>. The sum of unmarked elements is <code>2 + 2 + 3 + 1 = 8</code>.</li> <li>Mark the element at index <code>3</code>, since it is already marked we skip it. Then we mark <code>3</code> of the smallest unmarked elements with the smallest indices, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,3,<strong><u>1</u></strong>]</code>. The sum of unmarked elements is <code>3</code>.</li> <li>Mark the element at index <code>4</code>, since it is already marked we skip it. Then we mark <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,<strong><u>3</u></strong>,<u><strong>1</strong></u>]</code>. The sum of unmarked elements is <code>0</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,4,2,3], queries = [[0,1]]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[7]</span></p> <p><strong>Explanation: </strong> We do one query which is mark the element at index <code>0</code> and mark the smallest element among unmarked elements. The marked elements will be <code>nums = [<strong><u>1</u></strong>,4,<u><strong>2</strong></u>,3]</code>, and the sum of unmarked elements is <code>4 + 3 = 7</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>m == queries.length</code></li> <li><code>1 &lt;= m &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= index<sub>i</sub>, k<sub>i</sub> &lt;= n - 1</code></li> </ul>
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
C++
class Solution { public: vector<long long> unmarkedSumArray(vector<int>& nums, vector<vector<int>>& queries) { int n = nums.size(); long long s = accumulate(nums.begin(), nums.end(), 0LL); vector<bool> mark(n); vector<pair<int, int>> arr; for (int i = 0; i < n; ++i) { arr.emplace_back(nums[i], i); } sort(arr.begin(), arr.end()); vector<long long> ans; int m = queries.size(); for (int i = 0, j = 0; i < m; ++i) { int index = queries[i][0], k = queries[i][1]; if (!mark[index]) { mark[index] = true; s -= nums[index]; } for (; k && j < n; ++j) { if (!mark[arr[j].second]) { mark[arr[j].second] = true; s -= arr[j].first; --k; } } ans.push_back(s); } return ans; } };
3,080
Mark Elements on Array by Performing Queries
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of size <code>n</code> consisting of positive integers.</p> <p>You are also given a 2D array <code>queries</code> of size <code>m</code> where <code>queries[i] = [index<sub>i</sub>, k<sub>i</sub>]</code>.</p> <p>Initially all elements of the array are <strong>unmarked</strong>.</p> <p>You need to apply <code>m</code> queries on the array in order, where on the <code>i<sup>th</sup></code> query you do the following:</p> <ul> <li>Mark the element at index <code>index<sub>i</sub></code> if it is not already marked.</li> <li>Then mark <code>k<sub>i</sub></code> unmarked elements in the array with the <strong>smallest</strong> values. If multiple such elements exist, mark the ones with the smallest indices. And if less than <code>k<sub>i</sub></code> unmarked elements exist, then mark all of them.</li> </ul> <p>Return <em>an array answer of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>sum</strong> of unmarked elements in the array after the </em><code>i<sup>th</sup></code><em> query</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,2,1,2,3,1], queries = [[1,2],[3,3],[4,2]]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[8,3,0]</span></p> <p><strong>Explanation:</strong></p> <p>We do the following queries on the array:</p> <ul> <li>Mark the element at index <code>1</code>, and <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,2,<u><strong>1</strong></u>,2,3,1]</code>. The sum of unmarked elements is <code>2 + 2 + 3 + 1 = 8</code>.</li> <li>Mark the element at index <code>3</code>, since it is already marked we skip it. Then we mark <code>3</code> of the smallest unmarked elements with the smallest indices, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,3,<strong><u>1</u></strong>]</code>. The sum of unmarked elements is <code>3</code>.</li> <li>Mark the element at index <code>4</code>, since it is already marked we skip it. Then we mark <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,<strong><u>3</u></strong>,<u><strong>1</strong></u>]</code>. The sum of unmarked elements is <code>0</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,4,2,3], queries = [[0,1]]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[7]</span></p> <p><strong>Explanation: </strong> We do one query which is mark the element at index <code>0</code> and mark the smallest element among unmarked elements. The marked elements will be <code>nums = [<strong><u>1</u></strong>,4,<u><strong>2</strong></u>,3]</code>, and the sum of unmarked elements is <code>4 + 3 = 7</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>m == queries.length</code></li> <li><code>1 &lt;= m &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= index<sub>i</sub>, k<sub>i</sub> &lt;= n - 1</code></li> </ul>
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
Go
func unmarkedSumArray(nums []int, queries [][]int) []int64 { n := len(nums) var s int64 for _, x := range nums { s += int64(x) } mark := make([]bool, n) arr := make([][2]int, 0, n) for i, x := range nums { arr = append(arr, [2]int{x, i}) } sort.Slice(arr, func(i, j int) bool { if arr[i][0] == arr[j][0] { return arr[i][1] < arr[j][1] } return arr[i][0] < arr[j][0] }) ans := make([]int64, len(queries)) j := 0 for i, q := range queries { index, k := q[0], q[1] if !mark[index] { mark[index] = true s -= int64(nums[index]) } for ; k > 0 && j < n; j++ { if !mark[arr[j][1]] { mark[arr[j][1]] = true s -= int64(arr[j][0]) k-- } } ans[i] = s } return ans }
3,080
Mark Elements on Array by Performing Queries
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of size <code>n</code> consisting of positive integers.</p> <p>You are also given a 2D array <code>queries</code> of size <code>m</code> where <code>queries[i] = [index<sub>i</sub>, k<sub>i</sub>]</code>.</p> <p>Initially all elements of the array are <strong>unmarked</strong>.</p> <p>You need to apply <code>m</code> queries on the array in order, where on the <code>i<sup>th</sup></code> query you do the following:</p> <ul> <li>Mark the element at index <code>index<sub>i</sub></code> if it is not already marked.</li> <li>Then mark <code>k<sub>i</sub></code> unmarked elements in the array with the <strong>smallest</strong> values. If multiple such elements exist, mark the ones with the smallest indices. And if less than <code>k<sub>i</sub></code> unmarked elements exist, then mark all of them.</li> </ul> <p>Return <em>an array answer of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>sum</strong> of unmarked elements in the array after the </em><code>i<sup>th</sup></code><em> query</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,2,1,2,3,1], queries = [[1,2],[3,3],[4,2]]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[8,3,0]</span></p> <p><strong>Explanation:</strong></p> <p>We do the following queries on the array:</p> <ul> <li>Mark the element at index <code>1</code>, and <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,2,<u><strong>1</strong></u>,2,3,1]</code>. The sum of unmarked elements is <code>2 + 2 + 3 + 1 = 8</code>.</li> <li>Mark the element at index <code>3</code>, since it is already marked we skip it. Then we mark <code>3</code> of the smallest unmarked elements with the smallest indices, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,3,<strong><u>1</u></strong>]</code>. The sum of unmarked elements is <code>3</code>.</li> <li>Mark the element at index <code>4</code>, since it is already marked we skip it. Then we mark <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,<strong><u>3</u></strong>,<u><strong>1</strong></u>]</code>. The sum of unmarked elements is <code>0</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,4,2,3], queries = [[0,1]]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[7]</span></p> <p><strong>Explanation: </strong> We do one query which is mark the element at index <code>0</code> and mark the smallest element among unmarked elements. The marked elements will be <code>nums = [<strong><u>1</u></strong>,4,<u><strong>2</strong></u>,3]</code>, and the sum of unmarked elements is <code>4 + 3 = 7</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>m == queries.length</code></li> <li><code>1 &lt;= m &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= index<sub>i</sub>, k<sub>i</sub> &lt;= n - 1</code></li> </ul>
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
Java
class Solution { public long[] unmarkedSumArray(int[] nums, int[][] queries) { int n = nums.length; long s = Arrays.stream(nums).asLongStream().sum(); boolean[] mark = new boolean[n]; int[][] arr = new int[n][0]; for (int i = 0; i < n; ++i) { arr[i] = new int[] {nums[i], i}; } Arrays.sort(arr, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); int m = queries.length; long[] ans = new long[m]; for (int i = 0, j = 0; i < m; ++i) { int index = queries[i][0], k = queries[i][1]; if (!mark[index]) { mark[index] = true; s -= nums[index]; } for (; k > 0 && j < n; ++j) { if (!mark[arr[j][1]]) { mark[arr[j][1]] = true; s -= arr[j][0]; --k; } } ans[i] = s; } return ans; } }
3,080
Mark Elements on Array by Performing Queries
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of size <code>n</code> consisting of positive integers.</p> <p>You are also given a 2D array <code>queries</code> of size <code>m</code> where <code>queries[i] = [index<sub>i</sub>, k<sub>i</sub>]</code>.</p> <p>Initially all elements of the array are <strong>unmarked</strong>.</p> <p>You need to apply <code>m</code> queries on the array in order, where on the <code>i<sup>th</sup></code> query you do the following:</p> <ul> <li>Mark the element at index <code>index<sub>i</sub></code> if it is not already marked.</li> <li>Then mark <code>k<sub>i</sub></code> unmarked elements in the array with the <strong>smallest</strong> values. If multiple such elements exist, mark the ones with the smallest indices. And if less than <code>k<sub>i</sub></code> unmarked elements exist, then mark all of them.</li> </ul> <p>Return <em>an array answer of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>sum</strong> of unmarked elements in the array after the </em><code>i<sup>th</sup></code><em> query</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,2,1,2,3,1], queries = [[1,2],[3,3],[4,2]]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[8,3,0]</span></p> <p><strong>Explanation:</strong></p> <p>We do the following queries on the array:</p> <ul> <li>Mark the element at index <code>1</code>, and <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,2,<u><strong>1</strong></u>,2,3,1]</code>. The sum of unmarked elements is <code>2 + 2 + 3 + 1 = 8</code>.</li> <li>Mark the element at index <code>3</code>, since it is already marked we skip it. Then we mark <code>3</code> of the smallest unmarked elements with the smallest indices, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,3,<strong><u>1</u></strong>]</code>. The sum of unmarked elements is <code>3</code>.</li> <li>Mark the element at index <code>4</code>, since it is already marked we skip it. Then we mark <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,<strong><u>3</u></strong>,<u><strong>1</strong></u>]</code>. The sum of unmarked elements is <code>0</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,4,2,3], queries = [[0,1]]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[7]</span></p> <p><strong>Explanation: </strong> We do one query which is mark the element at index <code>0</code> and mark the smallest element among unmarked elements. The marked elements will be <code>nums = [<strong><u>1</u></strong>,4,<u><strong>2</strong></u>,3]</code>, and the sum of unmarked elements is <code>4 + 3 = 7</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>m == queries.length</code></li> <li><code>1 &lt;= m &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= index<sub>i</sub>, k<sub>i</sub> &lt;= n - 1</code></li> </ul>
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
Python
class Solution: def unmarkedSumArray(self, nums: List[int], queries: List[List[int]]) -> List[int]: n = len(nums) s = sum(nums) mark = [False] * n arr = sorted((x, i) for i, x in enumerate(nums)) j = 0 ans = [] for index, k in queries: if not mark[index]: mark[index] = True s -= nums[index] while k and j < n: if not mark[arr[j][1]]: mark[arr[j][1]] = True s -= arr[j][0] k -= 1 j += 1 ans.append(s) return ans
3,080
Mark Elements on Array by Performing Queries
Medium
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of size <code>n</code> consisting of positive integers.</p> <p>You are also given a 2D array <code>queries</code> of size <code>m</code> where <code>queries[i] = [index<sub>i</sub>, k<sub>i</sub>]</code>.</p> <p>Initially all elements of the array are <strong>unmarked</strong>.</p> <p>You need to apply <code>m</code> queries on the array in order, where on the <code>i<sup>th</sup></code> query you do the following:</p> <ul> <li>Mark the element at index <code>index<sub>i</sub></code> if it is not already marked.</li> <li>Then mark <code>k<sub>i</sub></code> unmarked elements in the array with the <strong>smallest</strong> values. If multiple such elements exist, mark the ones with the smallest indices. And if less than <code>k<sub>i</sub></code> unmarked elements exist, then mark all of them.</li> </ul> <p>Return <em>an array answer of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>sum</strong> of unmarked elements in the array after the </em><code>i<sup>th</sup></code><em> query</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,2,2,1,2,3,1], queries = [[1,2],[3,3],[4,2]]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[8,3,0]</span></p> <p><strong>Explanation:</strong></p> <p>We do the following queries on the array:</p> <ul> <li>Mark the element at index <code>1</code>, and <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,2,<u><strong>1</strong></u>,2,3,1]</code>. The sum of unmarked elements is <code>2 + 2 + 3 + 1 = 8</code>.</li> <li>Mark the element at index <code>3</code>, since it is already marked we skip it. Then we mark <code>3</code> of the smallest unmarked elements with the smallest indices, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,3,<strong><u>1</u></strong>]</code>. The sum of unmarked elements is <code>3</code>.</li> <li>Mark the element at index <code>4</code>, since it is already marked we skip it. Then we mark <code>2</code> of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are <code>nums = [<strong><u>1</u></strong>,<u><strong>2</strong></u>,<u><strong>2</strong></u>,<u><strong>1</strong></u>,<u><strong>2</strong></u>,<strong><u>3</u></strong>,<u><strong>1</strong></u>]</code>. The sum of unmarked elements is <code>0</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,4,2,3], queries = [[0,1]]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">[7]</span></p> <p><strong>Explanation: </strong> We do one query which is mark the element at index <code>0</code> and mark the smallest element among unmarked elements. The marked elements will be <code>nums = [<strong><u>1</u></strong>,4,<u><strong>2</strong></u>,3]</code>, and the sum of unmarked elements is <code>4 + 3 = 7</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>m == queries.length</code></li> <li><code>1 &lt;= m &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2</code></li> <li><code>0 &lt;= index<sub>i</sub>, k<sub>i</sub> &lt;= n - 1</code></li> </ul>
Array; Hash Table; Sorting; Simulation; Heap (Priority Queue)
TypeScript
function unmarkedSumArray(nums: number[], queries: number[][]): number[] { const n = nums.length; let s = nums.reduce((acc, x) => acc + x, 0); const mark: boolean[] = Array(n).fill(false); const arr = nums.map((x, i) => [x, i]); arr.sort((a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])); let j = 0; const ans: number[] = []; for (let [index, k] of queries) { if (!mark[index]) { mark[index] = true; s -= nums[index]; } for (; k && j < n; ++j) { if (!mark[arr[j][1]]) { mark[arr[j][1]] = true; s -= arr[j][0]; --k; } } ans.push(s); } return ans; }
3,081
Replace Question Marks in String to Minimize Its Value
Medium
<p>You are given a string <code>s</code>. <code>s[i]</code> is either a lowercase English letter or <code>&#39;?&#39;</code>.</p> <p>For a string <code>t</code> having length <code>m</code> containing <strong>only</strong> lowercase English letters, we define the function <code>cost(i)</code> for an index <code>i</code>&nbsp;as the number of characters <strong>equal</strong> to <code>t[i]</code>&nbsp;that appeared before it, i.e. in the range <code>[0, i - 1]</code>.</p> <p>The <strong>value</strong> of <code>t</code> is the <strong>sum</strong> of <code>cost(i)</code> for all indices <code>i</code>.</p> <p>For example, for the string <code>t = &quot;aab&quot;</code>:</p> <ul> <li><code>cost(0) = 0</code></li> <li><code>cost(1) = 1</code></li> <li><code>cost(2) = 0</code></li> <li>Hence, the value of <code>&quot;aab&quot;</code> is <code>0 + 1 + 0 = 1</code>.</li> </ul> <p>Your task is to <strong>replace all</strong> occurrences of <code>&#39;?&#39;</code> in <code>s</code> with any lowercase English letter so that the <strong>value</strong> of <code>s</code> is <strong>minimized</strong>.</p> <p>Return <em>a string denoting the modified string with replaced occurrences of </em><code>&#39;?&#39;</code><em>. If there are multiple strings resulting in the <strong>minimum value</strong>, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = &quot;???&quot; </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> &quot;abc&quot; </span></p> <p><strong>Explanation: </strong> In this example, we can replace the occurrences of <code>&#39;?&#39;</code> to make <code>s</code> equal to <code>&quot;abc&quot;</code>.</p> <p>For <code>&quot;abc&quot;</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, and <code>cost(2) = 0</code>.</p> <p>The value of <code>&quot;abc&quot;</code> is <code>0</code>.</p> <p>Some other modifications of <code>s</code> that have a value of <code>0</code> are <code>&quot;cba&quot;</code>, <code>&quot;abz&quot;</code>, and, <code>&quot;hey&quot;</code>.</p> <p>Among all of them, we choose the lexicographically smallest.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;a?a?&quot;</span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">&quot;abac&quot;</span></p> <p><strong>Explanation: </strong> In this example, the occurrences of <code>&#39;?&#39;</code> can be replaced to make <code>s</code> equal to <code>&quot;abac&quot;</code>.</p> <p>For <code>&quot;abac&quot;</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, <code>cost(2) = 1</code>, and <code>cost(3) = 0</code>.</p> <p>The value of <code>&quot;abac&quot;</code> is&nbsp;<code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either a lowercase English letter or <code>&#39;?&#39;</code>.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting; Heap (Priority Queue)
C++
class Solution { public: string minimizeStringValue(string s) { int cnt[26]{}; int k = 0; for (char& c : s) { if (c == '?') { ++k; } else { ++cnt[c - 'a']; } } priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq; for (int i = 0; i < 26; ++i) { pq.push({cnt[i], i}); } vector<int> t(k); for (int i = 0; i < k; ++i) { auto [v, c] = pq.top(); pq.pop(); t[i] = c; pq.push({v + 1, c}); } sort(t.begin(), t.end()); int j = 0; for (char& c : s) { if (c == '?') { c = t[j++] + 'a'; } } return s; } };
3,081
Replace Question Marks in String to Minimize Its Value
Medium
<p>You are given a string <code>s</code>. <code>s[i]</code> is either a lowercase English letter or <code>&#39;?&#39;</code>.</p> <p>For a string <code>t</code> having length <code>m</code> containing <strong>only</strong> lowercase English letters, we define the function <code>cost(i)</code> for an index <code>i</code>&nbsp;as the number of characters <strong>equal</strong> to <code>t[i]</code>&nbsp;that appeared before it, i.e. in the range <code>[0, i - 1]</code>.</p> <p>The <strong>value</strong> of <code>t</code> is the <strong>sum</strong> of <code>cost(i)</code> for all indices <code>i</code>.</p> <p>For example, for the string <code>t = &quot;aab&quot;</code>:</p> <ul> <li><code>cost(0) = 0</code></li> <li><code>cost(1) = 1</code></li> <li><code>cost(2) = 0</code></li> <li>Hence, the value of <code>&quot;aab&quot;</code> is <code>0 + 1 + 0 = 1</code>.</li> </ul> <p>Your task is to <strong>replace all</strong> occurrences of <code>&#39;?&#39;</code> in <code>s</code> with any lowercase English letter so that the <strong>value</strong> of <code>s</code> is <strong>minimized</strong>.</p> <p>Return <em>a string denoting the modified string with replaced occurrences of </em><code>&#39;?&#39;</code><em>. If there are multiple strings resulting in the <strong>minimum value</strong>, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = &quot;???&quot; </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> &quot;abc&quot; </span></p> <p><strong>Explanation: </strong> In this example, we can replace the occurrences of <code>&#39;?&#39;</code> to make <code>s</code> equal to <code>&quot;abc&quot;</code>.</p> <p>For <code>&quot;abc&quot;</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, and <code>cost(2) = 0</code>.</p> <p>The value of <code>&quot;abc&quot;</code> is <code>0</code>.</p> <p>Some other modifications of <code>s</code> that have a value of <code>0</code> are <code>&quot;cba&quot;</code>, <code>&quot;abz&quot;</code>, and, <code>&quot;hey&quot;</code>.</p> <p>Among all of them, we choose the lexicographically smallest.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;a?a?&quot;</span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">&quot;abac&quot;</span></p> <p><strong>Explanation: </strong> In this example, the occurrences of <code>&#39;?&#39;</code> can be replaced to make <code>s</code> equal to <code>&quot;abac&quot;</code>.</p> <p>For <code>&quot;abac&quot;</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, <code>cost(2) = 1</code>, and <code>cost(3) = 0</code>.</p> <p>The value of <code>&quot;abac&quot;</code> is&nbsp;<code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either a lowercase English letter or <code>&#39;?&#39;</code>.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting; Heap (Priority Queue)
Go
func minimizeStringValue(s string) string { cnt := [26]int{} k := 0 for _, c := range s { if c == '?' { k++ } else { cnt[c-'a']++ } } pq := hp{} for i, c := range cnt { heap.Push(&pq, pair{c, i}) } t := make([]int, k) for i := 0; i < k; i++ { p := heap.Pop(&pq).(pair) t[i] = p.c p.v++ heap.Push(&pq, p) } sort.Ints(t) cs := []byte(s) j := 0 for i, c := range cs { if c == '?' { cs[i] = byte(t[j] + 'a') j++ } } return string(cs) } type pair struct{ v, c int } type hp []pair func (h hp) Len() int { return len(h) } func (h hp) Less(i, j int) bool { return h[i].v < h[j].v || h[i].v == h[j].v && h[i].c < h[j].c } func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
3,081
Replace Question Marks in String to Minimize Its Value
Medium
<p>You are given a string <code>s</code>. <code>s[i]</code> is either a lowercase English letter or <code>&#39;?&#39;</code>.</p> <p>For a string <code>t</code> having length <code>m</code> containing <strong>only</strong> lowercase English letters, we define the function <code>cost(i)</code> for an index <code>i</code>&nbsp;as the number of characters <strong>equal</strong> to <code>t[i]</code>&nbsp;that appeared before it, i.e. in the range <code>[0, i - 1]</code>.</p> <p>The <strong>value</strong> of <code>t</code> is the <strong>sum</strong> of <code>cost(i)</code> for all indices <code>i</code>.</p> <p>For example, for the string <code>t = &quot;aab&quot;</code>:</p> <ul> <li><code>cost(0) = 0</code></li> <li><code>cost(1) = 1</code></li> <li><code>cost(2) = 0</code></li> <li>Hence, the value of <code>&quot;aab&quot;</code> is <code>0 + 1 + 0 = 1</code>.</li> </ul> <p>Your task is to <strong>replace all</strong> occurrences of <code>&#39;?&#39;</code> in <code>s</code> with any lowercase English letter so that the <strong>value</strong> of <code>s</code> is <strong>minimized</strong>.</p> <p>Return <em>a string denoting the modified string with replaced occurrences of </em><code>&#39;?&#39;</code><em>. If there are multiple strings resulting in the <strong>minimum value</strong>, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = &quot;???&quot; </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> &quot;abc&quot; </span></p> <p><strong>Explanation: </strong> In this example, we can replace the occurrences of <code>&#39;?&#39;</code> to make <code>s</code> equal to <code>&quot;abc&quot;</code>.</p> <p>For <code>&quot;abc&quot;</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, and <code>cost(2) = 0</code>.</p> <p>The value of <code>&quot;abc&quot;</code> is <code>0</code>.</p> <p>Some other modifications of <code>s</code> that have a value of <code>0</code> are <code>&quot;cba&quot;</code>, <code>&quot;abz&quot;</code>, and, <code>&quot;hey&quot;</code>.</p> <p>Among all of them, we choose the lexicographically smallest.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;a?a?&quot;</span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">&quot;abac&quot;</span></p> <p><strong>Explanation: </strong> In this example, the occurrences of <code>&#39;?&#39;</code> can be replaced to make <code>s</code> equal to <code>&quot;abac&quot;</code>.</p> <p>For <code>&quot;abac&quot;</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, <code>cost(2) = 1</code>, and <code>cost(3) = 0</code>.</p> <p>The value of <code>&quot;abac&quot;</code> is&nbsp;<code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either a lowercase English letter or <code>&#39;?&#39;</code>.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting; Heap (Priority Queue)
Java
class Solution { public String minimizeStringValue(String s) { int[] cnt = new int[26]; int n = s.length(); int k = 0; char[] cs = s.toCharArray(); for (char c : cs) { if (c == '?') { ++k; } else { ++cnt[c - 'a']; } } PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); for (int i = 0; i < 26; ++i) { pq.offer(new int[] {cnt[i], i}); } int[] t = new int[k]; for (int j = 0; j < k; ++j) { int[] p = pq.poll(); t[j] = p[1]; pq.offer(new int[] {p[0] + 1, p[1]}); } Arrays.sort(t); for (int i = 0, j = 0; i < n; ++i) { if (cs[i] == '?') { cs[i] = (char) (t[j++] + 'a'); } } return new String(cs); } }
3,081
Replace Question Marks in String to Minimize Its Value
Medium
<p>You are given a string <code>s</code>. <code>s[i]</code> is either a lowercase English letter or <code>&#39;?&#39;</code>.</p> <p>For a string <code>t</code> having length <code>m</code> containing <strong>only</strong> lowercase English letters, we define the function <code>cost(i)</code> for an index <code>i</code>&nbsp;as the number of characters <strong>equal</strong> to <code>t[i]</code>&nbsp;that appeared before it, i.e. in the range <code>[0, i - 1]</code>.</p> <p>The <strong>value</strong> of <code>t</code> is the <strong>sum</strong> of <code>cost(i)</code> for all indices <code>i</code>.</p> <p>For example, for the string <code>t = &quot;aab&quot;</code>:</p> <ul> <li><code>cost(0) = 0</code></li> <li><code>cost(1) = 1</code></li> <li><code>cost(2) = 0</code></li> <li>Hence, the value of <code>&quot;aab&quot;</code> is <code>0 + 1 + 0 = 1</code>.</li> </ul> <p>Your task is to <strong>replace all</strong> occurrences of <code>&#39;?&#39;</code> in <code>s</code> with any lowercase English letter so that the <strong>value</strong> of <code>s</code> is <strong>minimized</strong>.</p> <p>Return <em>a string denoting the modified string with replaced occurrences of </em><code>&#39;?&#39;</code><em>. If there are multiple strings resulting in the <strong>minimum value</strong>, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> s = &quot;???&quot; </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> &quot;abc&quot; </span></p> <p><strong>Explanation: </strong> In this example, we can replace the occurrences of <code>&#39;?&#39;</code> to make <code>s</code> equal to <code>&quot;abc&quot;</code>.</p> <p>For <code>&quot;abc&quot;</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, and <code>cost(2) = 0</code>.</p> <p>The value of <code>&quot;abc&quot;</code> is <code>0</code>.</p> <p>Some other modifications of <code>s</code> that have a value of <code>0</code> are <code>&quot;cba&quot;</code>, <code>&quot;abz&quot;</code>, and, <code>&quot;hey&quot;</code>.</p> <p>Among all of them, we choose the lexicographically smallest.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;a?a?&quot;</span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">&quot;abac&quot;</span></p> <p><strong>Explanation: </strong> In this example, the occurrences of <code>&#39;?&#39;</code> can be replaced to make <code>s</code> equal to <code>&quot;abac&quot;</code>.</p> <p>For <code>&quot;abac&quot;</code>, <code>cost(0) = 0</code>, <code>cost(1) = 0</code>, <code>cost(2) = 1</code>, and <code>cost(3) = 0</code>.</p> <p>The value of <code>&quot;abac&quot;</code> is&nbsp;<code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either a lowercase English letter or <code>&#39;?&#39;</code>.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting; Heap (Priority Queue)
Python
class Solution: def minimizeStringValue(self, s: str) -> str: cnt = Counter(s) pq = [(cnt[c], c) for c in ascii_lowercase] heapify(pq) t = [] for _ in range(s.count("?")): v, c = pq[0] t.append(c) heapreplace(pq, (v + 1, c)) t.sort() cs = list(s) j = 0 for i, c in enumerate(s): if c == "?": cs[i] = t[j] j += 1 return "".join(cs)
3,082
Find the Sum of the Power of All Subsequences
Hard
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>power</strong> of an array of integers is defined as the number of <span data-keyword="subsequence-array">subsequences</span> with their sum <strong>equal</strong> to <code>k</code>.</p> <p>Return <em>the <strong>sum</strong> of <strong>power</strong> of all subsequences of</em> <code>nums</code><em>.</em></p> <p>Since the answer may be very 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> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 3 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 6 </span></p> <p><strong>Explanation:</strong></p> <p>There are <code>5</code> subsequences of nums with non-zero power:</p> <ul> <li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>2</code> subsequences with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code> and <code>[<u>1</u>,<u>2</u>,3]</code>.</li> <li>The subsequence <code>[<u><strong>1</strong></u>,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> <li>The subsequence <code>[1,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> <li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,3]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[<u>1</u>,<u>2</u>,3]</code>.</li> <li>The subsequence <code>[1,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> </ul> <p>Hence the answer is <code>2 + 1 + 1 + 1 + 1 = 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,3,3], k = 5 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p> <p><strong>Explanation:</strong></p> <p>There are <code>3</code> subsequences of nums with non-zero power:</p> <ul> <li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,<u><strong>3</strong></u>]</code> has 2 subsequences with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code> and <code>[<u>2</u>,<u>3</u>,3]</code>.</li> <li>The subsequence <code>[<u><strong>2</strong></u>,3,<u><strong>3</strong></u>]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code>.</li> <li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,3]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,<u>3</u>,3]</code>.</li> </ul> <p>Hence the answer is <code>2 + 1 + 1 = 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 7 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p> <p><strong>Explanation:&nbsp;</strong>There exists no subsequence with sum <code>7</code>. Hence all subsequences of nums have <code>power = 0</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int sumOfPower(vector<int>& nums, int k) { const int mod = 1e9 + 7; int n = nums.size(); int f[n + 1][k + 1]; memset(f, 0, sizeof(f)); f[0][0] = 1; for (int i = 1; i <= n; ++i) { for (int j = 0; j <= k; ++j) { f[i][j] = (f[i - 1][j] * 2) % mod; if (j >= nums[i - 1]) { f[i][j] = (f[i][j] + f[i - 1][j - nums[i - 1]]) % mod; } } } return f[n][k]; } };
3,082
Find the Sum of the Power of All Subsequences
Hard
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>power</strong> of an array of integers is defined as the number of <span data-keyword="subsequence-array">subsequences</span> with their sum <strong>equal</strong> to <code>k</code>.</p> <p>Return <em>the <strong>sum</strong> of <strong>power</strong> of all subsequences of</em> <code>nums</code><em>.</em></p> <p>Since the answer may be very 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> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 3 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 6 </span></p> <p><strong>Explanation:</strong></p> <p>There are <code>5</code> subsequences of nums with non-zero power:</p> <ul> <li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>2</code> subsequences with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code> and <code>[<u>1</u>,<u>2</u>,3]</code>.</li> <li>The subsequence <code>[<u><strong>1</strong></u>,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> <li>The subsequence <code>[1,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> <li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,3]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[<u>1</u>,<u>2</u>,3]</code>.</li> <li>The subsequence <code>[1,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> </ul> <p>Hence the answer is <code>2 + 1 + 1 + 1 + 1 = 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,3,3], k = 5 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p> <p><strong>Explanation:</strong></p> <p>There are <code>3</code> subsequences of nums with non-zero power:</p> <ul> <li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,<u><strong>3</strong></u>]</code> has 2 subsequences with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code> and <code>[<u>2</u>,<u>3</u>,3]</code>.</li> <li>The subsequence <code>[<u><strong>2</strong></u>,3,<u><strong>3</strong></u>]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code>.</li> <li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,3]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,<u>3</u>,3]</code>.</li> </ul> <p>Hence the answer is <code>2 + 1 + 1 = 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 7 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p> <p><strong>Explanation:&nbsp;</strong>There exists no subsequence with sum <code>7</code>. Hence all subsequences of nums have <code>power = 0</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul>
Array; Dynamic Programming
Go
func sumOfPower(nums []int, k int) int { const mod int = 1e9 + 7 n := len(nums) f := make([][]int, n+1) for i := range f { f[i] = make([]int, k+1) } f[0][0] = 1 for i := 1; i <= n; i++ { for j := 0; j <= k; j++ { f[i][j] = (f[i-1][j] * 2) % mod if j >= nums[i-1] { f[i][j] = (f[i][j] + f[i-1][j-nums[i-1]]) % mod } } } return f[n][k] }
3,082
Find the Sum of the Power of All Subsequences
Hard
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>power</strong> of an array of integers is defined as the number of <span data-keyword="subsequence-array">subsequences</span> with their sum <strong>equal</strong> to <code>k</code>.</p> <p>Return <em>the <strong>sum</strong> of <strong>power</strong> of all subsequences of</em> <code>nums</code><em>.</em></p> <p>Since the answer may be very 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> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 3 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 6 </span></p> <p><strong>Explanation:</strong></p> <p>There are <code>5</code> subsequences of nums with non-zero power:</p> <ul> <li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>2</code> subsequences with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code> and <code>[<u>1</u>,<u>2</u>,3]</code>.</li> <li>The subsequence <code>[<u><strong>1</strong></u>,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> <li>The subsequence <code>[1,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> <li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,3]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[<u>1</u>,<u>2</u>,3]</code>.</li> <li>The subsequence <code>[1,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> </ul> <p>Hence the answer is <code>2 + 1 + 1 + 1 + 1 = 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,3,3], k = 5 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p> <p><strong>Explanation:</strong></p> <p>There are <code>3</code> subsequences of nums with non-zero power:</p> <ul> <li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,<u><strong>3</strong></u>]</code> has 2 subsequences with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code> and <code>[<u>2</u>,<u>3</u>,3]</code>.</li> <li>The subsequence <code>[<u><strong>2</strong></u>,3,<u><strong>3</strong></u>]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code>.</li> <li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,3]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,<u>3</u>,3]</code>.</li> </ul> <p>Hence the answer is <code>2 + 1 + 1 = 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 7 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p> <p><strong>Explanation:&nbsp;</strong>There exists no subsequence with sum <code>7</code>. Hence all subsequences of nums have <code>power = 0</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int sumOfPower(int[] nums, int k) { final int mod = (int) 1e9 + 7; int n = nums.length; int[][] f = new int[n + 1][k + 1]; f[0][0] = 1; for (int i = 1; i <= n; ++i) { for (int j = 0; j <= k; ++j) { f[i][j] = (f[i - 1][j] * 2) % mod; if (j >= nums[i - 1]) { f[i][j] = (f[i][j] + f[i - 1][j - nums[i - 1]]) % mod; } } } return f[n][k]; } }
3,082
Find the Sum of the Power of All Subsequences
Hard
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>power</strong> of an array of integers is defined as the number of <span data-keyword="subsequence-array">subsequences</span> with their sum <strong>equal</strong> to <code>k</code>.</p> <p>Return <em>the <strong>sum</strong> of <strong>power</strong> of all subsequences of</em> <code>nums</code><em>.</em></p> <p>Since the answer may be very 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> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 3 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 6 </span></p> <p><strong>Explanation:</strong></p> <p>There are <code>5</code> subsequences of nums with non-zero power:</p> <ul> <li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>2</code> subsequences with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code> and <code>[<u>1</u>,<u>2</u>,3]</code>.</li> <li>The subsequence <code>[<u><strong>1</strong></u>,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> <li>The subsequence <code>[1,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> <li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,3]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[<u>1</u>,<u>2</u>,3]</code>.</li> <li>The subsequence <code>[1,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> </ul> <p>Hence the answer is <code>2 + 1 + 1 + 1 + 1 = 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,3,3], k = 5 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p> <p><strong>Explanation:</strong></p> <p>There are <code>3</code> subsequences of nums with non-zero power:</p> <ul> <li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,<u><strong>3</strong></u>]</code> has 2 subsequences with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code> and <code>[<u>2</u>,<u>3</u>,3]</code>.</li> <li>The subsequence <code>[<u><strong>2</strong></u>,3,<u><strong>3</strong></u>]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code>.</li> <li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,3]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,<u>3</u>,3]</code>.</li> </ul> <p>Hence the answer is <code>2 + 1 + 1 = 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 7 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p> <p><strong>Explanation:&nbsp;</strong>There exists no subsequence with sum <code>7</code>. Hence all subsequences of nums have <code>power = 0</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def sumOfPower(self, nums: List[int], k: int) -> int: mod = 10**9 + 7 n = len(nums) f = [[0] * (k + 1) for _ in range(n + 1)] f[0][0] = 1 for i, x in enumerate(nums, 1): for j in range(k + 1): f[i][j] = f[i - 1][j] * 2 % mod if j >= x: f[i][j] = (f[i][j] + f[i - 1][j - x]) % mod return f[n][k]
3,082
Find the Sum of the Power of All Subsequences
Hard
<p>You are given an integer array <code>nums</code> of length <code>n</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>power</strong> of an array of integers is defined as the number of <span data-keyword="subsequence-array">subsequences</span> with their sum <strong>equal</strong> to <code>k</code>.</p> <p>Return <em>the <strong>sum</strong> of <strong>power</strong> of all subsequences of</em> <code>nums</code><em>.</em></p> <p>Since the answer may be very 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> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 3 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 6 </span></p> <p><strong>Explanation:</strong></p> <p>There are <code>5</code> subsequences of nums with non-zero power:</p> <ul> <li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>2</code> subsequences with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code> and <code>[<u>1</u>,<u>2</u>,3]</code>.</li> <li>The subsequence <code>[<u><strong>1</strong></u>,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> <li>The subsequence <code>[1,<u><strong>2</strong></u>,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> <li>The subsequence <code>[<u><strong>1</strong></u>,<u><strong>2</strong></u>,3]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[<u>1</u>,<u>2</u>,3]</code>.</li> <li>The subsequence <code>[1,2,<u><strong>3</strong></u>]</code> has <code>1</code> subsequence with <code>sum == 3</code>: <code>[1,2,<u>3</u>]</code>.</li> </ul> <p>Hence the answer is <code>2 + 1 + 1 + 1 + 1 = 6</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [2,3,3], k = 5 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 4 </span></p> <p><strong>Explanation:</strong></p> <p>There are <code>3</code> subsequences of nums with non-zero power:</p> <ul> <li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,<u><strong>3</strong></u>]</code> has 2 subsequences with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code> and <code>[<u>2</u>,<u>3</u>,3]</code>.</li> <li>The subsequence <code>[<u><strong>2</strong></u>,3,<u><strong>3</strong></u>]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,3,<u>3</u>]</code>.</li> <li>The subsequence <code>[<u><strong>2</strong></u>,<u><strong>3</strong></u>,3]</code> has 1 subsequence with <code>sum == 5</code>: <code>[<u>2</u>,<u>3</u>,3]</code>.</li> </ul> <p>Hence the answer is <code>2 + 1 + 1 = 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> nums = [1,2,3], k = 7 </span></p> <p><strong>Output: </strong> <span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;"> 0 </span></p> <p><strong>Explanation:&nbsp;</strong>There exists no subsequence with sum <code>7</code>. Hence all subsequences of nums have <code>power = 0</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul>
Array; Dynamic Programming
TypeScript
function sumOfPower(nums: number[], k: number): number { const mod = 10 ** 9 + 7; const n = nums.length; const f: number[][] = Array.from({ length: n + 1 }, () => Array(k + 1).fill(0)); f[0][0] = 1; for (let i = 1; i <= n; ++i) { for (let j = 0; j <= k; ++j) { f[i][j] = (f[i - 1][j] * 2) % mod; if (j >= nums[i - 1]) { f[i][j] = (f[i][j] + f[i - 1][j - nums[i - 1]]) % mod; } } } return f[n][k]; }
3,083
Existence of a Substring in a String and Its Reverse
Easy
<p>Given a<strong> </strong>string <code>s</code>, find any <span data-keyword="substring">substring</span> of length <code>2</code> which is also present in the reverse of <code>s</code>.</p> <p>Return <code>true</code><em> if such a substring exists, and </em><code>false</code><em> otherwise.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;leetcode&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p> <p><strong>Explanation:</strong> Substring <code>&quot;ee&quot;</code> is of length <code>2</code> which is also present in <code>reverse(s) == &quot;edocteel&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abcba&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p> <p><strong>Explanation:</strong> All of the substrings of length <code>2</code> <code>&quot;ab&quot;</code>, <code>&quot;bc&quot;</code>, <code>&quot;cb&quot;</code>, <code>&quot;ba&quot;</code> are also present in <code>reverse(s) == &quot;abcba&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abcd&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">false</span></p> <p><strong>Explanation:</strong> There is no substring of length <code>2</code> in <code>s</code>, which is also present in the reverse of <code>s</code>.</p> </div> <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 lowercase English letters.</li> </ul>
Hash Table; String
C++
class Solution { public: bool isSubstringPresent(string s) { bool st[26][26]{}; int n = s.size(); for (int i = 0; i < n - 1; ++i) { st[s[i + 1] - 'a'][s[i] - 'a'] = true; } for (int i = 0; i < n - 1; ++i) { if (st[s[i] - 'a'][s[i + 1] - 'a']) { return true; } } return false; } };
3,083
Existence of a Substring in a String and Its Reverse
Easy
<p>Given a<strong> </strong>string <code>s</code>, find any <span data-keyword="substring">substring</span> of length <code>2</code> which is also present in the reverse of <code>s</code>.</p> <p>Return <code>true</code><em> if such a substring exists, and </em><code>false</code><em> otherwise.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;leetcode&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p> <p><strong>Explanation:</strong> Substring <code>&quot;ee&quot;</code> is of length <code>2</code> which is also present in <code>reverse(s) == &quot;edocteel&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abcba&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p> <p><strong>Explanation:</strong> All of the substrings of length <code>2</code> <code>&quot;ab&quot;</code>, <code>&quot;bc&quot;</code>, <code>&quot;cb&quot;</code>, <code>&quot;ba&quot;</code> are also present in <code>reverse(s) == &quot;abcba&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abcd&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">false</span></p> <p><strong>Explanation:</strong> There is no substring of length <code>2</code> in <code>s</code>, which is also present in the reverse of <code>s</code>.</p> </div> <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 lowercase English letters.</li> </ul>
Hash Table; String
Go
func isSubstringPresent(s string) bool { st := [26][26]bool{} for i := 0; i < len(s)-1; i++ { st[s[i+1]-'a'][s[i]-'a'] = true } for i := 0; i < len(s)-1; i++ { if st[s[i]-'a'][s[i+1]-'a'] { return true } } return false }
3,083
Existence of a Substring in a String and Its Reverse
Easy
<p>Given a<strong> </strong>string <code>s</code>, find any <span data-keyword="substring">substring</span> of length <code>2</code> which is also present in the reverse of <code>s</code>.</p> <p>Return <code>true</code><em> if such a substring exists, and </em><code>false</code><em> otherwise.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;leetcode&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p> <p><strong>Explanation:</strong> Substring <code>&quot;ee&quot;</code> is of length <code>2</code> which is also present in <code>reverse(s) == &quot;edocteel&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abcba&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p> <p><strong>Explanation:</strong> All of the substrings of length <code>2</code> <code>&quot;ab&quot;</code>, <code>&quot;bc&quot;</code>, <code>&quot;cb&quot;</code>, <code>&quot;ba&quot;</code> are also present in <code>reverse(s) == &quot;abcba&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abcd&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">false</span></p> <p><strong>Explanation:</strong> There is no substring of length <code>2</code> in <code>s</code>, which is also present in the reverse of <code>s</code>.</p> </div> <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 lowercase English letters.</li> </ul>
Hash Table; String
Java
class Solution { public boolean isSubstringPresent(String s) { boolean[][] st = new boolean[26][26]; int n = s.length(); for (int i = 0; i < n - 1; ++i) { st[s.charAt(i + 1) - 'a'][s.charAt(i) - 'a'] = true; } for (int i = 0; i < n - 1; ++i) { if (st[s.charAt(i) - 'a'][s.charAt(i + 1) - 'a']) { return true; } } return false; } }
3,083
Existence of a Substring in a String and Its Reverse
Easy
<p>Given a<strong> </strong>string <code>s</code>, find any <span data-keyword="substring">substring</span> of length <code>2</code> which is also present in the reverse of <code>s</code>.</p> <p>Return <code>true</code><em> if such a substring exists, and </em><code>false</code><em> otherwise.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;leetcode&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p> <p><strong>Explanation:</strong> Substring <code>&quot;ee&quot;</code> is of length <code>2</code> which is also present in <code>reverse(s) == &quot;edocteel&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abcba&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p> <p><strong>Explanation:</strong> All of the substrings of length <code>2</code> <code>&quot;ab&quot;</code>, <code>&quot;bc&quot;</code>, <code>&quot;cb&quot;</code>, <code>&quot;ba&quot;</code> are also present in <code>reverse(s) == &quot;abcba&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abcd&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">false</span></p> <p><strong>Explanation:</strong> There is no substring of length <code>2</code> in <code>s</code>, which is also present in the reverse of <code>s</code>.</p> </div> <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 lowercase English letters.</li> </ul>
Hash Table; String
Python
class Solution: def isSubstringPresent(self, s: str) -> bool: st = {(a, b) for a, b in pairwise(s[::-1])} return any((a, b) in st for a, b in pairwise(s))
3,083
Existence of a Substring in a String and Its Reverse
Easy
<p>Given a<strong> </strong>string <code>s</code>, find any <span data-keyword="substring">substring</span> of length <code>2</code> which is also present in the reverse of <code>s</code>.</p> <p>Return <code>true</code><em> if such a substring exists, and </em><code>false</code><em> otherwise.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;leetcode&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p> <p><strong>Explanation:</strong> Substring <code>&quot;ee&quot;</code> is of length <code>2</code> which is also present in <code>reverse(s) == &quot;edocteel&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abcba&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">true</span></p> <p><strong>Explanation:</strong> All of the substrings of length <code>2</code> <code>&quot;ab&quot;</code>, <code>&quot;bc&quot;</code>, <code>&quot;cb&quot;</code>, <code>&quot;ba&quot;</code> are also present in <code>reverse(s) == &quot;abcba&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abcd&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">false</span></p> <p><strong>Explanation:</strong> There is no substring of length <code>2</code> in <code>s</code>, which is also present in the reverse of <code>s</code>.</p> </div> <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 lowercase English letters.</li> </ul>
Hash Table; String
TypeScript
function isSubstringPresent(s: string): boolean { const st: boolean[][] = Array.from({ length: 26 }, () => Array(26).fill(false)); for (let i = 0; i < s.length - 1; ++i) { st[s.charCodeAt(i + 1) - 97][s.charCodeAt(i) - 97] = true; } for (let i = 0; i < s.length - 1; ++i) { if (st[s.charCodeAt(i) - 97][s.charCodeAt(i + 1) - 97]) { return true; } } return false; }
3,084
Count Substrings Starting and Ending with Given Character
Medium
<p>You are given a string <code>s</code> and a character <code>c</code>. Return <em>the total number of <span data-keyword="substring-nonempty">substrings</span> of </em><code>s</code><em> that start and end with </em><code>c</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abada&quot;, c = &quot;a&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> Substrings starting and ending with <code>&quot;a&quot;</code> are: <code>&quot;<strong><u>a</u></strong>bada&quot;</code>, <code>&quot;<u><strong>aba</strong></u>da&quot;</code>, <code>&quot;<u><strong>abada</strong></u>&quot;</code>, <code>&quot;ab<u><strong>a</strong></u>da&quot;</code>, <code>&quot;ab<u><strong>ada</strong></u>&quot;</code>, <code>&quot;abad<u><strong>a</strong></u>&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;zzz&quot;, c = &quot;z&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> There are a total of <code>6</code> substrings in <code>s</code> and all start and end with <code>&quot;z&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>c</code> consist&nbsp;only of lowercase English letters.</li> </ul>
Math; String; Counting
C++
class Solution { public: long long countSubstrings(string s, char c) { long long cnt = ranges::count(s, c); return cnt + cnt * (cnt - 1) / 2; } };
3,084
Count Substrings Starting and Ending with Given Character
Medium
<p>You are given a string <code>s</code> and a character <code>c</code>. Return <em>the total number of <span data-keyword="substring-nonempty">substrings</span> of </em><code>s</code><em> that start and end with </em><code>c</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abada&quot;, c = &quot;a&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> Substrings starting and ending with <code>&quot;a&quot;</code> are: <code>&quot;<strong><u>a</u></strong>bada&quot;</code>, <code>&quot;<u><strong>aba</strong></u>da&quot;</code>, <code>&quot;<u><strong>abada</strong></u>&quot;</code>, <code>&quot;ab<u><strong>a</strong></u>da&quot;</code>, <code>&quot;ab<u><strong>ada</strong></u>&quot;</code>, <code>&quot;abad<u><strong>a</strong></u>&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;zzz&quot;, c = &quot;z&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> There are a total of <code>6</code> substrings in <code>s</code> and all start and end with <code>&quot;z&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>c</code> consist&nbsp;only of lowercase English letters.</li> </ul>
Math; String; Counting
Go
func countSubstrings(s string, c byte) int64 { cnt := int64(strings.Count(s, string(c))) return cnt + cnt*(cnt-1)/2 }
3,084
Count Substrings Starting and Ending with Given Character
Medium
<p>You are given a string <code>s</code> and a character <code>c</code>. Return <em>the total number of <span data-keyword="substring-nonempty">substrings</span> of </em><code>s</code><em> that start and end with </em><code>c</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abada&quot;, c = &quot;a&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> Substrings starting and ending with <code>&quot;a&quot;</code> are: <code>&quot;<strong><u>a</u></strong>bada&quot;</code>, <code>&quot;<u><strong>aba</strong></u>da&quot;</code>, <code>&quot;<u><strong>abada</strong></u>&quot;</code>, <code>&quot;ab<u><strong>a</strong></u>da&quot;</code>, <code>&quot;ab<u><strong>ada</strong></u>&quot;</code>, <code>&quot;abad<u><strong>a</strong></u>&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;zzz&quot;, c = &quot;z&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> There are a total of <code>6</code> substrings in <code>s</code> and all start and end with <code>&quot;z&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>c</code> consist&nbsp;only of lowercase English letters.</li> </ul>
Math; String; Counting
Java
class Solution { public long countSubstrings(String s, char c) { long cnt = s.chars().filter(ch -> ch == c).count(); return cnt + cnt * (cnt - 1) / 2; } }
3,084
Count Substrings Starting and Ending with Given Character
Medium
<p>You are given a string <code>s</code> and a character <code>c</code>. Return <em>the total number of <span data-keyword="substring-nonempty">substrings</span> of </em><code>s</code><em> that start and end with </em><code>c</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abada&quot;, c = &quot;a&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> Substrings starting and ending with <code>&quot;a&quot;</code> are: <code>&quot;<strong><u>a</u></strong>bada&quot;</code>, <code>&quot;<u><strong>aba</strong></u>da&quot;</code>, <code>&quot;<u><strong>abada</strong></u>&quot;</code>, <code>&quot;ab<u><strong>a</strong></u>da&quot;</code>, <code>&quot;ab<u><strong>ada</strong></u>&quot;</code>, <code>&quot;abad<u><strong>a</strong></u>&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;zzz&quot;, c = &quot;z&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> There are a total of <code>6</code> substrings in <code>s</code> and all start and end with <code>&quot;z&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>c</code> consist&nbsp;only of lowercase English letters.</li> </ul>
Math; String; Counting
Python
class Solution: def countSubstrings(self, s: str, c: str) -> int: cnt = s.count(c) return cnt + cnt * (cnt - 1) // 2
3,084
Count Substrings Starting and Ending with Given Character
Medium
<p>You are given a string <code>s</code> and a character <code>c</code>. Return <em>the total number of <span data-keyword="substring-nonempty">substrings</span> of </em><code>s</code><em> that start and end with </em><code>c</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;abada&quot;, c = &quot;a&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> Substrings starting and ending with <code>&quot;a&quot;</code> are: <code>&quot;<strong><u>a</u></strong>bada&quot;</code>, <code>&quot;<u><strong>aba</strong></u>da&quot;</code>, <code>&quot;<u><strong>abada</strong></u>&quot;</code>, <code>&quot;ab<u><strong>a</strong></u>da&quot;</code>, <code>&quot;ab<u><strong>ada</strong></u>&quot;</code>, <code>&quot;abad<u><strong>a</strong></u>&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">s = &quot;zzz&quot;, c = &quot;z&quot;</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">6</span></p> <p><strong>Explanation:</strong> There are a total of <code>6</code> substrings in <code>s</code> and all start and end with <code>&quot;z&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> and <code>c</code> consist&nbsp;only of lowercase English letters.</li> </ul>
Math; String; Counting
TypeScript
function countSubstrings(s: string, c: string): number { const cnt = s.split('').filter(ch => ch === c).length; return cnt + Math.floor((cnt * (cnt - 1)) / 2); }
3,085
Minimum Deletions to Make String K-Special
Medium
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p> <p>We consider <code>word</code> to be <strong>k-special</strong> if <code>|freq(word[i]) - freq(word[j])| &lt;= k</code> for all indices <code>i</code> and <code>j</code> in the string.</p> <p>Here, <code>freq(x)</code> denotes the <span data-keyword="frequency-letter">frequency</span> of the character <code>x</code> in <code>word</code>, and <code>|y|</code> denotes the absolute value of <code>y</code>.</p> <p>Return <em>the <strong>minimum</strong> number of characters you need to delete to make</em> <code>word</code> <strong><em>k-special</em></strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;aabcaba&quot;, k = 0</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>0</code>-special by deleting <code>2</code> occurrences of <code>&quot;a&quot;</code> and <code>1</code> occurrence of <code>&quot;c&quot;</code>. Therefore, <code>word</code> becomes equal to <code>&quot;baba&quot;</code> where <code>freq(&#39;a&#39;) == freq(&#39;b&#39;) == 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;dabdcbdcdcd&quot;, k = 2</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>&quot;a&quot;</code> and <code>1</code> occurrence of <code>&quot;d&quot;</code>. Therefore, <code>word</code> becomes equal to &quot;bdcbdcdcd&quot; where <code>freq(&#39;b&#39;) == 2</code>, <code>freq(&#39;c&#39;) == 3</code>, and <code>freq(&#39;d&#39;) == 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;aaabaaa&quot;, k = 2</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">1</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>&quot;b&quot;</code>. Therefore, <code>word</code> becomes equal to <code>&quot;aaaaaa&quot;</code> where each letter&#39;s frequency is now uniformly <code>6</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting
C++
class Solution { public: int minimumDeletions(string word, int k) { int freq[26]{}; for (char& c : word) { ++freq[c - 'a']; } vector<int> nums; for (int v : freq) { if (v) { nums.push_back(v); } } int n = word.size(); int ans = n; auto f = [&](int v) { int ans = 0; for (int x : nums) { if (x < v) { ans += x; } else if (x > v + k) { ans += x - v - k; } } return ans; }; for (int i = 0; i <= n; ++i) { ans = min(ans, f(i)); } return ans; } };
3,085
Minimum Deletions to Make String K-Special
Medium
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p> <p>We consider <code>word</code> to be <strong>k-special</strong> if <code>|freq(word[i]) - freq(word[j])| &lt;= k</code> for all indices <code>i</code> and <code>j</code> in the string.</p> <p>Here, <code>freq(x)</code> denotes the <span data-keyword="frequency-letter">frequency</span> of the character <code>x</code> in <code>word</code>, and <code>|y|</code> denotes the absolute value of <code>y</code>.</p> <p>Return <em>the <strong>minimum</strong> number of characters you need to delete to make</em> <code>word</code> <strong><em>k-special</em></strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;aabcaba&quot;, k = 0</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>0</code>-special by deleting <code>2</code> occurrences of <code>&quot;a&quot;</code> and <code>1</code> occurrence of <code>&quot;c&quot;</code>. Therefore, <code>word</code> becomes equal to <code>&quot;baba&quot;</code> where <code>freq(&#39;a&#39;) == freq(&#39;b&#39;) == 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;dabdcbdcdcd&quot;, k = 2</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>&quot;a&quot;</code> and <code>1</code> occurrence of <code>&quot;d&quot;</code>. Therefore, <code>word</code> becomes equal to &quot;bdcbdcdcd&quot; where <code>freq(&#39;b&#39;) == 2</code>, <code>freq(&#39;c&#39;) == 3</code>, and <code>freq(&#39;d&#39;) == 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;aaabaaa&quot;, k = 2</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">1</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>&quot;b&quot;</code>. Therefore, <code>word</code> becomes equal to <code>&quot;aaaaaa&quot;</code> where each letter&#39;s frequency is now uniformly <code>6</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting
Go
func minimumDeletions(word string, k int) int { freq := [26]int{} for _, c := range word { freq[c-'a']++ } nums := []int{} for _, v := range freq { if v > 0 { nums = append(nums, v) } } f := func(v int) int { ans := 0 for _, x := range nums { if x < v { ans += x } else if x > v+k { ans += x - v - k } } return ans } ans := len(word) for i := 0; i <= len(word); i++ { ans = min(ans, f(i)) } return ans }
3,085
Minimum Deletions to Make String K-Special
Medium
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p> <p>We consider <code>word</code> to be <strong>k-special</strong> if <code>|freq(word[i]) - freq(word[j])| &lt;= k</code> for all indices <code>i</code> and <code>j</code> in the string.</p> <p>Here, <code>freq(x)</code> denotes the <span data-keyword="frequency-letter">frequency</span> of the character <code>x</code> in <code>word</code>, and <code>|y|</code> denotes the absolute value of <code>y</code>.</p> <p>Return <em>the <strong>minimum</strong> number of characters you need to delete to make</em> <code>word</code> <strong><em>k-special</em></strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;aabcaba&quot;, k = 0</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>0</code>-special by deleting <code>2</code> occurrences of <code>&quot;a&quot;</code> and <code>1</code> occurrence of <code>&quot;c&quot;</code>. Therefore, <code>word</code> becomes equal to <code>&quot;baba&quot;</code> where <code>freq(&#39;a&#39;) == freq(&#39;b&#39;) == 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;dabdcbdcdcd&quot;, k = 2</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>&quot;a&quot;</code> and <code>1</code> occurrence of <code>&quot;d&quot;</code>. Therefore, <code>word</code> becomes equal to &quot;bdcbdcdcd&quot; where <code>freq(&#39;b&#39;) == 2</code>, <code>freq(&#39;c&#39;) == 3</code>, and <code>freq(&#39;d&#39;) == 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;aaabaaa&quot;, k = 2</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">1</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>&quot;b&quot;</code>. Therefore, <code>word</code> becomes equal to <code>&quot;aaaaaa&quot;</code> where each letter&#39;s frequency is now uniformly <code>6</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting
Java
class Solution { private List<Integer> nums = new ArrayList<>(); public int minimumDeletions(String word, int k) { int[] freq = new int[26]; int n = word.length(); for (int i = 0; i < n; ++i) { ++freq[word.charAt(i) - 'a']; } for (int v : freq) { if (v > 0) { nums.add(v); } } int ans = n; for (int i = 0; i <= n; ++i) { ans = Math.min(ans, f(i, k)); } return ans; } private int f(int v, int k) { int ans = 0; for (int x : nums) { if (x < v) { ans += x; } else if (x > v + k) { ans += x - v - k; } } return ans; } }
3,085
Minimum Deletions to Make String K-Special
Medium
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p> <p>We consider <code>word</code> to be <strong>k-special</strong> if <code>|freq(word[i]) - freq(word[j])| &lt;= k</code> for all indices <code>i</code> and <code>j</code> in the string.</p> <p>Here, <code>freq(x)</code> denotes the <span data-keyword="frequency-letter">frequency</span> of the character <code>x</code> in <code>word</code>, and <code>|y|</code> denotes the absolute value of <code>y</code>.</p> <p>Return <em>the <strong>minimum</strong> number of characters you need to delete to make</em> <code>word</code> <strong><em>k-special</em></strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;aabcaba&quot;, k = 0</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>0</code>-special by deleting <code>2</code> occurrences of <code>&quot;a&quot;</code> and <code>1</code> occurrence of <code>&quot;c&quot;</code>. Therefore, <code>word</code> becomes equal to <code>&quot;baba&quot;</code> where <code>freq(&#39;a&#39;) == freq(&#39;b&#39;) == 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;dabdcbdcdcd&quot;, k = 2</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>&quot;a&quot;</code> and <code>1</code> occurrence of <code>&quot;d&quot;</code>. Therefore, <code>word</code> becomes equal to &quot;bdcbdcdcd&quot; where <code>freq(&#39;b&#39;) == 2</code>, <code>freq(&#39;c&#39;) == 3</code>, and <code>freq(&#39;d&#39;) == 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;aaabaaa&quot;, k = 2</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">1</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>&quot;b&quot;</code>. Therefore, <code>word</code> becomes equal to <code>&quot;aaaaaa&quot;</code> where each letter&#39;s frequency is now uniformly <code>6</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting
Python
class Solution: def minimumDeletions(self, word: str, k: int) -> int: def f(v: int) -> int: ans = 0 for x in nums: if x < v: ans += x elif x > v + k: ans += x - v - k return ans nums = Counter(word).values() return min(f(v) for v in range(len(word) + 1))
3,085
Minimum Deletions to Make String K-Special
Medium
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p> <p>We consider <code>word</code> to be <strong>k-special</strong> if <code>|freq(word[i]) - freq(word[j])| &lt;= k</code> for all indices <code>i</code> and <code>j</code> in the string.</p> <p>Here, <code>freq(x)</code> denotes the <span data-keyword="frequency-letter">frequency</span> of the character <code>x</code> in <code>word</code>, and <code>|y|</code> denotes the absolute value of <code>y</code>.</p> <p>Return <em>the <strong>minimum</strong> number of characters you need to delete to make</em> <code>word</code> <strong><em>k-special</em></strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;aabcaba&quot;, k = 0</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>0</code>-special by deleting <code>2</code> occurrences of <code>&quot;a&quot;</code> and <code>1</code> occurrence of <code>&quot;c&quot;</code>. Therefore, <code>word</code> becomes equal to <code>&quot;baba&quot;</code> where <code>freq(&#39;a&#39;) == freq(&#39;b&#39;) == 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;dabdcbdcdcd&quot;, k = 2</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>&quot;a&quot;</code> and <code>1</code> occurrence of <code>&quot;d&quot;</code>. Therefore, <code>word</code> becomes equal to &quot;bdcbdcdcd&quot; where <code>freq(&#39;b&#39;) == 2</code>, <code>freq(&#39;c&#39;) == 3</code>, and <code>freq(&#39;d&#39;) == 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;aaabaaa&quot;, k = 2</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">1</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>&quot;b&quot;</code>. Therefore, <code>word</code> becomes equal to <code>&quot;aaaaaa&quot;</code> where each letter&#39;s frequency is now uniformly <code>6</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting
Rust
impl Solution { pub fn minimum_deletions(word: String, k: i32) -> i32 { let mut freq = [0; 26]; for c in word.chars() { freq[(c as u8 - b'a') as usize] += 1; } let mut nums = vec![]; for &v in freq.iter() { if v > 0 { nums.push(v); } } let n = word.len() as i32; let mut ans = n; for i in 0..=n { let mut cur = 0; for &x in nums.iter() { if x < i { cur += x; } else if x > i + k { cur += x - i - k; } } ans = ans.min(cur); } ans } }
3,085
Minimum Deletions to Make String K-Special
Medium
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p> <p>We consider <code>word</code> to be <strong>k-special</strong> if <code>|freq(word[i]) - freq(word[j])| &lt;= k</code> for all indices <code>i</code> and <code>j</code> in the string.</p> <p>Here, <code>freq(x)</code> denotes the <span data-keyword="frequency-letter">frequency</span> of the character <code>x</code> in <code>word</code>, and <code>|y|</code> denotes the absolute value of <code>y</code>.</p> <p>Return <em>the <strong>minimum</strong> number of characters you need to delete to make</em> <code>word</code> <strong><em>k-special</em></strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;aabcaba&quot;, k = 0</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>0</code>-special by deleting <code>2</code> occurrences of <code>&quot;a&quot;</code> and <code>1</code> occurrence of <code>&quot;c&quot;</code>. Therefore, <code>word</code> becomes equal to <code>&quot;baba&quot;</code> where <code>freq(&#39;a&#39;) == freq(&#39;b&#39;) == 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;dabdcbdcdcd&quot;, k = 2</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">2</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>&quot;a&quot;</code> and <code>1</code> occurrence of <code>&quot;d&quot;</code>. Therefore, <code>word</code> becomes equal to &quot;bdcbdcdcd&quot; where <code>freq(&#39;b&#39;) == 2</code>, <code>freq(&#39;c&#39;) == 3</code>, and <code>freq(&#39;d&#39;) == 4</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">word = &quot;aaabaaa&quot;, k = 2</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">1</span></p> <p><strong>Explanation:</strong> We can make <code>word</code> <code>2</code>-special by deleting <code>1</code> occurrence of <code>&quot;b&quot;</code>. Therefore, <code>word</code> becomes equal to <code>&quot;aaaaaa&quot;</code> where each letter&#39;s frequency is now uniformly <code>6</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Greedy; Hash Table; String; Counting; Sorting
TypeScript
function minimumDeletions(word: string, k: number): number { const freq: number[] = Array(26).fill(0); for (const ch of word) { ++freq[ch.charCodeAt(0) - 97]; } const nums = freq.filter(x => x > 0); const f = (v: number): number => { let ans = 0; for (const x of nums) { if (x < v) { ans += x; } else if (x > v + k) { ans += x - v - k; } } return ans; }; return Math.min(...Array.from({ length: word.length + 1 }, (_, i) => f(i))); }
3,086
Minimum Moves to Pick K Ones
Hard
<p>You are given a binary array <code>nums</code> of length <code>n</code>, a <strong>positive</strong> integer <code>k</code> and a <strong>non-negative</strong> integer <code>maxChanges</code>.</p> <p>Alice plays a game, where the goal is for Alice to pick up <code>k</code> ones from <code>nums</code> using the <strong>minimum</strong> number of <strong>moves</strong>. When the game starts, Alice picks up any index <code>aliceIndex</code> in the range <code>[0, n - 1]</code> and stands there. If <code>nums[aliceIndex] == 1</code> , Alice picks up the one and <code>nums[aliceIndex]</code> becomes <code>0</code>(this <strong>does not</strong> count as a move). After this, Alice can make <strong>any</strong> number of <strong>moves</strong> (<strong>including</strong> <strong>zero</strong>) where in each move Alice must perform <strong>exactly</strong> one of the following actions:</p> <ul> <li>Select any index <code>j != aliceIndex</code> such that <code>nums[j] == 0</code> and set <code>nums[j] = 1</code>. This action can be performed <strong>at</strong> <strong>most</strong> <code>maxChanges</code> times.</li> <li>Select any two adjacent indices <code>x</code> and <code>y</code> (<code>|x - y| == 1</code>) such that <code>nums[x] == 1</code>, <code>nums[y] == 0</code>, then swap their values (set <code>nums[y] = 1</code> and <code>nums[x] = 0</code>). If <code>y == aliceIndex</code>, Alice picks up the one after this move and <code>nums[y]</code> becomes <code>0</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of moves required by Alice to pick <strong>exactly </strong></em><code>k</code> <em>ones</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p> <p><strong>Explanation:</strong> Alice can pick up <code>3</code> ones in <code>3</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 1</code>:</p> <ul> <li>At the start of the game Alice picks up the one and <code>nums[1]</code> becomes <code>0</code>. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> <li>Select <code>j == 2</code> and perform an action of the first type. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,1,0,0,1,1,0,0,1]</code></li> <li>Select <code>x == 2</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[1,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> <li>Select <code>x == 0</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[0,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[0,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> </ul> <p>Note that it may be possible for Alice to pick up <code>3</code> ones using some other sequence of <code>3</code> moves.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [0,0,0,0], k = 2, maxChanges = 3</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong> Alice can pick up <code>2</code> ones in <code>4</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 0</code>:</p> <ul> <li>Select <code>j == 1</code> and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li> <li>Select <code>x == 1</code> and <code>y == 0</code>, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li> <li>Select <code>j == 1</code> again and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li> <li>Select <code>x == 1</code> and <code>y == 0</code> again, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= maxChanges &lt;= 10<sup>5</sup></code></li> <li><code>maxChanges + sum(nums) &gt;= k</code></li> </ul>
Greedy; Array; Prefix Sum; Sliding Window
C++
class Solution { public: long long minimumMoves(vector<int>& nums, int k, int maxChanges) { int n = nums.size(); vector<int> cnt(n + 1, 0); vector<long long> s(n + 1, 0); for (int i = 1; i <= n; ++i) { cnt[i] = cnt[i - 1] + nums[i - 1]; s[i] = s[i - 1] + 1LL * i * nums[i - 1]; } long long ans = LLONG_MAX; for (int i = 1; i <= n; ++i) { long long t = 0; int need = k - nums[i - 1]; for (int j = i - 1; j <= i + 1; j += 2) { if (need > 0 && 1 <= j && j <= n && nums[j - 1] == 1) { --need; ++t; } } int c = min(need, maxChanges); need -= c; t += c * 2; if (need <= 0) { ans = min(ans, t); continue; } int l = 2, r = max(i - 1, n - i); while (l <= r) { int mid = (l + r) / 2; int l1 = max(1, i - mid), r1 = max(0, i - 2); int l2 = min(n + 1, i + 2), r2 = min(n, i + mid); int c1 = cnt[r1] - cnt[l1 - 1]; int c2 = cnt[r2] - cnt[l2 - 1]; if (c1 + c2 >= need) { long long t1 = 1LL * c1 * i - (s[r1] - s[l1 - 1]); long long t2 = s[r2] - s[l2 - 1] - 1LL * c2 * i; ans = min(ans, t + t1 + t2); r = mid - 1; } else { l = mid + 1; } } } return ans; } };
3,086
Minimum Moves to Pick K Ones
Hard
<p>You are given a binary array <code>nums</code> of length <code>n</code>, a <strong>positive</strong> integer <code>k</code> and a <strong>non-negative</strong> integer <code>maxChanges</code>.</p> <p>Alice plays a game, where the goal is for Alice to pick up <code>k</code> ones from <code>nums</code> using the <strong>minimum</strong> number of <strong>moves</strong>. When the game starts, Alice picks up any index <code>aliceIndex</code> in the range <code>[0, n - 1]</code> and stands there. If <code>nums[aliceIndex] == 1</code> , Alice picks up the one and <code>nums[aliceIndex]</code> becomes <code>0</code>(this <strong>does not</strong> count as a move). After this, Alice can make <strong>any</strong> number of <strong>moves</strong> (<strong>including</strong> <strong>zero</strong>) where in each move Alice must perform <strong>exactly</strong> one of the following actions:</p> <ul> <li>Select any index <code>j != aliceIndex</code> such that <code>nums[j] == 0</code> and set <code>nums[j] = 1</code>. This action can be performed <strong>at</strong> <strong>most</strong> <code>maxChanges</code> times.</li> <li>Select any two adjacent indices <code>x</code> and <code>y</code> (<code>|x - y| == 1</code>) such that <code>nums[x] == 1</code>, <code>nums[y] == 0</code>, then swap their values (set <code>nums[y] = 1</code> and <code>nums[x] = 0</code>). If <code>y == aliceIndex</code>, Alice picks up the one after this move and <code>nums[y]</code> becomes <code>0</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of moves required by Alice to pick <strong>exactly </strong></em><code>k</code> <em>ones</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p> <p><strong>Explanation:</strong> Alice can pick up <code>3</code> ones in <code>3</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 1</code>:</p> <ul> <li>At the start of the game Alice picks up the one and <code>nums[1]</code> becomes <code>0</code>. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> <li>Select <code>j == 2</code> and perform an action of the first type. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,1,0,0,1,1,0,0,1]</code></li> <li>Select <code>x == 2</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[1,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> <li>Select <code>x == 0</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[0,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[0,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> </ul> <p>Note that it may be possible for Alice to pick up <code>3</code> ones using some other sequence of <code>3</code> moves.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [0,0,0,0], k = 2, maxChanges = 3</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong> Alice can pick up <code>2</code> ones in <code>4</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 0</code>:</p> <ul> <li>Select <code>j == 1</code> and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li> <li>Select <code>x == 1</code> and <code>y == 0</code>, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li> <li>Select <code>j == 1</code> again and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li> <li>Select <code>x == 1</code> and <code>y == 0</code> again, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= maxChanges &lt;= 10<sup>5</sup></code></li> <li><code>maxChanges + sum(nums) &gt;= k</code></li> </ul>
Greedy; Array; Prefix Sum; Sliding Window
Go
func minimumMoves(nums []int, k int, maxChanges int) int64 { n := len(nums) cnt := make([]int, n+1) s := make([]int, n+1) for i := 1; i <= n; i++ { cnt[i] = cnt[i-1] + nums[i-1] s[i] = s[i-1] + i*nums[i-1] } ans := math.MaxInt64 for i := 1; i <= n; i++ { t := 0 need := k - nums[i-1] for _, j := range []int{i - 1, i + 1} { if need > 0 && 1 <= j && j <= n && nums[j-1] == 1 { need-- t++ } } c := min(need, maxChanges) need -= c t += c * 2 if need <= 0 { ans = min(ans, t) continue } l, r := 2, max(i-1, n-i) for l <= r { mid := (l + r) >> 1 l1, r1 := max(1, i-mid), max(0, i-2) l2, r2 := min(n+1, i+2), min(n, i+mid) c1 := cnt[r1] - cnt[l1-1] c2 := cnt[r2] - cnt[l2-1] if c1+c2 >= need { t1 := c1*i - (s[r1] - s[l1-1]) t2 := s[r2] - s[l2-1] - c2*i ans = min(ans, t+t1+t2) r = mid - 1 } else { l = mid + 1 } } } return int64(ans) }
3,086
Minimum Moves to Pick K Ones
Hard
<p>You are given a binary array <code>nums</code> of length <code>n</code>, a <strong>positive</strong> integer <code>k</code> and a <strong>non-negative</strong> integer <code>maxChanges</code>.</p> <p>Alice plays a game, where the goal is for Alice to pick up <code>k</code> ones from <code>nums</code> using the <strong>minimum</strong> number of <strong>moves</strong>. When the game starts, Alice picks up any index <code>aliceIndex</code> in the range <code>[0, n - 1]</code> and stands there. If <code>nums[aliceIndex] == 1</code> , Alice picks up the one and <code>nums[aliceIndex]</code> becomes <code>0</code>(this <strong>does not</strong> count as a move). After this, Alice can make <strong>any</strong> number of <strong>moves</strong> (<strong>including</strong> <strong>zero</strong>) where in each move Alice must perform <strong>exactly</strong> one of the following actions:</p> <ul> <li>Select any index <code>j != aliceIndex</code> such that <code>nums[j] == 0</code> and set <code>nums[j] = 1</code>. This action can be performed <strong>at</strong> <strong>most</strong> <code>maxChanges</code> times.</li> <li>Select any two adjacent indices <code>x</code> and <code>y</code> (<code>|x - y| == 1</code>) such that <code>nums[x] == 1</code>, <code>nums[y] == 0</code>, then swap their values (set <code>nums[y] = 1</code> and <code>nums[x] = 0</code>). If <code>y == aliceIndex</code>, Alice picks up the one after this move and <code>nums[y]</code> becomes <code>0</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of moves required by Alice to pick <strong>exactly </strong></em><code>k</code> <em>ones</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p> <p><strong>Explanation:</strong> Alice can pick up <code>3</code> ones in <code>3</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 1</code>:</p> <ul> <li>At the start of the game Alice picks up the one and <code>nums[1]</code> becomes <code>0</code>. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> <li>Select <code>j == 2</code> and perform an action of the first type. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,1,0,0,1,1,0,0,1]</code></li> <li>Select <code>x == 2</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[1,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> <li>Select <code>x == 0</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[0,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[0,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> </ul> <p>Note that it may be possible for Alice to pick up <code>3</code> ones using some other sequence of <code>3</code> moves.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [0,0,0,0], k = 2, maxChanges = 3</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong> Alice can pick up <code>2</code> ones in <code>4</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 0</code>:</p> <ul> <li>Select <code>j == 1</code> and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li> <li>Select <code>x == 1</code> and <code>y == 0</code>, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li> <li>Select <code>j == 1</code> again and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li> <li>Select <code>x == 1</code> and <code>y == 0</code> again, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= maxChanges &lt;= 10<sup>5</sup></code></li> <li><code>maxChanges + sum(nums) &gt;= k</code></li> </ul>
Greedy; Array; Prefix Sum; Sliding Window
Java
class Solution { public long minimumMoves(int[] nums, int k, int maxChanges) { int n = nums.length; int[] cnt = new int[n + 1]; long[] s = new long[n + 1]; for (int i = 1; i <= n; ++i) { cnt[i] = cnt[i - 1] + nums[i - 1]; s[i] = s[i - 1] + i * nums[i - 1]; } long ans = Long.MAX_VALUE; for (int i = 1; i <= n; ++i) { long t = 0; int need = k - nums[i - 1]; for (int j = i - 1; j <= i + 1; j += 2) { if (need > 0 && 1 <= j && j <= n && nums[j - 1] == 1) { --need; ++t; } } int c = Math.min(need, maxChanges); need -= c; t += c * 2; if (need <= 0) { ans = Math.min(ans, t); continue; } int l = 2, r = Math.max(i - 1, n - i); while (l <= r) { int mid = (l + r) >> 1; int l1 = Math.max(1, i - mid), r1 = Math.max(0, i - 2); int l2 = Math.min(n + 1, i + 2), r2 = Math.min(n, i + mid); int c1 = cnt[r1] - cnt[l1 - 1]; int c2 = cnt[r2] - cnt[l2 - 1]; if (c1 + c2 >= need) { long t1 = 1L * c1 * i - (s[r1] - s[l1 - 1]); long t2 = s[r2] - s[l2 - 1] - 1L * c2 * i; ans = Math.min(ans, t + t1 + t2); r = mid - 1; } else { l = mid + 1; } } } return ans; } }
3,086
Minimum Moves to Pick K Ones
Hard
<p>You are given a binary array <code>nums</code> of length <code>n</code>, a <strong>positive</strong> integer <code>k</code> and a <strong>non-negative</strong> integer <code>maxChanges</code>.</p> <p>Alice plays a game, where the goal is for Alice to pick up <code>k</code> ones from <code>nums</code> using the <strong>minimum</strong> number of <strong>moves</strong>. When the game starts, Alice picks up any index <code>aliceIndex</code> in the range <code>[0, n - 1]</code> and stands there. If <code>nums[aliceIndex] == 1</code> , Alice picks up the one and <code>nums[aliceIndex]</code> becomes <code>0</code>(this <strong>does not</strong> count as a move). After this, Alice can make <strong>any</strong> number of <strong>moves</strong> (<strong>including</strong> <strong>zero</strong>) where in each move Alice must perform <strong>exactly</strong> one of the following actions:</p> <ul> <li>Select any index <code>j != aliceIndex</code> such that <code>nums[j] == 0</code> and set <code>nums[j] = 1</code>. This action can be performed <strong>at</strong> <strong>most</strong> <code>maxChanges</code> times.</li> <li>Select any two adjacent indices <code>x</code> and <code>y</code> (<code>|x - y| == 1</code>) such that <code>nums[x] == 1</code>, <code>nums[y] == 0</code>, then swap their values (set <code>nums[y] = 1</code> and <code>nums[x] = 0</code>). If <code>y == aliceIndex</code>, Alice picks up the one after this move and <code>nums[y]</code> becomes <code>0</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of moves required by Alice to pick <strong>exactly </strong></em><code>k</code> <em>ones</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p> <p><strong>Explanation:</strong> Alice can pick up <code>3</code> ones in <code>3</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 1</code>:</p> <ul> <li>At the start of the game Alice picks up the one and <code>nums[1]</code> becomes <code>0</code>. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> <li>Select <code>j == 2</code> and perform an action of the first type. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,1,0,0,1,1,0,0,1]</code></li> <li>Select <code>x == 2</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[1,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> <li>Select <code>x == 0</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[0,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[0,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> </ul> <p>Note that it may be possible for Alice to pick up <code>3</code> ones using some other sequence of <code>3</code> moves.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [0,0,0,0], k = 2, maxChanges = 3</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong> Alice can pick up <code>2</code> ones in <code>4</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 0</code>:</p> <ul> <li>Select <code>j == 1</code> and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li> <li>Select <code>x == 1</code> and <code>y == 0</code>, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li> <li>Select <code>j == 1</code> again and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li> <li>Select <code>x == 1</code> and <code>y == 0</code> again, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= maxChanges &lt;= 10<sup>5</sup></code></li> <li><code>maxChanges + sum(nums) &gt;= k</code></li> </ul>
Greedy; Array; Prefix Sum; Sliding Window
Python
class Solution: def minimumMoves(self, nums: List[int], k: int, maxChanges: int) -> int: n = len(nums) cnt = [0] * (n + 1) s = [0] * (n + 1) for i, x in enumerate(nums, 1): cnt[i] = cnt[i - 1] + x s[i] = s[i - 1] + i * x ans = inf max = lambda x, y: x if x > y else y min = lambda x, y: x if x < y else y for i, x in enumerate(nums, 1): t = 0 need = k - x for j in (i - 1, i + 1): if need > 0 and 1 <= j <= n and nums[j - 1] == 1: need -= 1 t += 1 c = min(need, maxChanges) need -= c t += c * 2 if need <= 0: ans = min(ans, t) continue l, r = 2, max(i - 1, n - i) while l <= r: mid = (l + r) >> 1 l1, r1 = max(1, i - mid), max(0, i - 2) l2, r2 = min(n + 1, i + 2), min(n, i + mid) c1 = cnt[r1] - cnt[l1 - 1] c2 = cnt[r2] - cnt[l2 - 1] if c1 + c2 >= need: t1 = c1 * i - (s[r1] - s[l1 - 1]) t2 = s[r2] - s[l2 - 1] - c2 * i ans = min(ans, t + t1 + t2) r = mid - 1 else: l = mid + 1 return ans
3,086
Minimum Moves to Pick K Ones
Hard
<p>You are given a binary array <code>nums</code> of length <code>n</code>, a <strong>positive</strong> integer <code>k</code> and a <strong>non-negative</strong> integer <code>maxChanges</code>.</p> <p>Alice plays a game, where the goal is for Alice to pick up <code>k</code> ones from <code>nums</code> using the <strong>minimum</strong> number of <strong>moves</strong>. When the game starts, Alice picks up any index <code>aliceIndex</code> in the range <code>[0, n - 1]</code> and stands there. If <code>nums[aliceIndex] == 1</code> , Alice picks up the one and <code>nums[aliceIndex]</code> becomes <code>0</code>(this <strong>does not</strong> count as a move). After this, Alice can make <strong>any</strong> number of <strong>moves</strong> (<strong>including</strong> <strong>zero</strong>) where in each move Alice must perform <strong>exactly</strong> one of the following actions:</p> <ul> <li>Select any index <code>j != aliceIndex</code> such that <code>nums[j] == 0</code> and set <code>nums[j] = 1</code>. This action can be performed <strong>at</strong> <strong>most</strong> <code>maxChanges</code> times.</li> <li>Select any two adjacent indices <code>x</code> and <code>y</code> (<code>|x - y| == 1</code>) such that <code>nums[x] == 1</code>, <code>nums[y] == 0</code>, then swap their values (set <code>nums[y] = 1</code> and <code>nums[x] = 0</code>). If <code>y == aliceIndex</code>, Alice picks up the one after this move and <code>nums[y]</code> becomes <code>0</code>.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of moves required by Alice to pick <strong>exactly </strong></em><code>k</code> <em>ones</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">3</span></p> <p><strong>Explanation:</strong> Alice can pick up <code>3</code> ones in <code>3</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 1</code>:</p> <ul> <li>At the start of the game Alice picks up the one and <code>nums[1]</code> becomes <code>0</code>. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> <li>Select <code>j == 2</code> and perform an action of the first type. <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,1,0,0,1,1,0,0,1]</code></li> <li>Select <code>x == 2</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[1,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[1,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> <li>Select <code>x == 0</code> and <code>y == 1</code>, and perform an action of the second type. <code>nums</code> becomes <code>[0,<strong><u>1</u></strong>,0,0,0,1,1,0,0,1]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[0,<strong><u>0</u></strong>,0,0,0,1,1,0,0,1]</code>.</li> </ul> <p>Note that it may be possible for Alice to pick up <code>3</code> ones using some other sequence of <code>3</code> moves.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">nums = [0,0,0,0], k = 2, maxChanges = 3</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong> Alice can pick up <code>2</code> ones in <code>4</code> moves, if Alice performs the following actions in each move when standing at <code>aliceIndex == 0</code>:</p> <ul> <li>Select <code>j == 1</code> and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li> <li>Select <code>x == 1</code> and <code>y == 0</code>, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li> <li>Select <code>j == 1</code> again and perform an action of the first type. <code>nums</code> becomes <code>[<strong><u>0</u></strong>,1,0,0]</code>.</li> <li>Select <code>x == 1</code> and <code>y == 0</code> again, and perform an action of the second type. <code>nums</code> becomes <code>[<strong><u>1</u></strong>,0,0,0]</code>. As <code>y == aliceIndex</code>, Alice picks up the one and <code>nums</code> becomes <code>[<strong><u>0</u></strong>,0,0,0]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 1</code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= maxChanges &lt;= 10<sup>5</sup></code></li> <li><code>maxChanges + sum(nums) &gt;= k</code></li> </ul>
Greedy; Array; Prefix Sum; Sliding Window
TypeScript
function minimumMoves(nums: number[], k: number, maxChanges: number): number { const n = nums.length; const cnt = Array(n + 1).fill(0); const s = Array(n + 1).fill(0); for (let i = 1; i <= n; i++) { cnt[i] = cnt[i - 1] + nums[i - 1]; s[i] = s[i - 1] + i * nums[i - 1]; } let ans = Infinity; for (let i = 1; i <= n; i++) { let t = 0; let need = k - nums[i - 1]; for (let j of [i - 1, i + 1]) { if (need > 0 && 1 <= j && j <= n && nums[j - 1] === 1) { need--; t++; } } const c = Math.min(need, maxChanges); need -= c; t += c * 2; if (need <= 0) { ans = Math.min(ans, t); continue; } let l = 2, r = Math.max(i - 1, n - i); while (l <= r) { const mid = (l + r) >> 1; const [l1, r1] = [Math.max(1, i - mid), Math.max(0, i - 2)]; const [l2, r2] = [Math.min(n + 1, i + 2), Math.min(n, i + mid)]; const c1 = cnt[r1] - cnt[l1 - 1]; const c2 = cnt[r2] - cnt[l2 - 1]; if (c1 + c2 >= need) { const t1 = c1 * i - (s[r1] - s[l1 - 1]); const t2 = s[r2] - s[l2 - 1] - c2 * i; ans = Math.min(ans, t + t1 + t2); r = mid - 1; } else { l = mid + 1; } } } return ans; }
3,087
Find Trending Hashtags
Medium
<p>Table: <code>Tweets</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | user_id | int | | tweet_id | int | | tweet_date | date | | tweet | varchar | +-------------+---------+ tweet_id is the primary key (column with unique values) for this table. Each row of this table contains user_id, tweet_id, tweet_date and tweet. </pre> <p>Write a solution to find the <strong>top</strong> <code>3</code> trending <strong>hashtags</strong>&nbsp;in&nbsp;<strong>February</strong> <code>2024</code>. Each tweet only contains one hashtag.</p> <p>Return <em>the result table orderd by count of hashtag, hashtag in </em><strong>descending</strong><em> order.</em></p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Tweets table:</p> <pre class="example-io"> +---------+----------+----------------------------------------------+------------+ | user_id | tweet_id | tweet | tweet_date | +---------+----------+----------------------------------------------+------------+ | 135 | 13 | Enjoying a great start to the day! #HappyDay | 2024-02-01 | | 136 | 14 | Another #HappyDay with good vibes! | 2024-02-03 | | 137 | 15 | Productivity peaks! #WorkLife | 2024-02-04 | | 138 | 16 | Exploring new tech frontiers. #TechLife | 2024-02-04 | | 139 | 17 | Gratitude for today&#39;s moments. #HappyDay | 2024-02-05 | | 140 | 18 | Innovation drives us. #TechLife | 2024-02-07 | | 141 | 19 | Connecting with nature&#39;s serenity. #Nature | 2024-02-09 | +---------+----------+----------------------------------------------+------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-----------+--------------+ | hashtag | hashtag_count| +-----------+--------------+ | #HappyDay | 3 | | #TechLife | 2 | | #WorkLife | 1 | +-----------+--------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>#HappyDay:</strong> Appeared in tweet IDs 13, 14, and 17, with a total count of 3 mentions.</li> <li><strong>#TechLife:</strong> Appeared in tweet IDs 16 and 18, with a total count of 2 mentions.</li> <li><strong>#WorkLife:</strong> Appeared in tweet ID 15, with a total count of 1 mention.</li> </ul> <p><b>Note:</b> Output table is sorted in descending order by hashtag_count and hashtag respectively.</p> </div>
Database
Python
import pandas as pd def find_trending_hashtags(tweets: pd.DataFrame) -> pd.DataFrame: tweets = tweets[tweets["tweet_date"].dt.strftime("%Y%m") == "202402"] tweets["hashtag"] = "#" + tweets["tweet"].str.extract(r"#(\w+)") hashtag_counts = tweets["hashtag"].value_counts().reset_index() hashtag_counts.columns = ["hashtag", "hashtag_count"] hashtag_counts = hashtag_counts.sort_values( by=["hashtag_count", "hashtag"], ascending=[False, False] ) top_3_hashtags = hashtag_counts.head(3) return top_3_hashtags
3,087
Find Trending Hashtags
Medium
<p>Table: <code>Tweets</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | user_id | int | | tweet_id | int | | tweet_date | date | | tweet | varchar | +-------------+---------+ tweet_id is the primary key (column with unique values) for this table. Each row of this table contains user_id, tweet_id, tweet_date and tweet. </pre> <p>Write a solution to find the <strong>top</strong> <code>3</code> trending <strong>hashtags</strong>&nbsp;in&nbsp;<strong>February</strong> <code>2024</code>. Each tweet only contains one hashtag.</p> <p>Return <em>the result table orderd by count of hashtag, hashtag in </em><strong>descending</strong><em> order.</em></p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Tweets table:</p> <pre class="example-io"> +---------+----------+----------------------------------------------+------------+ | user_id | tweet_id | tweet | tweet_date | +---------+----------+----------------------------------------------+------------+ | 135 | 13 | Enjoying a great start to the day! #HappyDay | 2024-02-01 | | 136 | 14 | Another #HappyDay with good vibes! | 2024-02-03 | | 137 | 15 | Productivity peaks! #WorkLife | 2024-02-04 | | 138 | 16 | Exploring new tech frontiers. #TechLife | 2024-02-04 | | 139 | 17 | Gratitude for today&#39;s moments. #HappyDay | 2024-02-05 | | 140 | 18 | Innovation drives us. #TechLife | 2024-02-07 | | 141 | 19 | Connecting with nature&#39;s serenity. #Nature | 2024-02-09 | +---------+----------+----------------------------------------------+------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-----------+--------------+ | hashtag | hashtag_count| +-----------+--------------+ | #HappyDay | 3 | | #TechLife | 2 | | #WorkLife | 1 | +-----------+--------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>#HappyDay:</strong> Appeared in tweet IDs 13, 14, and 17, with a total count of 3 mentions.</li> <li><strong>#TechLife:</strong> Appeared in tweet IDs 16 and 18, with a total count of 2 mentions.</li> <li><strong>#WorkLife:</strong> Appeared in tweet ID 15, with a total count of 1 mention.</li> </ul> <p><b>Note:</b> Output table is sorted in descending order by hashtag_count and hashtag respectively.</p> </div>
Database
SQL
# Write your MySQL query statement below SELECT CONCAT('#', SUBSTRING_INDEX(SUBSTRING_INDEX(tweet, '#', -1), ' ', 1)) AS hashtag, COUNT(1) AS hashtag_count FROM Tweets WHERE DATE_FORMAT(tweet_date, '%Y%m') = '202402' GROUP BY 1 ORDER BY 2 DESC, 1 DESC LIMIT 3;
3,088
Make String Anti-palindrome
Hard
<p>We call a string <code>s</code> of <strong>even</strong> length <code>n</code> an <strong>anti-palindrome</strong> if for each index <code>0 &lt;= i &lt; n</code>, <code>s[i] != s[n - i - 1]</code>.</p> <p>Given a string <code>s</code>, your task is to make <code>s</code> an <strong>anti-palindrome</strong> by doing <strong>any</strong> number of operations (including zero).</p> <p>In one operation, you can select two characters from <code>s</code> and swap them.</p> <p>Return <em>the resulting string. If multiple strings meet the conditions, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one. If it can&#39;t be made into an anti-palindrome, return </em><code>&quot;-1&quot;</code><em>.</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">s = &quot;abca&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aabc&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aabc&quot;</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>&quot;abca&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aabb&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aabb&quot;</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>&quot;abba&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;cccd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;-1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>You can see that no matter how you rearrange the characters of <code>&quot;cccd&quot;</code>, either <code>s[0] == s[3]</code> or <code>s[1] == s[2]</code>. So it can not form an anti-palindrome string.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s.length % 2 == 0</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; String; Counting Sort; Sorting
C++
class Solution { public: string makeAntiPalindrome(string s) { sort(s.begin(), s.end()); int n = s.length(); int m = n / 2; if (s[m] == s[m - 1]) { int i = m; while (i < n && s[i] == s[i - 1]) { ++i; } for (int j = m; j < n && s[j] == s[n - j - 1]; ++i, ++j) { if (i >= n) { return "-1"; } swap(s[i], s[j]); } } return s; } };
3,088
Make String Anti-palindrome
Hard
<p>We call a string <code>s</code> of <strong>even</strong> length <code>n</code> an <strong>anti-palindrome</strong> if for each index <code>0 &lt;= i &lt; n</code>, <code>s[i] != s[n - i - 1]</code>.</p> <p>Given a string <code>s</code>, your task is to make <code>s</code> an <strong>anti-palindrome</strong> by doing <strong>any</strong> number of operations (including zero).</p> <p>In one operation, you can select two characters from <code>s</code> and swap them.</p> <p>Return <em>the resulting string. If multiple strings meet the conditions, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one. If it can&#39;t be made into an anti-palindrome, return </em><code>&quot;-1&quot;</code><em>.</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">s = &quot;abca&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aabc&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aabc&quot;</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>&quot;abca&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aabb&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aabb&quot;</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>&quot;abba&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;cccd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;-1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>You can see that no matter how you rearrange the characters of <code>&quot;cccd&quot;</code>, either <code>s[0] == s[3]</code> or <code>s[1] == s[2]</code>. So it can not form an anti-palindrome string.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s.length % 2 == 0</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; String; Counting Sort; Sorting
Go
func makeAntiPalindrome(s string) string { cs := []byte(s) sort.Slice(cs, func(i, j int) bool { return cs[i] < cs[j] }) n := len(cs) m := n / 2 if cs[m] == cs[m-1] { i := m for i < n && cs[i] == cs[i-1] { i++ } for j := m; j < n && cs[j] == cs[n-j-1]; i, j = i+1, j+1 { if i >= n { return "-1" } cs[i], cs[j] = cs[j], cs[i] } } return string(cs) }
3,088
Make String Anti-palindrome
Hard
<p>We call a string <code>s</code> of <strong>even</strong> length <code>n</code> an <strong>anti-palindrome</strong> if for each index <code>0 &lt;= i &lt; n</code>, <code>s[i] != s[n - i - 1]</code>.</p> <p>Given a string <code>s</code>, your task is to make <code>s</code> an <strong>anti-palindrome</strong> by doing <strong>any</strong> number of operations (including zero).</p> <p>In one operation, you can select two characters from <code>s</code> and swap them.</p> <p>Return <em>the resulting string. If multiple strings meet the conditions, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one. If it can&#39;t be made into an anti-palindrome, return </em><code>&quot;-1&quot;</code><em>.</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">s = &quot;abca&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aabc&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aabc&quot;</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>&quot;abca&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aabb&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aabb&quot;</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>&quot;abba&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;cccd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;-1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>You can see that no matter how you rearrange the characters of <code>&quot;cccd&quot;</code>, either <code>s[0] == s[3]</code> or <code>s[1] == s[2]</code>. So it can not form an anti-palindrome string.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s.length % 2 == 0</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; String; Counting Sort; Sorting
Java
class Solution { public String makeAntiPalindrome(String s) { char[] cs = s.toCharArray(); Arrays.sort(cs); int n = cs.length; int m = n / 2; if (cs[m] == cs[m - 1]) { int i = m; while (i < n && cs[i] == cs[i - 1]) { ++i; } for (int j = m; j < n && cs[j] == cs[n - j - 1]; ++i, ++j) { if (i >= n) { return "-1"; } char t = cs[i]; cs[i] = cs[j]; cs[j] = t; } } return new String(cs); } }
3,088
Make String Anti-palindrome
Hard
<p>We call a string <code>s</code> of <strong>even</strong> length <code>n</code> an <strong>anti-palindrome</strong> if for each index <code>0 &lt;= i &lt; n</code>, <code>s[i] != s[n - i - 1]</code>.</p> <p>Given a string <code>s</code>, your task is to make <code>s</code> an <strong>anti-palindrome</strong> by doing <strong>any</strong> number of operations (including zero).</p> <p>In one operation, you can select two characters from <code>s</code> and swap them.</p> <p>Return <em>the resulting string. If multiple strings meet the conditions, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one. If it can&#39;t be made into an anti-palindrome, return </em><code>&quot;-1&quot;</code><em>.</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">s = &quot;abca&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aabc&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aabc&quot;</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>&quot;abca&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aabb&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aabb&quot;</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>&quot;abba&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;cccd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;-1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>You can see that no matter how you rearrange the characters of <code>&quot;cccd&quot;</code>, either <code>s[0] == s[3]</code> or <code>s[1] == s[2]</code>. So it can not form an anti-palindrome string.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s.length % 2 == 0</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; String; Counting Sort; Sorting
Python
class Solution: def makeAntiPalindrome(self, s: str) -> str: cs = sorted(s) n = len(cs) m = n // 2 if cs[m] == cs[m - 1]: i = m while i < n and cs[i] == cs[i - 1]: i += 1 j = m while j < n and cs[j] == cs[n - j - 1]: if i >= n: return "-1" cs[i], cs[j] = cs[j], cs[i] i, j = i + 1, j + 1 return "".join(cs)
3,088
Make String Anti-palindrome
Hard
<p>We call a string <code>s</code> of <strong>even</strong> length <code>n</code> an <strong>anti-palindrome</strong> if for each index <code>0 &lt;= i &lt; n</code>, <code>s[i] != s[n - i - 1]</code>.</p> <p>Given a string <code>s</code>, your task is to make <code>s</code> an <strong>anti-palindrome</strong> by doing <strong>any</strong> number of operations (including zero).</p> <p>In one operation, you can select two characters from <code>s</code> and swap them.</p> <p>Return <em>the resulting string. If multiple strings meet the conditions, return the <span data-keyword="lexicographically-smaller-string">lexicographically smallest</span> one. If it can&#39;t be made into an anti-palindrome, return </em><code>&quot;-1&quot;</code><em>.</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">s = &quot;abca&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aabc&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aabc&quot;</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>&quot;abca&quot;</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aabb&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aabb&quot;</code> is an anti-palindrome string since <code>s[0] != s[3]</code> and <code>s[1] != s[2]</code>. Also, it is a rearrangement of <code>&quot;abba&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;cccd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;-1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>You can see that no matter how you rearrange the characters of <code>&quot;cccd&quot;</code>, either <code>s[0] == s[3]</code> or <code>s[1] == s[2]</code>. So it can not form an anti-palindrome string.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s.length % 2 == 0</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; String; Counting Sort; Sorting
TypeScript
function makeAntiPalindrome(s: string): string { const cs: string[] = s.split('').sort(); const n: number = cs.length; const m = n >> 1; if (cs[m] === cs[m - 1]) { let i = m; for (; i < n && cs[i] === cs[i - 1]; i++); for (let j = m; j < n && cs[j] === cs[n - j - 1]; ++i, ++j) { if (i >= n) { return '-1'; } [cs[j], cs[i]] = [cs[i], cs[j]]; } } return cs.join(''); }
3,089
Find Bursty Behavior
Medium
<p>Table: <code>Posts</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | post_id | int | | user_id | int | | post_date | date | +-------------+---------+ post_id is the primary key (column with unique values) for this table. Each row of this table contains post_id, user_id, and post_date. </pre> <p>Write a solution to find users who demonstrate <strong>bursty behavior</strong> in their posting patterns during February <code>2024</code>. <strong>Bursty behavior</strong> is defined as <strong>any</strong> period of <strong>7</strong> <strong>consecutive</strong> days where a user&#39;s posting frequency is <strong>at least twice</strong> to their <strong>average</strong> weekly posting frequency for February <code>2024</code>.</p> <p><strong>Note:</strong> Only include the dates from February <code>1</code> to February <code>28</code> in your analysis, which means you should count February as having exactly <code>4</code> weeks.</p> <p>Return <em>the result table orderd by </em><code>user_id</code><em> in </em><strong>ascending</strong><em> order.</em></p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Posts table:</p> <pre class="example-io"> +---------+---------+------------+ | post_id | user_id | post_date | +---------+---------+------------+ | 1 | 1 | 2024-02-27 | | 2 | 5 | 2024-02-06 | | 3 | 3 | 2024-02-25 | | 4 | 3 | 2024-02-14 | | 5 | 3 | 2024-02-06 | | 6 | 2 | 2024-02-25 | +---------+---------+------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+----------------+------------------+ | user_id | max_7day_posts | avg_weekly_posts | +---------+----------------+------------------+ | 1 | 1 | 0.2500 | | 2 | 1 | 0.2500 | | 5 | 1 | 0.2500 | +---------+----------------+------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>User 1:</strong> Made only 1 post in February, resulting in an average of 0.25 posts per week and a max of 1 post in any 7-day period.</li> <li><strong>User 2:</strong> Also made just 1 post, with the same average and max 7-day posting frequency as User 1.</li> <li><strong>User 5:</strong> Like Users 1 and 2, User 5 made only 1 post throughout February, leading to the same average and max 7-day posting metrics.</li> <li><strong>User 3:</strong> Although User 3 made more posts than the others (3 posts), they did not reach twice the average weekly posts in their consecutive 7-day window, so they are not listed in the output.</li> </ul> <p><b>Note:</b> Output table is ordered by user_id in ascending order.</p> </div>
Database
Python
import pandas as pd def find_bursty_behavior(posts: pd.DataFrame) -> pd.DataFrame: # Subquery P p1 = pd.merge(posts, posts, on="user_id", suffixes=("_1", "_2")) p1 = p1[ p1["post_date_2"].between( p1["post_date_1"], p1["post_date_1"] + pd.Timedelta(days=6) ) ] p1 = p1.groupby(["user_id", "post_id_1"]).size().reset_index(name="cnt") # Subquery T t = posts[ (posts["post_date"] >= "2024-02-01") & (posts["post_date"] <= "2024-02-28") ] t = t.groupby("user_id").size().div(4).reset_index(name="avg_weekly_posts") # Joining P and T merged_df = pd.merge(p1, t, on="user_id", how="inner") # Filtering filtered_df = merged_df[merged_df["cnt"] >= merged_df["avg_weekly_posts"] * 2] # Aggregating result_df = ( filtered_df.groupby("user_id") .agg({"cnt": "max", "avg_weekly_posts": "first"}) .reset_index() ) result_df.columns = ["user_id", "max_7day_posts", "avg_weekly_posts"] # Sorting result_df.sort_values(by="user_id", inplace=True) return result_df
3,089
Find Bursty Behavior
Medium
<p>Table: <code>Posts</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | post_id | int | | user_id | int | | post_date | date | +-------------+---------+ post_id is the primary key (column with unique values) for this table. Each row of this table contains post_id, user_id, and post_date. </pre> <p>Write a solution to find users who demonstrate <strong>bursty behavior</strong> in their posting patterns during February <code>2024</code>. <strong>Bursty behavior</strong> is defined as <strong>any</strong> period of <strong>7</strong> <strong>consecutive</strong> days where a user&#39;s posting frequency is <strong>at least twice</strong> to their <strong>average</strong> weekly posting frequency for February <code>2024</code>.</p> <p><strong>Note:</strong> Only include the dates from February <code>1</code> to February <code>28</code> in your analysis, which means you should count February as having exactly <code>4</code> weeks.</p> <p>Return <em>the result table orderd by </em><code>user_id</code><em> in </em><strong>ascending</strong><em> order.</em></p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Posts table:</p> <pre class="example-io"> +---------+---------+------------+ | post_id | user_id | post_date | +---------+---------+------------+ | 1 | 1 | 2024-02-27 | | 2 | 5 | 2024-02-06 | | 3 | 3 | 2024-02-25 | | 4 | 3 | 2024-02-14 | | 5 | 3 | 2024-02-06 | | 6 | 2 | 2024-02-25 | +---------+---------+------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+----------------+------------------+ | user_id | max_7day_posts | avg_weekly_posts | +---------+----------------+------------------+ | 1 | 1 | 0.2500 | | 2 | 1 | 0.2500 | | 5 | 1 | 0.2500 | +---------+----------------+------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>User 1:</strong> Made only 1 post in February, resulting in an average of 0.25 posts per week and a max of 1 post in any 7-day period.</li> <li><strong>User 2:</strong> Also made just 1 post, with the same average and max 7-day posting frequency as User 1.</li> <li><strong>User 5:</strong> Like Users 1 and 2, User 5 made only 1 post throughout February, leading to the same average and max 7-day posting metrics.</li> <li><strong>User 3:</strong> Although User 3 made more posts than the others (3 posts), they did not reach twice the average weekly posts in their consecutive 7-day window, so they are not listed in the output.</li> </ul> <p><b>Note:</b> Output table is ordered by user_id in ascending order.</p> </div>
Database
SQL
# Write your MySQL query statement below WITH P AS ( SELECT p1.user_id AS user_id, COUNT(1) AS cnt FROM Posts AS p1 JOIN Posts AS p2 ON p1.user_id = p2.user_id AND p2.post_date BETWEEN p1.post_date AND DATE_ADD(p1.post_date, INTERVAL 6 DAY) GROUP BY p1.user_id, p1.post_id ), T AS ( SELECT user_id, COUNT(1) / 4 AS avg_weekly_posts FROM Posts WHERE post_date BETWEEN '2024-02-01' AND '2024-02-28' GROUP BY 1 ) SELECT user_id, MAX(cnt) AS max_7day_posts, avg_weekly_posts FROM P JOIN T USING (user_id) GROUP BY 1 HAVING max_7day_posts >= avg_weekly_posts * 2 ORDER BY 1;
3,090
Maximum Length Substring With Two Occurrences
Easy
Given a string <code>s</code>, return the <strong>maximum</strong> length of a <span data-keyword="substring">substring</span>&nbsp;such that it contains <em>at most two occurrences</em> of each character. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;bcbbbcba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> The following substring has a length of 4 and contains at most two occurrences of each character: <code>&quot;bcbb<u>bcba</u>&quot;</code>.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> The following substring has a length of 2 and contains at most two occurrences of each character: <code>&quot;<u>aa</u>aa&quot;</code>.</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
C++
class Solution { public: int maximumLengthSubstring(string s) { int cnt[26]{}; int ans = 0; for (int i = 0, j = 0; j < s.length(); ++j) { int idx = s[j] - 'a'; ++cnt[idx]; while (cnt[idx] > 2) { --cnt[s[i++] - 'a']; } ans = max(ans, j - i + 1); } return ans; } };
3,090
Maximum Length Substring With Two Occurrences
Easy
Given a string <code>s</code>, return the <strong>maximum</strong> length of a <span data-keyword="substring">substring</span>&nbsp;such that it contains <em>at most two occurrences</em> of each character. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;bcbbbcba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> The following substring has a length of 4 and contains at most two occurrences of each character: <code>&quot;bcbb<u>bcba</u>&quot;</code>.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> The following substring has a length of 2 and contains at most two occurrences of each character: <code>&quot;<u>aa</u>aa&quot;</code>.</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Go
func maximumLengthSubstring(s string) (ans int) { cnt := [26]int{} i := 0 for j, c := range s { idx := c - 'a' cnt[idx]++ for cnt[idx] > 2 { cnt[s[i]-'a']-- i++ } ans = max(ans, j-i+1) } return }
3,090
Maximum Length Substring With Two Occurrences
Easy
Given a string <code>s</code>, return the <strong>maximum</strong> length of a <span data-keyword="substring">substring</span>&nbsp;such that it contains <em>at most two occurrences</em> of each character. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;bcbbbcba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> The following substring has a length of 4 and contains at most two occurrences of each character: <code>&quot;bcbb<u>bcba</u>&quot;</code>.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> The following substring has a length of 2 and contains at most two occurrences of each character: <code>&quot;<u>aa</u>aa&quot;</code>.</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Java
class Solution { public int maximumLengthSubstring(String s) { int[] cnt = new int[26]; int ans = 0; for (int i = 0, j = 0; j < s.length(); ++j) { int idx = s.charAt(j) - 'a'; ++cnt[idx]; while (cnt[idx] > 2) { --cnt[s.charAt(i++) - 'a']; } ans = Math.max(ans, j - i + 1); } return ans; } }
3,090
Maximum Length Substring With Two Occurrences
Easy
Given a string <code>s</code>, return the <strong>maximum</strong> length of a <span data-keyword="substring">substring</span>&nbsp;such that it contains <em>at most two occurrences</em> of each character. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;bcbbbcba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> The following substring has a length of 4 and contains at most two occurrences of each character: <code>&quot;bcbb<u>bcba</u>&quot;</code>.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> The following substring has a length of 2 and contains at most two occurrences of each character: <code>&quot;<u>aa</u>aa&quot;</code>.</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Python
class Solution: def maximumLengthSubstring(self, s: str) -> int: cnt = Counter() ans = i = 0 for j, c in enumerate(s): cnt[c] += 1 while cnt[c] > 2: cnt[s[i]] -= 1 i += 1 ans = max(ans, j - i + 1) return ans
3,090
Maximum Length Substring With Two Occurrences
Easy
Given a string <code>s</code>, return the <strong>maximum</strong> length of a <span data-keyword="substring">substring</span>&nbsp;such that it contains <em>at most two occurrences</em> of each character. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;bcbbbcba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> The following substring has a length of 4 and contains at most two occurrences of each character: <code>&quot;bcbb<u>bcba</u>&quot;</code>.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> The following substring has a length of 2 and contains at most two occurrences of each character: <code>&quot;<u>aa</u>aa&quot;</code>.</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
TypeScript
function maximumLengthSubstring(s: string): number { let ans = 0; const cnt: number[] = Array(26).fill(0); for (let i = 0, j = 0; j < s.length; ++j) { const idx = s[j].charCodeAt(0) - 'a'.charCodeAt(0); ++cnt[idx]; while (cnt[idx] > 2) { --cnt[s[i++].charCodeAt(0) - 'a'.charCodeAt(0)]; } ans = Math.max(ans, j - i + 1); } return ans; }
3,091
Apply Operations to Make Sum of Array Greater Than or Equal to k
Medium
<p>You are given a <strong>positive</strong> integer <code>k</code>. Initially, you have an array <code>nums = [1]</code>.</p> <p>You can perform <strong>any</strong> of the following operations on the array <strong>any</strong> number of times (<strong>possibly zero</strong>):</p> <ul> <li>Choose any element in the array and <strong>increase</strong> its value by <code>1</code>.</li> <li>Duplicate any element in the array and add it to the end of the array.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations required to make the <strong>sum</strong> of elements of the final array greater than or equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">k = 11</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can do the following operations on the array <code>nums = [1]</code>:</p> <ul> <li>Increase the element by <code>1</code> three times. The resulting array is <code>nums = [4]</code>.</li> <li>Duplicate the element two times. The resulting array is <code>nums = [4,4,4]</code>.</li> </ul> <p>The sum of the final array is <code>4 + 4 + 4 = 12</code> which is greater than or equal to <code>k = 11</code>.<br /> The total number of operations performed is <code>3 + 2 = 5</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The sum of the original array is already greater than or equal to <code>1</code>, so no operations are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Math; Enumeration
C++
class Solution { public: int minOperations(int k) { int ans = k; for (int a = 0; a < k; ++a) { int x = a + 1; int b = (k + x - 1) / x - 1; ans = min(ans, a + b); } return ans; } };
3,091
Apply Operations to Make Sum of Array Greater Than or Equal to k
Medium
<p>You are given a <strong>positive</strong> integer <code>k</code>. Initially, you have an array <code>nums = [1]</code>.</p> <p>You can perform <strong>any</strong> of the following operations on the array <strong>any</strong> number of times (<strong>possibly zero</strong>):</p> <ul> <li>Choose any element in the array and <strong>increase</strong> its value by <code>1</code>.</li> <li>Duplicate any element in the array and add it to the end of the array.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations required to make the <strong>sum</strong> of elements of the final array greater than or equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">k = 11</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can do the following operations on the array <code>nums = [1]</code>:</p> <ul> <li>Increase the element by <code>1</code> three times. The resulting array is <code>nums = [4]</code>.</li> <li>Duplicate the element two times. The resulting array is <code>nums = [4,4,4]</code>.</li> </ul> <p>The sum of the final array is <code>4 + 4 + 4 = 12</code> which is greater than or equal to <code>k = 11</code>.<br /> The total number of operations performed is <code>3 + 2 = 5</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The sum of the original array is already greater than or equal to <code>1</code>, so no operations are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Math; Enumeration
Go
func minOperations(k int) int { ans := k for a := 0; a < k; a++ { x := a + 1 b := (k+x-1)/x - 1 ans = min(ans, a+b) } return ans }