id
int64
1
3.71k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
3,565
Sequential Grid Path Cover
Medium
<p>You are given a 2D array <code>grid</code> of size <code>m x n</code>, and an integer <code>k</code>. There are <code>k</code> cells in <code>grid</code> containing the values from 1 to <code>k</code> <strong>exactly once</strong>, and the rest of the cells have a value 0.</p> <p>You can start at any cell, and move from a cell to its neighbors (up, down, left, or right). You must find a path in <code>grid</code> which:</p> <ul> <li>Visits each cell in <code>grid</code> <strong>exactly once</strong>.</li> <li>Visits the cells with values from 1 to <code>k</code> <strong>in order</strong>.</li> </ul> <p>Return a 2D array <code>result</code> of size <code>(m * n) x 2</code>, where <code>result[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the <code>i<sup>th</sup></code> cell visited in the path. If there are multiple such paths, you may return <strong>any</strong> one.</p> <p>If no such path exists, return an <strong>empty</strong> array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,0,0],[0,1,2]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[0,0],[1,0],[1,1],[1,2],[0,2],[0,1]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3565.Sequential%20Grid%20Path%20Cover/images/ezgifcom-animated-gif-maker1.gif" style="width: 200px; height: 160px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,4],[3,0,2]], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>There is no possible path that satisfies the conditions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == grid.length &lt;= 5</code></li> <li><code>1 &lt;= n == grid[i].length &lt;= 5</code></li> <li><code>1 &lt;= k &lt;= m * n</code></li> <li><code>0 &lt;= grid[i][j] &lt;= k</code></li> <li><code>grid</code> contains all integers between 1 and <code>k</code> <strong>exactly</strong> once.</li> </ul>
Recursion; Array; Matrix
Java
class Solution { private int m, n; private long st = 0; private List<List<Integer>> path = new ArrayList<>(); private final int[] dirs = {-1, 0, 1, 0, -1}; private int f(int i, int j) { return i * n + j; } private boolean dfs(int i, int j, int v, int[][] grid) { path.add(Arrays.asList(i, j)); if (path.size() == m * n) { return true; } st |= 1L << f(i, j); if (grid[i][j] == v) { v += 1; } for (int t = 0; t < 4; t++) { int a = dirs[t], b = dirs[t + 1]; int x = i + a, y = j + b; if (0 <= x && x < m && 0 <= y && y < n && (st & (1L << f(x, y))) == 0 && (grid[x][y] == 0 || grid[x][y] == v)) { if (dfs(x, y, v, grid)) { return true; } } } path.remove(path.size() - 1); st ^= 1L << f(i, j); return false; } public List<List<Integer>> findPath(int[][] grid, int k) { m = grid.length; n = grid[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 0 || grid[i][j] == 1) { if (dfs(i, j, 1, grid)) { return path; } path.clear(); st = 0; } } } return List.of(); } }
3,565
Sequential Grid Path Cover
Medium
<p>You are given a 2D array <code>grid</code> of size <code>m x n</code>, and an integer <code>k</code>. There are <code>k</code> cells in <code>grid</code> containing the values from 1 to <code>k</code> <strong>exactly once</strong>, and the rest of the cells have a value 0.</p> <p>You can start at any cell, and move from a cell to its neighbors (up, down, left, or right). You must find a path in <code>grid</code> which:</p> <ul> <li>Visits each cell in <code>grid</code> <strong>exactly once</strong>.</li> <li>Visits the cells with values from 1 to <code>k</code> <strong>in order</strong>.</li> </ul> <p>Return a 2D array <code>result</code> of size <code>(m * n) x 2</code>, where <code>result[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the <code>i<sup>th</sup></code> cell visited in the path. If there are multiple such paths, you may return <strong>any</strong> one.</p> <p>If no such path exists, return an <strong>empty</strong> array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,0,0],[0,1,2]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[0,0],[1,0],[1,1],[1,2],[0,2],[0,1]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3565.Sequential%20Grid%20Path%20Cover/images/ezgifcom-animated-gif-maker1.gif" style="width: 200px; height: 160px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,4],[3,0,2]], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>There is no possible path that satisfies the conditions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == grid.length &lt;= 5</code></li> <li><code>1 &lt;= n == grid[i].length &lt;= 5</code></li> <li><code>1 &lt;= k &lt;= m * n</code></li> <li><code>0 &lt;= grid[i][j] &lt;= k</code></li> <li><code>grid</code> contains all integers between 1 and <code>k</code> <strong>exactly</strong> once.</li> </ul>
Recursion; Array; Matrix
Python
class Solution: def findPath(self, grid: List[List[int]], k: int) -> List[List[int]]: def f(i: int, j: int) -> int: return i * n + j def dfs(i: int, j: int, v: int): nonlocal st path.append([i, j]) if len(path) == m * n: return True st |= 1 << f(i, j) if grid[i][j] == v: v += 1 for a, b in pairwise(dirs): x, y = i + a, j + b if ( 0 <= x < m and 0 <= y < n and (st & 1 << f(x, y)) == 0 and grid[x][y] in (0, v) ): if dfs(x, y, v): return True path.pop() st ^= 1 << f(i, j) return False m, n = len(grid), len(grid[0]) st = 0 path = [] dirs = (-1, 0, 1, 0, -1) for i in range(m): for j in range(n): if grid[i][j] in (0, 1): if dfs(i, j, 1): return path path.clear() st = 0 return []
3,565
Sequential Grid Path Cover
Medium
<p>You are given a 2D array <code>grid</code> of size <code>m x n</code>, and an integer <code>k</code>. There are <code>k</code> cells in <code>grid</code> containing the values from 1 to <code>k</code> <strong>exactly once</strong>, and the rest of the cells have a value 0.</p> <p>You can start at any cell, and move from a cell to its neighbors (up, down, left, or right). You must find a path in <code>grid</code> which:</p> <ul> <li>Visits each cell in <code>grid</code> <strong>exactly once</strong>.</li> <li>Visits the cells with values from 1 to <code>k</code> <strong>in order</strong>.</li> </ul> <p>Return a 2D array <code>result</code> of size <code>(m * n) x 2</code>, where <code>result[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the <code>i<sup>th</sup></code> cell visited in the path. If there are multiple such paths, you may return <strong>any</strong> one.</p> <p>If no such path exists, return an <strong>empty</strong> array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,0,0],[0,1,2]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[0,0],[1,0],[1,1],[1,2],[0,2],[0,1]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3565.Sequential%20Grid%20Path%20Cover/images/ezgifcom-animated-gif-maker1.gif" style="width: 200px; height: 160px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,0,4],[3,0,2]], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> <p><strong>Explanation:</strong></p> <p>There is no possible path that satisfies the conditions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == grid.length &lt;= 5</code></li> <li><code>1 &lt;= n == grid[i].length &lt;= 5</code></li> <li><code>1 &lt;= k &lt;= m * n</code></li> <li><code>0 &lt;= grid[i][j] &lt;= k</code></li> <li><code>grid</code> contains all integers between 1 and <code>k</code> <strong>exactly</strong> once.</li> </ul>
Recursion; Array; Matrix
TypeScript
function findPath(grid: number[][], k: number): number[][] { const m = grid.length; const n = grid[0].length; const dirs = [-1, 0, 1, 0, -1]; const path: number[][] = []; let st = 0; function f(i: number, j: number): number { return i * n + j; } function dfs(i: number, j: number, v: number): boolean { path.push([i, j]); if (path.length === m * n) { return true; } st |= 1 << f(i, j); if (grid[i][j] === v) { v += 1; } for (let d = 0; d < 4; d++) { const x = i + dirs[d]; const y = j + dirs[d + 1]; const pos = f(x, y); if ( x >= 0 && x < m && y >= 0 && y < n && (st & (1 << pos)) === 0 && (grid[x][y] === 0 || grid[x][y] === v) ) { if (dfs(x, y, v)) { return true; } } } path.pop(); st ^= 1 << f(i, j); return false; } for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (grid[i][j] === 0 || grid[i][j] === 1) { st = 0; path.length = 0; if (dfs(i, j, 1)) { return path; } } } } return []; }
3,566
Partition Array into Two Equal Product Subsets
Medium
<p>You are given an integer array <code>nums</code> containing <strong>distinct</strong> positive integers and an integer <code>target</code>.</p> <p>Determine if you can partition <code>nums</code> into two <strong>non-empty</strong> <strong>disjoint</strong> <strong>subsets</strong>, with each element belonging to <strong>exactly one</strong> subset, such that the product of the elements in each subset is equal to <code>target</code>.</p> <p>Return <code>true</code> if such a partition exists and <code>false</code> otherwise.</p> A <strong>subset</strong> of an array is a selection of elements of the array. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,6,8,4], target = 24</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong> The subsets <code>[3, 8]</code> and <code>[1, 6, 4]</code> each have a product of 24. Hence, the output is true.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,3,7], target = 15</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong> There is no way to partition <code>nums</code> into two non-empty disjoint subsets such that both subsets have a product of 15. Hence, the output is false.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 12</code></li> <li><code>1 &lt;= target &lt;= 10<sup>15</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li>All elements of <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Bit Manipulation; Recursion; Array; Enumeration
C++
class Solution { public: bool checkEqualPartitions(vector<int>& nums, long long target) { int n = nums.size(); for (int i = 0; i < 1 << n; ++i) { long long x = 1, y = 1; for (int j = 0; j < n; ++j) { if ((i >> j & 1) == 1) { x *= nums[j]; } else { y *= nums[j]; } if (x > target || y > target) { break; } } if (x == target && y == target) { return true; } } return false; } };
3,566
Partition Array into Two Equal Product Subsets
Medium
<p>You are given an integer array <code>nums</code> containing <strong>distinct</strong> positive integers and an integer <code>target</code>.</p> <p>Determine if you can partition <code>nums</code> into two <strong>non-empty</strong> <strong>disjoint</strong> <strong>subsets</strong>, with each element belonging to <strong>exactly one</strong> subset, such that the product of the elements in each subset is equal to <code>target</code>.</p> <p>Return <code>true</code> if such a partition exists and <code>false</code> otherwise.</p> A <strong>subset</strong> of an array is a selection of elements of the array. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,6,8,4], target = 24</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong> The subsets <code>[3, 8]</code> and <code>[1, 6, 4]</code> each have a product of 24. Hence, the output is true.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,3,7], target = 15</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong> There is no way to partition <code>nums</code> into two non-empty disjoint subsets such that both subsets have a product of 15. Hence, the output is false.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 12</code></li> <li><code>1 &lt;= target &lt;= 10<sup>15</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li>All elements of <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Bit Manipulation; Recursion; Array; Enumeration
Go
func checkEqualPartitions(nums []int, target int64) bool { n := len(nums) for i := 0; i < 1<<n; i++ { x, y := int64(1), int64(1) for j, v := range nums { if i>>j&1 == 1 { x *= int64(v) } else { y *= int64(v) } if x > target || y > target { break } } if x == target && y == target { return true } } return false }
3,566
Partition Array into Two Equal Product Subsets
Medium
<p>You are given an integer array <code>nums</code> containing <strong>distinct</strong> positive integers and an integer <code>target</code>.</p> <p>Determine if you can partition <code>nums</code> into two <strong>non-empty</strong> <strong>disjoint</strong> <strong>subsets</strong>, with each element belonging to <strong>exactly one</strong> subset, such that the product of the elements in each subset is equal to <code>target</code>.</p> <p>Return <code>true</code> if such a partition exists and <code>false</code> otherwise.</p> A <strong>subset</strong> of an array is a selection of elements of the array. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,6,8,4], target = 24</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong> The subsets <code>[3, 8]</code> and <code>[1, 6, 4]</code> each have a product of 24. Hence, the output is true.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,3,7], target = 15</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong> There is no way to partition <code>nums</code> into two non-empty disjoint subsets such that both subsets have a product of 15. Hence, the output is false.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 12</code></li> <li><code>1 &lt;= target &lt;= 10<sup>15</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li>All elements of <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Bit Manipulation; Recursion; Array; Enumeration
Java
class Solution { public boolean checkEqualPartitions(int[] nums, long target) { int n = nums.length; for (int i = 0; i < 1 << n; ++i) { long x = 1, y = 1; for (int j = 0; j < n; ++j) { if ((i >> j & 1) == 1) { x *= nums[j]; } else { y *= nums[j]; } } if (x == target && y == target) { return true; } } return false; } }
3,566
Partition Array into Two Equal Product Subsets
Medium
<p>You are given an integer array <code>nums</code> containing <strong>distinct</strong> positive integers and an integer <code>target</code>.</p> <p>Determine if you can partition <code>nums</code> into two <strong>non-empty</strong> <strong>disjoint</strong> <strong>subsets</strong>, with each element belonging to <strong>exactly one</strong> subset, such that the product of the elements in each subset is equal to <code>target</code>.</p> <p>Return <code>true</code> if such a partition exists and <code>false</code> otherwise.</p> A <strong>subset</strong> of an array is a selection of elements of the array. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,6,8,4], target = 24</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong> The subsets <code>[3, 8]</code> and <code>[1, 6, 4]</code> each have a product of 24. Hence, the output is true.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,3,7], target = 15</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong> There is no way to partition <code>nums</code> into two non-empty disjoint subsets such that both subsets have a product of 15. Hence, the output is false.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 12</code></li> <li><code>1 &lt;= target &lt;= 10<sup>15</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li>All elements of <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Bit Manipulation; Recursion; Array; Enumeration
Python
class Solution: def checkEqualPartitions(self, nums: List[int], target: int) -> bool: n = len(nums) for i in range(1 << n): x = y = 1 for j in range(n): if i >> j & 1: x *= nums[j] else: y *= nums[j] if x == target and y == target: return True return False
3,566
Partition Array into Two Equal Product Subsets
Medium
<p>You are given an integer array <code>nums</code> containing <strong>distinct</strong> positive integers and an integer <code>target</code>.</p> <p>Determine if you can partition <code>nums</code> into two <strong>non-empty</strong> <strong>disjoint</strong> <strong>subsets</strong>, with each element belonging to <strong>exactly one</strong> subset, such that the product of the elements in each subset is equal to <code>target</code>.</p> <p>Return <code>true</code> if such a partition exists and <code>false</code> otherwise.</p> A <strong>subset</strong> of an array is a selection of elements of the array. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,1,6,8,4], target = 24</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong> The subsets <code>[3, 8]</code> and <code>[1, 6, 4]</code> each have a product of 24. Hence, the output is true.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,3,7], target = 15</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong> There is no way to partition <code>nums</code> into two non-empty disjoint subsets such that both subsets have a product of 15. Hence, the output is false.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 12</code></li> <li><code>1 &lt;= target &lt;= 10<sup>15</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li>All elements of <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Bit Manipulation; Recursion; Array; Enumeration
TypeScript
function checkEqualPartitions(nums: number[], target: number): boolean { const n = nums.length; for (let i = 0; i < 1 << n; ++i) { let [x, y] = [1, 1]; for (let j = 0; j < n; ++j) { if (((i >> j) & 1) === 1) { x *= nums[j]; } else { y *= nums[j]; } if (x > target || y > target) { break; } } if (x === target && y === target) { return true; } } return false; }
3,567
Minimum Absolute Difference in Sliding Submatrix
Medium
<p>You are given an <code>m x n</code> integer matrix <code>grid</code> and an integer <code>k</code>.</p> <p>For every contiguous <code>k x k</code> <strong>submatrix</strong> of <code>grid</code>, compute the <strong>minimum absolute</strong> difference between any two <strong>distinct</strong> values within that <strong>submatrix</strong>.</p> <p>Return a 2D array <code>ans</code> of size <code>(m - k + 1) x (n - k + 1)</code>, where <code>ans[i][j]</code> is the minimum absolute difference in the submatrix whose top-left corner is <code>(i, j)</code> in <code>grid</code>.</p> <p><strong>Note</strong>: If all elements in the submatrix have the same value, the answer will be 0.</p> A submatrix <code>(x1, y1, x2, y2)</code> is a matrix that is formed by choosing all cells <code>matrix[x][y]</code> where <code>x1 &lt;= x &lt;= x2</code> and <code>y1 &lt;= y &lt;= y2</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,8],[3,-2]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[2]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There is only one possible <code>k x k</code> submatrix: <code><span class="example-io">[[1, 8], [3, -2]]</span></code><span class="example-io">.</span></li> <li>Distinct values in the submatrix are<span class="example-io"> <code>[1, 8, 3, -2]</code>.</span></li> <li>The minimum absolute difference in the submatrix is <code>|1 - 3| = 2</code>. Thus, the answer is <code>[[2]]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,-1]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[[0,0]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Both <code>k x k</code> submatrix has only one distinct element.</li> <li>Thus, the answer is <code>[[0, 0]]</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,-2,3],[2,3,5]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are two possible <code>k &times; k</code> submatrix: <ul> <li>Starting at <code>(0, 0)</code>: <code>[[1, -2], [2, 3]]</code>. <ul> <li>Distinct values in the submatrix are <code>[1, -2, 2, 3]</code>.</li> <li>The minimum absolute difference in the submatrix is <code>|1 - 2| = 1</code>.</li> </ul> </li> <li>Starting at <code>(0, 1)</code>: <code>[[-2, 3], [3, 5]]</code>. <ul> <li>Distinct values in the submatrix are <code>[-2, 3, 5]</code>.</li> <li>The minimum absolute difference in the submatrix is <code>|3 - 5| = 2</code>.</li> </ul> </li> </ul> </li> <li>Thus, the answer is <code>[[1, 2]]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == grid.length &lt;= 30</code></li> <li><code>1 &lt;= n == grid[i].length &lt;= 30</code></li> <li><code>-10<sup>5</sup> &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= min(m, n)</code></li> </ul>
Array; Matrix; Sorting
C++
class Solution { public: vector<vector<int>> minAbsDiff(vector<vector<int>>& grid, int k) { int m = grid.size(), n = grid[0].size(); vector<vector<int>> ans(m - k + 1, vector<int>(n - k + 1, 0)); for (int i = 0; i <= m - k; ++i) { for (int j = 0; j <= n - k; ++j) { vector<int> nums; for (int x = i; x < i + k; ++x) { for (int y = j; y < j + k; ++y) { nums.push_back(grid[x][y]); } } sort(nums.begin(), nums.end()); int d = INT_MAX; for (int t = 1; t < nums.size(); ++t) { if (nums[t] != nums[t - 1]) { d = min(d, abs(nums[t] - nums[t - 1])); } } ans[i][j] = (d == INT_MAX) ? 0 : d; } } return ans; } };
3,567
Minimum Absolute Difference in Sliding Submatrix
Medium
<p>You are given an <code>m x n</code> integer matrix <code>grid</code> and an integer <code>k</code>.</p> <p>For every contiguous <code>k x k</code> <strong>submatrix</strong> of <code>grid</code>, compute the <strong>minimum absolute</strong> difference between any two <strong>distinct</strong> values within that <strong>submatrix</strong>.</p> <p>Return a 2D array <code>ans</code> of size <code>(m - k + 1) x (n - k + 1)</code>, where <code>ans[i][j]</code> is the minimum absolute difference in the submatrix whose top-left corner is <code>(i, j)</code> in <code>grid</code>.</p> <p><strong>Note</strong>: If all elements in the submatrix have the same value, the answer will be 0.</p> A submatrix <code>(x1, y1, x2, y2)</code> is a matrix that is formed by choosing all cells <code>matrix[x][y]</code> where <code>x1 &lt;= x &lt;= x2</code> and <code>y1 &lt;= y &lt;= y2</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,8],[3,-2]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[2]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There is only one possible <code>k x k</code> submatrix: <code><span class="example-io">[[1, 8], [3, -2]]</span></code><span class="example-io">.</span></li> <li>Distinct values in the submatrix are<span class="example-io"> <code>[1, 8, 3, -2]</code>.</span></li> <li>The minimum absolute difference in the submatrix is <code>|1 - 3| = 2</code>. Thus, the answer is <code>[[2]]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,-1]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[[0,0]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Both <code>k x k</code> submatrix has only one distinct element.</li> <li>Thus, the answer is <code>[[0, 0]]</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,-2,3],[2,3,5]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are two possible <code>k &times; k</code> submatrix: <ul> <li>Starting at <code>(0, 0)</code>: <code>[[1, -2], [2, 3]]</code>. <ul> <li>Distinct values in the submatrix are <code>[1, -2, 2, 3]</code>.</li> <li>The minimum absolute difference in the submatrix is <code>|1 - 2| = 1</code>.</li> </ul> </li> <li>Starting at <code>(0, 1)</code>: <code>[[-2, 3], [3, 5]]</code>. <ul> <li>Distinct values in the submatrix are <code>[-2, 3, 5]</code>.</li> <li>The minimum absolute difference in the submatrix is <code>|3 - 5| = 2</code>.</li> </ul> </li> </ul> </li> <li>Thus, the answer is <code>[[1, 2]]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == grid.length &lt;= 30</code></li> <li><code>1 &lt;= n == grid[i].length &lt;= 30</code></li> <li><code>-10<sup>5</sup> &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= min(m, n)</code></li> </ul>
Array; Matrix; Sorting
Go
func minAbsDiff(grid [][]int, k int) [][]int { m, n := len(grid), len(grid[0]) ans := make([][]int, m-k+1) for i := range ans { ans[i] = make([]int, n-k+1) } for i := 0; i <= m-k; i++ { for j := 0; j <= n-k; j++ { var nums []int for x := i; x < i+k; x++ { for y := j; y < j+k; y++ { nums = append(nums, grid[x][y]) } } sort.Ints(nums) d := math.MaxInt for t := 1; t < len(nums); t++ { if nums[t] != nums[t-1] { diff := abs(nums[t] - nums[t-1]) if diff < d { d = diff } } } if d != math.MaxInt { ans[i][j] = d } } } return ans } func abs(x int) int { if x < 0 { return -x } return x }
3,567
Minimum Absolute Difference in Sliding Submatrix
Medium
<p>You are given an <code>m x n</code> integer matrix <code>grid</code> and an integer <code>k</code>.</p> <p>For every contiguous <code>k x k</code> <strong>submatrix</strong> of <code>grid</code>, compute the <strong>minimum absolute</strong> difference between any two <strong>distinct</strong> values within that <strong>submatrix</strong>.</p> <p>Return a 2D array <code>ans</code> of size <code>(m - k + 1) x (n - k + 1)</code>, where <code>ans[i][j]</code> is the minimum absolute difference in the submatrix whose top-left corner is <code>(i, j)</code> in <code>grid</code>.</p> <p><strong>Note</strong>: If all elements in the submatrix have the same value, the answer will be 0.</p> A submatrix <code>(x1, y1, x2, y2)</code> is a matrix that is formed by choosing all cells <code>matrix[x][y]</code> where <code>x1 &lt;= x &lt;= x2</code> and <code>y1 &lt;= y &lt;= y2</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,8],[3,-2]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[2]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There is only one possible <code>k x k</code> submatrix: <code><span class="example-io">[[1, 8], [3, -2]]</span></code><span class="example-io">.</span></li> <li>Distinct values in the submatrix are<span class="example-io"> <code>[1, 8, 3, -2]</code>.</span></li> <li>The minimum absolute difference in the submatrix is <code>|1 - 3| = 2</code>. Thus, the answer is <code>[[2]]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,-1]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[[0,0]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Both <code>k x k</code> submatrix has only one distinct element.</li> <li>Thus, the answer is <code>[[0, 0]]</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,-2,3],[2,3,5]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are two possible <code>k &times; k</code> submatrix: <ul> <li>Starting at <code>(0, 0)</code>: <code>[[1, -2], [2, 3]]</code>. <ul> <li>Distinct values in the submatrix are <code>[1, -2, 2, 3]</code>.</li> <li>The minimum absolute difference in the submatrix is <code>|1 - 2| = 1</code>.</li> </ul> </li> <li>Starting at <code>(0, 1)</code>: <code>[[-2, 3], [3, 5]]</code>. <ul> <li>Distinct values in the submatrix are <code>[-2, 3, 5]</code>.</li> <li>The minimum absolute difference in the submatrix is <code>|3 - 5| = 2</code>.</li> </ul> </li> </ul> </li> <li>Thus, the answer is <code>[[1, 2]]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == grid.length &lt;= 30</code></li> <li><code>1 &lt;= n == grid[i].length &lt;= 30</code></li> <li><code>-10<sup>5</sup> &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= min(m, n)</code></li> </ul>
Array; Matrix; Sorting
Java
class Solution { public int[][] minAbsDiff(int[][] grid, int k) { int m = grid.length, n = grid[0].length; int[][] ans = new int[m - k + 1][n - k + 1]; for (int i = 0; i <= m - k; i++) { for (int j = 0; j <= n - k; j++) { List<Integer> nums = new ArrayList<>(); for (int x = i; x < i + k; x++) { for (int y = j; y < j + k; y++) { nums.add(grid[x][y]); } } Collections.sort(nums); int d = Integer.MAX_VALUE; for (int t = 1; t < nums.size(); t++) { int a = nums.get(t - 1); int b = nums.get(t); if (a != b) { d = Math.min(d, Math.abs(a - b)); } } ans[i][j] = (d == Integer.MAX_VALUE) ? 0 : d; } } return ans; } }
3,567
Minimum Absolute Difference in Sliding Submatrix
Medium
<p>You are given an <code>m x n</code> integer matrix <code>grid</code> and an integer <code>k</code>.</p> <p>For every contiguous <code>k x k</code> <strong>submatrix</strong> of <code>grid</code>, compute the <strong>minimum absolute</strong> difference between any two <strong>distinct</strong> values within that <strong>submatrix</strong>.</p> <p>Return a 2D array <code>ans</code> of size <code>(m - k + 1) x (n - k + 1)</code>, where <code>ans[i][j]</code> is the minimum absolute difference in the submatrix whose top-left corner is <code>(i, j)</code> in <code>grid</code>.</p> <p><strong>Note</strong>: If all elements in the submatrix have the same value, the answer will be 0.</p> A submatrix <code>(x1, y1, x2, y2)</code> is a matrix that is formed by choosing all cells <code>matrix[x][y]</code> where <code>x1 &lt;= x &lt;= x2</code> and <code>y1 &lt;= y &lt;= y2</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,8],[3,-2]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[2]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There is only one possible <code>k x k</code> submatrix: <code><span class="example-io">[[1, 8], [3, -2]]</span></code><span class="example-io">.</span></li> <li>Distinct values in the submatrix are<span class="example-io"> <code>[1, 8, 3, -2]</code>.</span></li> <li>The minimum absolute difference in the submatrix is <code>|1 - 3| = 2</code>. Thus, the answer is <code>[[2]]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,-1]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[[0,0]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Both <code>k x k</code> submatrix has only one distinct element.</li> <li>Thus, the answer is <code>[[0, 0]]</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,-2,3],[2,3,5]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are two possible <code>k &times; k</code> submatrix: <ul> <li>Starting at <code>(0, 0)</code>: <code>[[1, -2], [2, 3]]</code>. <ul> <li>Distinct values in the submatrix are <code>[1, -2, 2, 3]</code>.</li> <li>The minimum absolute difference in the submatrix is <code>|1 - 2| = 1</code>.</li> </ul> </li> <li>Starting at <code>(0, 1)</code>: <code>[[-2, 3], [3, 5]]</code>. <ul> <li>Distinct values in the submatrix are <code>[-2, 3, 5]</code>.</li> <li>The minimum absolute difference in the submatrix is <code>|3 - 5| = 2</code>.</li> </ul> </li> </ul> </li> <li>Thus, the answer is <code>[[1, 2]]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == grid.length &lt;= 30</code></li> <li><code>1 &lt;= n == grid[i].length &lt;= 30</code></li> <li><code>-10<sup>5</sup> &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= min(m, n)</code></li> </ul>
Array; Matrix; Sorting
Python
class Solution: def minAbsDiff(self, grid: List[List[int]], k: int) -> List[List[int]]: m, n = len(grid), len(grid[0]) ans = [[0] * (n - k + 1) for _ in range(m - k + 1)] for i in range(m - k + 1): for j in range(n - k + 1): nums = [] for x in range(i, i + k): for y in range(j, j + k): nums.append(grid[x][y]) nums.sort() d = min((abs(a - b) for a, b in pairwise(nums) if a != b), default=0) ans[i][j] = d return ans
3,567
Minimum Absolute Difference in Sliding Submatrix
Medium
<p>You are given an <code>m x n</code> integer matrix <code>grid</code> and an integer <code>k</code>.</p> <p>For every contiguous <code>k x k</code> <strong>submatrix</strong> of <code>grid</code>, compute the <strong>minimum absolute</strong> difference between any two <strong>distinct</strong> values within that <strong>submatrix</strong>.</p> <p>Return a 2D array <code>ans</code> of size <code>(m - k + 1) x (n - k + 1)</code>, where <code>ans[i][j]</code> is the minimum absolute difference in the submatrix whose top-left corner is <code>(i, j)</code> in <code>grid</code>.</p> <p><strong>Note</strong>: If all elements in the submatrix have the same value, the answer will be 0.</p> A submatrix <code>(x1, y1, x2, y2)</code> is a matrix that is formed by choosing all cells <code>matrix[x][y]</code> where <code>x1 &lt;= x &lt;= x2</code> and <code>y1 &lt;= y &lt;= y2</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,8],[3,-2]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[2]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There is only one possible <code>k x k</code> submatrix: <code><span class="example-io">[[1, 8], [3, -2]]</span></code><span class="example-io">.</span></li> <li>Distinct values in the submatrix are<span class="example-io"> <code>[1, 8, 3, -2]</code>.</span></li> <li>The minimum absolute difference in the submatrix is <code>|1 - 3| = 2</code>. Thus, the answer is <code>[[2]]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,-1]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[[0,0]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Both <code>k x k</code> submatrix has only one distinct element.</li> <li>Thus, the answer is <code>[[0, 0]]</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,-2,3],[2,3,5]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[[1,2]]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are two possible <code>k &times; k</code> submatrix: <ul> <li>Starting at <code>(0, 0)</code>: <code>[[1, -2], [2, 3]]</code>. <ul> <li>Distinct values in the submatrix are <code>[1, -2, 2, 3]</code>.</li> <li>The minimum absolute difference in the submatrix is <code>|1 - 2| = 1</code>.</li> </ul> </li> <li>Starting at <code>(0, 1)</code>: <code>[[-2, 3], [3, 5]]</code>. <ul> <li>Distinct values in the submatrix are <code>[-2, 3, 5]</code>.</li> <li>The minimum absolute difference in the submatrix is <code>|3 - 5| = 2</code>.</li> </ul> </li> </ul> </li> <li>Thus, the answer is <code>[[1, 2]]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == grid.length &lt;= 30</code></li> <li><code>1 &lt;= n == grid[i].length &lt;= 30</code></li> <li><code>-10<sup>5</sup> &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= k &lt;= min(m, n)</code></li> </ul>
Array; Matrix; Sorting
TypeScript
function minAbsDiff(grid: number[][], k: number): number[][] { const m = grid.length; const n = grid[0].length; const ans: number[][] = Array.from({ length: m - k + 1 }, () => Array(n - k + 1).fill(0)); for (let i = 0; i <= m - k; i++) { for (let j = 0; j <= n - k; j++) { const nums: number[] = []; for (let x = i; x < i + k; x++) { for (let y = j; y < j + k; y++) { nums.push(grid[x][y]); } } nums.sort((a, b) => a - b); let d = Number.MAX_SAFE_INTEGER; for (let t = 1; t < nums.length; t++) { if (nums[t] !== nums[t - 1]) { d = Math.min(d, Math.abs(nums[t] - nums[t - 1])); } } ans[i][j] = d === Number.MAX_SAFE_INTEGER ? 0 : d; } } return ans; }
3,568
Minimum Moves to Clean the Classroom
Medium
<p data-end="324" data-start="147">You are given an <code>m x n</code> grid <code>classroom</code> where a student volunteer is tasked with cleaning up litter scattered around the room. Each cell in the grid is one of the following:</p> <ul> <li><code>&#39;S&#39;</code>: Starting position of the student</li> <li><code>&#39;L&#39;</code>: Litter that must be collected (once collected, the cell becomes empty)</li> <li><code>&#39;R&#39;</code>: Reset area that restores the student&#39;s energy to full capacity, regardless of their current energy level (can be used multiple times)</li> <li><code>&#39;X&#39;</code>: Obstacle the student cannot pass through</li> <li><code>&#39;.&#39;</code>: Empty space</li> </ul> <p>You are also given an integer <code>energy</code>, representing the student&#39;s maximum energy capacity. The student starts with this energy from the starting position <code>&#39;S&#39;</code>.</p> <p>Each move to an adjacent cell (up, down, left, or right) costs 1 unit of energy. If the energy reaches 0, the student can only continue if they are on a reset area <code>&#39;R&#39;</code>, which resets the energy to its <strong>maximum</strong> capacity <code>energy</code>.</p> <p>Return the <strong>minimum</strong> number of moves required to collect all litter items, or <code>-1</code> if it&#39;s impossible.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">classroom = [&quot;S.&quot;, &quot;XL&quot;], energy = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The student starts at cell <code data-end="262" data-start="254">(0, 0)</code> with 2 units of energy.</li> <li>Since cell <code>(1, 0)</code> contains an obstacle &#39;X&#39;, the student cannot move directly downward.</li> <li>A valid sequence of moves to collect all litter is as follows: <ul> <li>Move 1: From <code>(0, 0)</code> &rarr; <code>(0, 1)</code> with 1 unit of energy and 1 unit remaining.</li> <li>Move 2: From <code>(0, 1)</code> &rarr; <code>(1, 1)</code> to collect the litter <code>&#39;L&#39;</code>.</li> </ul> </li> <li>The student collects all the litter using 2 moves. Thus, the output is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">classroom = [&quot;LS&quot;, &quot;RL&quot;], energy = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The student starts at cell <code data-end="262" data-start="254">(0, 1)</code> with 4 units of energy.</li> <li>A valid sequence of moves to collect all litter is as follows: <ul> <li>Move 1: From <code>(0, 1)</code> &rarr; <code>(0, 0)</code> to collect the first litter <code>&#39;L&#39;</code> with 1 unit of energy used and 3 units remaining.</li> <li>Move 2: From <code>(0, 0)</code> &rarr; <code>(1, 0)</code> to <code>&#39;R&#39;</code> to reset and restore energy back to 4.</li> <li>Move 3: From <code>(1, 0)</code> &rarr; <code>(1, 1)</code> to collect the second litter <code data-end="1068" data-start="1063">&#39;L&#39;</code>.</li> </ul> </li> <li>The student collects all the litter using 3 moves. Thus, the output is 3.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">classroom = [&quot;L.S&quot;, &quot;RXL&quot;], energy = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>No valid path collects all <code>&#39;L&#39;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == classroom.length &lt;= 20</code></li> <li><code>1 &lt;= n == classroom[i].length &lt;= 20</code></li> <li><code>classroom[i][j]</code> is one of <code>&#39;S&#39;</code>, <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code>, <code>&#39;X&#39;</code>, or <code>&#39;.&#39;</code></li> <li><code>1 &lt;= energy &lt;= 50</code></li> <li>There is exactly <strong>one</strong> <code>&#39;S&#39;</code> in the grid.</li> <li>There are <strong>at most</strong> 10 <code>&#39;L&#39;</code> cells in the grid.</li> </ul>
Bit Manipulation; Breadth-First Search; Array; Hash Table; Matrix
C++
class Solution { public: int minMoves(vector<string>& classroom, int energy) { int m = classroom.size(), n = classroom[0].size(); vector<vector<int>> d(m, vector<int>(n, 0)); int x = 0, y = 0, cnt = 0; for (int i = 0; i < m; ++i) { string& row = classroom[i]; for (int j = 0; j < n; ++j) { char c = row[j]; if (c == 'S') { x = i; y = j; } else if (c == 'L') { d[i][j] = cnt; cnt++; } } } if (cnt == 0) { return 0; } vector<vector<vector<vector<bool>>>> vis(m, vector<vector<vector<bool>>>(n, vector<vector<bool>>(energy + 1, vector<bool>(1 << cnt, false)))); queue<tuple<int, int, int, int>> q; q.emplace(x, y, energy, (1 << cnt) - 1); vis[x][y][energy][(1 << cnt) - 1] = true; vector<int> dirs = {-1, 0, 1, 0, -1}; int ans = 0; while (!q.empty()) { int sz = q.size(); while (sz--) { auto [i, j, cur_energy, mask] = q.front(); q.pop(); if (mask == 0) { return ans; } if (cur_energy <= 0) { continue; } for (int k = 0; k < 4; ++k) { int nx = i + dirs[k], ny = j + dirs[k + 1]; if (nx >= 0 && nx < m && ny >= 0 && ny < n && classroom[nx][ny] != 'X') { int nxt_energy = classroom[nx][ny] == 'R' ? energy : cur_energy - 1; int nxt_mask = mask; if (classroom[nx][ny] == 'L') { nxt_mask &= ~(1 << d[nx][ny]); } if (!vis[nx][ny][nxt_energy][nxt_mask]) { vis[nx][ny][nxt_energy][nxt_mask] = true; q.emplace(nx, ny, nxt_energy, nxt_mask); } } } } ans++; } return -1; } };
3,568
Minimum Moves to Clean the Classroom
Medium
<p data-end="324" data-start="147">You are given an <code>m x n</code> grid <code>classroom</code> where a student volunteer is tasked with cleaning up litter scattered around the room. Each cell in the grid is one of the following:</p> <ul> <li><code>&#39;S&#39;</code>: Starting position of the student</li> <li><code>&#39;L&#39;</code>: Litter that must be collected (once collected, the cell becomes empty)</li> <li><code>&#39;R&#39;</code>: Reset area that restores the student&#39;s energy to full capacity, regardless of their current energy level (can be used multiple times)</li> <li><code>&#39;X&#39;</code>: Obstacle the student cannot pass through</li> <li><code>&#39;.&#39;</code>: Empty space</li> </ul> <p>You are also given an integer <code>energy</code>, representing the student&#39;s maximum energy capacity. The student starts with this energy from the starting position <code>&#39;S&#39;</code>.</p> <p>Each move to an adjacent cell (up, down, left, or right) costs 1 unit of energy. If the energy reaches 0, the student can only continue if they are on a reset area <code>&#39;R&#39;</code>, which resets the energy to its <strong>maximum</strong> capacity <code>energy</code>.</p> <p>Return the <strong>minimum</strong> number of moves required to collect all litter items, or <code>-1</code> if it&#39;s impossible.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">classroom = [&quot;S.&quot;, &quot;XL&quot;], energy = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The student starts at cell <code data-end="262" data-start="254">(0, 0)</code> with 2 units of energy.</li> <li>Since cell <code>(1, 0)</code> contains an obstacle &#39;X&#39;, the student cannot move directly downward.</li> <li>A valid sequence of moves to collect all litter is as follows: <ul> <li>Move 1: From <code>(0, 0)</code> &rarr; <code>(0, 1)</code> with 1 unit of energy and 1 unit remaining.</li> <li>Move 2: From <code>(0, 1)</code> &rarr; <code>(1, 1)</code> to collect the litter <code>&#39;L&#39;</code>.</li> </ul> </li> <li>The student collects all the litter using 2 moves. Thus, the output is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">classroom = [&quot;LS&quot;, &quot;RL&quot;], energy = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The student starts at cell <code data-end="262" data-start="254">(0, 1)</code> with 4 units of energy.</li> <li>A valid sequence of moves to collect all litter is as follows: <ul> <li>Move 1: From <code>(0, 1)</code> &rarr; <code>(0, 0)</code> to collect the first litter <code>&#39;L&#39;</code> with 1 unit of energy used and 3 units remaining.</li> <li>Move 2: From <code>(0, 0)</code> &rarr; <code>(1, 0)</code> to <code>&#39;R&#39;</code> to reset and restore energy back to 4.</li> <li>Move 3: From <code>(1, 0)</code> &rarr; <code>(1, 1)</code> to collect the second litter <code data-end="1068" data-start="1063">&#39;L&#39;</code>.</li> </ul> </li> <li>The student collects all the litter using 3 moves. Thus, the output is 3.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">classroom = [&quot;L.S&quot;, &quot;RXL&quot;], energy = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>No valid path collects all <code>&#39;L&#39;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == classroom.length &lt;= 20</code></li> <li><code>1 &lt;= n == classroom[i].length &lt;= 20</code></li> <li><code>classroom[i][j]</code> is one of <code>&#39;S&#39;</code>, <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code>, <code>&#39;X&#39;</code>, or <code>&#39;.&#39;</code></li> <li><code>1 &lt;= energy &lt;= 50</code></li> <li>There is exactly <strong>one</strong> <code>&#39;S&#39;</code> in the grid.</li> <li>There are <strong>at most</strong> 10 <code>&#39;L&#39;</code> cells in the grid.</li> </ul>
Bit Manipulation; Breadth-First Search; Array; Hash Table; Matrix
Go
func minMoves(classroom []string, energy int) int { m, n := len(classroom), len(classroom[0]) d := make([][]int, m) for i := range d { d[i] = make([]int, n) } x, y, cnt := 0, 0, 0 for i := 0; i < m; i++ { row := classroom[i] for j := 0; j < n; j++ { c := row[j] if c == 'S' { x, y = i, j } else if c == 'L' { d[i][j] = cnt cnt++ } } } if cnt == 0 { return 0 } vis := make([][][][]bool, m) for i := range vis { vis[i] = make([][][]bool, n) for j := range vis[i] { vis[i][j] = make([][]bool, energy+1) for e := range vis[i][j] { vis[i][j][e] = make([]bool, 1<<cnt) } } } type state struct { i, j, curEnergy, mask int } q := []state{{x, y, energy, (1 << cnt) - 1}} vis[x][y][energy][(1<<cnt)-1] = true dirs := []int{-1, 0, 1, 0, -1} ans := 0 for len(q) > 0 { t := q q = []state{} for _, s := range t { i, j, curEnergy, mask := s.i, s.j, s.curEnergy, s.mask if mask == 0 { return ans } if curEnergy <= 0 { continue } for k := 0; k < 4; k++ { nx, ny := i+dirs[k], j+dirs[k+1] if nx >= 0 && nx < m && ny >= 0 && ny < n && classroom[nx][ny] != 'X' { var nxtEnergy int if classroom[nx][ny] == 'R' { nxtEnergy = energy } else { nxtEnergy = curEnergy - 1 } nxtMask := mask if classroom[nx][ny] == 'L' { nxtMask &= ^(1 << d[nx][ny]) } if !vis[nx][ny][nxtEnergy][nxtMask] { vis[nx][ny][nxtEnergy][nxtMask] = true q = append(q, state{nx, ny, nxtEnergy, nxtMask}) } } } } ans++ } return -1 }
3,568
Minimum Moves to Clean the Classroom
Medium
<p data-end="324" data-start="147">You are given an <code>m x n</code> grid <code>classroom</code> where a student volunteer is tasked with cleaning up litter scattered around the room. Each cell in the grid is one of the following:</p> <ul> <li><code>&#39;S&#39;</code>: Starting position of the student</li> <li><code>&#39;L&#39;</code>: Litter that must be collected (once collected, the cell becomes empty)</li> <li><code>&#39;R&#39;</code>: Reset area that restores the student&#39;s energy to full capacity, regardless of their current energy level (can be used multiple times)</li> <li><code>&#39;X&#39;</code>: Obstacle the student cannot pass through</li> <li><code>&#39;.&#39;</code>: Empty space</li> </ul> <p>You are also given an integer <code>energy</code>, representing the student&#39;s maximum energy capacity. The student starts with this energy from the starting position <code>&#39;S&#39;</code>.</p> <p>Each move to an adjacent cell (up, down, left, or right) costs 1 unit of energy. If the energy reaches 0, the student can only continue if they are on a reset area <code>&#39;R&#39;</code>, which resets the energy to its <strong>maximum</strong> capacity <code>energy</code>.</p> <p>Return the <strong>minimum</strong> number of moves required to collect all litter items, or <code>-1</code> if it&#39;s impossible.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">classroom = [&quot;S.&quot;, &quot;XL&quot;], energy = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The student starts at cell <code data-end="262" data-start="254">(0, 0)</code> with 2 units of energy.</li> <li>Since cell <code>(1, 0)</code> contains an obstacle &#39;X&#39;, the student cannot move directly downward.</li> <li>A valid sequence of moves to collect all litter is as follows: <ul> <li>Move 1: From <code>(0, 0)</code> &rarr; <code>(0, 1)</code> with 1 unit of energy and 1 unit remaining.</li> <li>Move 2: From <code>(0, 1)</code> &rarr; <code>(1, 1)</code> to collect the litter <code>&#39;L&#39;</code>.</li> </ul> </li> <li>The student collects all the litter using 2 moves. Thus, the output is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">classroom = [&quot;LS&quot;, &quot;RL&quot;], energy = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The student starts at cell <code data-end="262" data-start="254">(0, 1)</code> with 4 units of energy.</li> <li>A valid sequence of moves to collect all litter is as follows: <ul> <li>Move 1: From <code>(0, 1)</code> &rarr; <code>(0, 0)</code> to collect the first litter <code>&#39;L&#39;</code> with 1 unit of energy used and 3 units remaining.</li> <li>Move 2: From <code>(0, 0)</code> &rarr; <code>(1, 0)</code> to <code>&#39;R&#39;</code> to reset and restore energy back to 4.</li> <li>Move 3: From <code>(1, 0)</code> &rarr; <code>(1, 1)</code> to collect the second litter <code data-end="1068" data-start="1063">&#39;L&#39;</code>.</li> </ul> </li> <li>The student collects all the litter using 3 moves. Thus, the output is 3.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">classroom = [&quot;L.S&quot;, &quot;RXL&quot;], energy = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>No valid path collects all <code>&#39;L&#39;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == classroom.length &lt;= 20</code></li> <li><code>1 &lt;= n == classroom[i].length &lt;= 20</code></li> <li><code>classroom[i][j]</code> is one of <code>&#39;S&#39;</code>, <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code>, <code>&#39;X&#39;</code>, or <code>&#39;.&#39;</code></li> <li><code>1 &lt;= energy &lt;= 50</code></li> <li>There is exactly <strong>one</strong> <code>&#39;S&#39;</code> in the grid.</li> <li>There are <strong>at most</strong> 10 <code>&#39;L&#39;</code> cells in the grid.</li> </ul>
Bit Manipulation; Breadth-First Search; Array; Hash Table; Matrix
Java
class Solution { public int minMoves(String[] classroom, int energy) { int m = classroom.length, n = classroom[0].length(); int[][] d = new int[m][n]; int x = 0, y = 0, cnt = 0; for (int i = 0; i < m; i++) { String row = classroom[i]; for (int j = 0; j < n; j++) { char c = row.charAt(j); if (c == 'S') { x = i; y = j; } else if (c == 'L') { d[i][j] = cnt; cnt++; } } } if (cnt == 0) { return 0; } boolean[][][][] vis = new boolean[m][n][energy + 1][1 << cnt]; List<int[]> q = new ArrayList<>(); q.add(new int[] {x, y, energy, (1 << cnt) - 1}); vis[x][y][energy][(1 << cnt) - 1] = true; int[] dirs = {-1, 0, 1, 0, -1}; int ans = 0; while (!q.isEmpty()) { List<int[]> t = q; q = new ArrayList<>(); for (int[] state : t) { int i = state[0], j = state[1], curEnergy = state[2], mask = state[3]; if (mask == 0) { return ans; } if (curEnergy <= 0) { continue; } for (int k = 0; k < 4; k++) { int nx = i + dirs[k], ny = j + dirs[k + 1]; if (nx >= 0 && nx < m && ny >= 0 && ny < n && classroom[nx].charAt(ny) != 'X') { int nxtEnergy = classroom[nx].charAt(ny) == 'R' ? energy : curEnergy - 1; int nxtMask = mask; if (classroom[nx].charAt(ny) == 'L') { nxtMask &= ~(1 << d[nx][ny]); } if (!vis[nx][ny][nxtEnergy][nxtMask]) { vis[nx][ny][nxtEnergy][nxtMask] = true; q.add(new int[] {nx, ny, nxtEnergy, nxtMask}); } } } } ans++; } return -1; } }
3,568
Minimum Moves to Clean the Classroom
Medium
<p data-end="324" data-start="147">You are given an <code>m x n</code> grid <code>classroom</code> where a student volunteer is tasked with cleaning up litter scattered around the room. Each cell in the grid is one of the following:</p> <ul> <li><code>&#39;S&#39;</code>: Starting position of the student</li> <li><code>&#39;L&#39;</code>: Litter that must be collected (once collected, the cell becomes empty)</li> <li><code>&#39;R&#39;</code>: Reset area that restores the student&#39;s energy to full capacity, regardless of their current energy level (can be used multiple times)</li> <li><code>&#39;X&#39;</code>: Obstacle the student cannot pass through</li> <li><code>&#39;.&#39;</code>: Empty space</li> </ul> <p>You are also given an integer <code>energy</code>, representing the student&#39;s maximum energy capacity. The student starts with this energy from the starting position <code>&#39;S&#39;</code>.</p> <p>Each move to an adjacent cell (up, down, left, or right) costs 1 unit of energy. If the energy reaches 0, the student can only continue if they are on a reset area <code>&#39;R&#39;</code>, which resets the energy to its <strong>maximum</strong> capacity <code>energy</code>.</p> <p>Return the <strong>minimum</strong> number of moves required to collect all litter items, or <code>-1</code> if it&#39;s impossible.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">classroom = [&quot;S.&quot;, &quot;XL&quot;], energy = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The student starts at cell <code data-end="262" data-start="254">(0, 0)</code> with 2 units of energy.</li> <li>Since cell <code>(1, 0)</code> contains an obstacle &#39;X&#39;, the student cannot move directly downward.</li> <li>A valid sequence of moves to collect all litter is as follows: <ul> <li>Move 1: From <code>(0, 0)</code> &rarr; <code>(0, 1)</code> with 1 unit of energy and 1 unit remaining.</li> <li>Move 2: From <code>(0, 1)</code> &rarr; <code>(1, 1)</code> to collect the litter <code>&#39;L&#39;</code>.</li> </ul> </li> <li>The student collects all the litter using 2 moves. Thus, the output is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">classroom = [&quot;LS&quot;, &quot;RL&quot;], energy = 4</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The student starts at cell <code data-end="262" data-start="254">(0, 1)</code> with 4 units of energy.</li> <li>A valid sequence of moves to collect all litter is as follows: <ul> <li>Move 1: From <code>(0, 1)</code> &rarr; <code>(0, 0)</code> to collect the first litter <code>&#39;L&#39;</code> with 1 unit of energy used and 3 units remaining.</li> <li>Move 2: From <code>(0, 0)</code> &rarr; <code>(1, 0)</code> to <code>&#39;R&#39;</code> to reset and restore energy back to 4.</li> <li>Move 3: From <code>(1, 0)</code> &rarr; <code>(1, 1)</code> to collect the second litter <code data-end="1068" data-start="1063">&#39;L&#39;</code>.</li> </ul> </li> <li>The student collects all the litter using 3 moves. Thus, the output is 3.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">classroom = [&quot;L.S&quot;, &quot;RXL&quot;], energy = 3</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>No valid path collects all <code>&#39;L&#39;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == classroom.length &lt;= 20</code></li> <li><code>1 &lt;= n == classroom[i].length &lt;= 20</code></li> <li><code>classroom[i][j]</code> is one of <code>&#39;S&#39;</code>, <code>&#39;L&#39;</code>, <code>&#39;R&#39;</code>, <code>&#39;X&#39;</code>, or <code>&#39;.&#39;</code></li> <li><code>1 &lt;= energy &lt;= 50</code></li> <li>There is exactly <strong>one</strong> <code>&#39;S&#39;</code> in the grid.</li> <li>There are <strong>at most</strong> 10 <code>&#39;L&#39;</code> cells in the grid.</li> </ul>
Bit Manipulation; Breadth-First Search; Array; Hash Table; Matrix
Python
class Solution: def minMoves(self, classroom: List[str], energy: int) -> int: m, n = len(classroom), len(classroom[0]) d = [[0] * n for _ in range(m)] x = y = cnt = 0 for i, row in enumerate(classroom): for j, c in enumerate(row): if c == "S": x, y = i, j elif c == "L": d[i][j] = cnt cnt += 1 if cnt == 0: return 0 vis = [ [[[False] * (1 << cnt) for _ in range(energy + 1)] for _ in range(n)] for _ in range(m) ] q = [(x, y, energy, (1 << cnt) - 1)] vis[x][y][energy][(1 << cnt) - 1] = True dirs = (-1, 0, 1, 0, -1) ans = 0 while q: t = q q = [] for i, j, cur_energy, mask in t: if mask == 0: return ans if cur_energy <= 0: continue for k in range(4): x, y = i + dirs[k], j + dirs[k + 1] if 0 <= x < m and 0 <= y < n and classroom[x][y] != "X": nxt_energy = ( energy if classroom[x][y] == "R" else cur_energy - 1 ) nxt_mask = mask if classroom[x][y] == "L": nxt_mask &= ~(1 << d[x][y]) if not vis[x][y][nxt_energy][nxt_mask]: vis[x][y][nxt_energy][nxt_mask] = True q.append((x, y, nxt_energy, nxt_mask)) ans += 1 return -1
3,570
Find Books with No Available Copies
Easy
<p>Table: <code>library_books</code></p> <pre> +------------------+---------+ | Column Name | Type | +------------------+---------+ | book_id | int | | title | varchar | | author | varchar | | genre | varchar | | publication_year | int | | total_copies | int | +------------------+---------+ book_id is the unique identifier for this table. Each row contains information about a book in the library, including the total number of copies owned by the library. </pre> <p>Table: <code>borrowing_records</code></p> <pre> +---------------+---------+ | Column Name | Type | +---------------+---------+ | record_id | int | | book_id | int | | borrower_name | varchar | | borrow_date | date | | return_date | date | +---------------+---------+ record_id is the unique identifier for this table. Each row represents a borrowing transaction and return_date is NULL if the book is currently borrowed and hasn&#39;t been returned yet. </pre> <p>Write a solution to find <strong>all books</strong> that are <strong>currently borrowed (not returned)</strong> and have <strong>zero copies available</strong> in the library.</p> <ul> <li>A book is considered <strong>currently borrowed</strong> if there exists a<strong> </strong>borrowing record with a <strong>NULL</strong> <code>return_date</code></li> </ul> <p>Return <em>the result table ordered by current borrowers in <strong>descending</strong> order, then by book title in <strong>ascending</strong> order.</em></p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>library_books table:</p> <pre class="example-io"> +---------+------------------------+------------------+----------+------------------+--------------+ | book_id | title | author | genre | publication_year | total_copies | +---------+------------------------+------------------+----------+------------------+--------------+ | 1 | The Great Gatsby | F. Scott | Fiction | 1925 | 3 | | 2 | To Kill a Mockingbird | Harper Lee | Fiction | 1960 | 3 | | 3 | 1984 | George Orwell | Dystopian| 1949 | 1 | | 4 | Pride and Prejudice | Jane Austen | Romance | 1813 | 2 | | 5 | The Catcher in the Rye | J.D. Salinger | Fiction | 1951 | 1 | | 6 | Brave New World | Aldous Huxley | Dystopian| 1932 | 4 | +---------+------------------------+------------------+----------+------------------+--------------+ </pre> <p>borrowing_records table:</p> <pre class="example-io"> +-----------+---------+---------------+-------------+-------------+ | record_id | book_id | borrower_name | borrow_date | return_date | +-----------+---------+---------------+-------------+-------------+ | 1 | 1 | Alice Smith | 2024-01-15 | NULL | | 2 | 1 | Bob Johnson | 2024-01-20 | NULL | | 3 | 2 | Carol White | 2024-01-10 | 2024-01-25 | | 4 | 3 | David Brown | 2024-02-01 | NULL | | 5 | 4 | Emma Wilson | 2024-01-05 | NULL | | 6 | 5 | Frank Davis | 2024-01-18 | 2024-02-10 | | 7 | 1 | Grace Miller | 2024-02-05 | NULL | | 8 | 6 | Henry Taylor | 2024-01-12 | NULL | | 9 | 2 | Ivan Clark | 2024-02-12 | NULL | | 10 | 2 | Jane Adams | 2024-02-15 | NULL | +-----------+---------+---------------+-------------+-------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+------------------+---------------+-----------+------------------+-------------------+ | book_id | title | author | genre | publication_year | current_borrowers | +---------+------------------+---------------+-----------+------------------+-------------------+ | 1 | The Great Gatsby | F. Scott | Fiction | 1925 | 3 | | 3 | 1984 | George Orwell | Dystopian | 1949 | 1 | +---------+------------------+---------------+-----------+------------------+-------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>The Great Gatsby (book_id = 1):</strong> <ul> <li>Total copies: 3</li> <li>Currently borrowed by Alice Smith, Bob Johnson, and Grace Miller (3 borrowers)</li> <li>Available copies: 3 - 3 = 0</li> <li>Included because available_copies = 0</li> </ul> </li> <li><strong>1984 (book_id = 3):</strong> <ul> <li>Total copies: 1</li> <li>Currently borrowed by David Brown (1 borrower)</li> <li>Available copies: 1 - 1 = 0</li> <li>Included because available_copies = 0</li> </ul> </li> <li><strong>Books not included:</strong> <ul> <li>To Kill a Mockingbird (book_id = 2): Total copies = 3, current borrowers = 2, available = 1</li> <li>Pride and Prejudice (book_id = 4): Total copies = 2, current borrowers = 1, available = 1</li> <li>The Catcher in the Rye (book_id = 5): Total copies = 1, current borrowers = 0, available = 1</li> <li>Brave New World (book_id = 6): Total copies = 4, current borrowers = 1, available = 3</li> </ul> </li> <li><strong>Result ordering:</strong> <ul> <li>The Great Gatsby appears first with 3 current borrowers</li> <li>1984 appears second with 1 current borrower</li> </ul> </li> </ul> <p>Output table is ordered by current_borrowers in descending order, then by book_title in ascending order.</p> </div>
Database
Python
import pandas as pd def find_books_with_no_available_copies( library_books: pd.DataFrame, borrowing_records: pd.DataFrame ) -> pd.DataFrame: current_borrowers = ( borrowing_records[borrowing_records["return_date"].isna()] .groupby("book_id") .size() .rename("current_borrowers") .reset_index() ) merged = library_books.merge(current_borrowers, on="book_id", how="inner") fully_borrowed = merged[merged["current_borrowers"] == merged["total_copies"]] fully_borrowed = fully_borrowed.sort_values( by=["current_borrowers", "title"], ascending=[False, True] ) cols = [ "book_id", "title", "author", "genre", "publication_year", "current_borrowers", ] return fully_borrowed[cols].reset_index(drop=True)
3,570
Find Books with No Available Copies
Easy
<p>Table: <code>library_books</code></p> <pre> +------------------+---------+ | Column Name | Type | +------------------+---------+ | book_id | int | | title | varchar | | author | varchar | | genre | varchar | | publication_year | int | | total_copies | int | +------------------+---------+ book_id is the unique identifier for this table. Each row contains information about a book in the library, including the total number of copies owned by the library. </pre> <p>Table: <code>borrowing_records</code></p> <pre> +---------------+---------+ | Column Name | Type | +---------------+---------+ | record_id | int | | book_id | int | | borrower_name | varchar | | borrow_date | date | | return_date | date | +---------------+---------+ record_id is the unique identifier for this table. Each row represents a borrowing transaction and return_date is NULL if the book is currently borrowed and hasn&#39;t been returned yet. </pre> <p>Write a solution to find <strong>all books</strong> that are <strong>currently borrowed (not returned)</strong> and have <strong>zero copies available</strong> in the library.</p> <ul> <li>A book is considered <strong>currently borrowed</strong> if there exists a<strong> </strong>borrowing record with a <strong>NULL</strong> <code>return_date</code></li> </ul> <p>Return <em>the result table ordered by current borrowers in <strong>descending</strong> order, then by book title in <strong>ascending</strong> order.</em></p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>library_books table:</p> <pre class="example-io"> +---------+------------------------+------------------+----------+------------------+--------------+ | book_id | title | author | genre | publication_year | total_copies | +---------+------------------------+------------------+----------+------------------+--------------+ | 1 | The Great Gatsby | F. Scott | Fiction | 1925 | 3 | | 2 | To Kill a Mockingbird | Harper Lee | Fiction | 1960 | 3 | | 3 | 1984 | George Orwell | Dystopian| 1949 | 1 | | 4 | Pride and Prejudice | Jane Austen | Romance | 1813 | 2 | | 5 | The Catcher in the Rye | J.D. Salinger | Fiction | 1951 | 1 | | 6 | Brave New World | Aldous Huxley | Dystopian| 1932 | 4 | +---------+------------------------+------------------+----------+------------------+--------------+ </pre> <p>borrowing_records table:</p> <pre class="example-io"> +-----------+---------+---------------+-------------+-------------+ | record_id | book_id | borrower_name | borrow_date | return_date | +-----------+---------+---------------+-------------+-------------+ | 1 | 1 | Alice Smith | 2024-01-15 | NULL | | 2 | 1 | Bob Johnson | 2024-01-20 | NULL | | 3 | 2 | Carol White | 2024-01-10 | 2024-01-25 | | 4 | 3 | David Brown | 2024-02-01 | NULL | | 5 | 4 | Emma Wilson | 2024-01-05 | NULL | | 6 | 5 | Frank Davis | 2024-01-18 | 2024-02-10 | | 7 | 1 | Grace Miller | 2024-02-05 | NULL | | 8 | 6 | Henry Taylor | 2024-01-12 | NULL | | 9 | 2 | Ivan Clark | 2024-02-12 | NULL | | 10 | 2 | Jane Adams | 2024-02-15 | NULL | +-----------+---------+---------------+-------------+-------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+------------------+---------------+-----------+------------------+-------------------+ | book_id | title | author | genre | publication_year | current_borrowers | +---------+------------------+---------------+-----------+------------------+-------------------+ | 1 | The Great Gatsby | F. Scott | Fiction | 1925 | 3 | | 3 | 1984 | George Orwell | Dystopian | 1949 | 1 | +---------+------------------+---------------+-----------+------------------+-------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>The Great Gatsby (book_id = 1):</strong> <ul> <li>Total copies: 3</li> <li>Currently borrowed by Alice Smith, Bob Johnson, and Grace Miller (3 borrowers)</li> <li>Available copies: 3 - 3 = 0</li> <li>Included because available_copies = 0</li> </ul> </li> <li><strong>1984 (book_id = 3):</strong> <ul> <li>Total copies: 1</li> <li>Currently borrowed by David Brown (1 borrower)</li> <li>Available copies: 1 - 1 = 0</li> <li>Included because available_copies = 0</li> </ul> </li> <li><strong>Books not included:</strong> <ul> <li>To Kill a Mockingbird (book_id = 2): Total copies = 3, current borrowers = 2, available = 1</li> <li>Pride and Prejudice (book_id = 4): Total copies = 2, current borrowers = 1, available = 1</li> <li>The Catcher in the Rye (book_id = 5): Total copies = 1, current borrowers = 0, available = 1</li> <li>Brave New World (book_id = 6): Total copies = 4, current borrowers = 1, available = 3</li> </ul> </li> <li><strong>Result ordering:</strong> <ul> <li>The Great Gatsby appears first with 3 current borrowers</li> <li>1984 appears second with 1 current borrower</li> </ul> </li> </ul> <p>Output table is ordered by current_borrowers in descending order, then by book_title in ascending order.</p> </div>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT book_id, COUNT(1) current_borrowers FROM borrowing_records WHERE return_date IS NULL GROUP BY 1 ) SELECT book_id, title, author, genre, publication_year, current_borrowers FROM library_books JOIN T USING (book_id) WHERE current_borrowers = total_copies ORDER BY 6 DESC, 2;
3,571
Find the Shortest Superstring II
Easy
<p>You are given <strong>two</strong> strings, <code>s1</code> and <code>s2</code>. Return the <strong>shortest</strong> <em>possible</em> string that contains both <code>s1</code> and <code>s2</code> as substrings. If there are multiple valid answers, return <em>any </em>one of them.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s1 = &quot;aba&quot;, s2 = &quot;bab&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abab&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;abab&quot;</code> is the shortest string that contains both <code>&quot;aba&quot;</code> and <code>&quot;bab&quot;</code> as substrings.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s1 = &quot;aa&quot;, s2 = &quot;aaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaa&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aa&quot;</code> is already contained within <code>&quot;aaa&quot;</code>, so the shortest superstring is <code>&quot;aaa&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="23" data-start="2"><code>1 &lt;= s1.length &lt;= 100</code></li> <li data-end="47" data-start="26"><code>1 &lt;= s2.length &lt;= 100</code></li> <li data-end="102" data-is-last-node="" data-start="50"><code>s1</code> and <code>s2</code> consist of lowercase English letters only.</li> </ul>
String
C++
class Solution { public: string shortestSuperstring(string s1, string s2) { int m = s1.size(), n = s2.size(); if (m > n) { return shortestSuperstring(s2, s1); } if (s2.find(s1) != string::npos) { return s2; } for (int i = 0; i < m; ++i) { if (s2.find(s1.substr(i)) == 0) { return s1.substr(0, i) + s2; } if (s2.rfind(s1.substr(0, m - i)) == s2.size() - (m - i)) { return s2 + s1.substr(m - i); } } return s1 + s2; } };
3,571
Find the Shortest Superstring II
Easy
<p>You are given <strong>two</strong> strings, <code>s1</code> and <code>s2</code>. Return the <strong>shortest</strong> <em>possible</em> string that contains both <code>s1</code> and <code>s2</code> as substrings. If there are multiple valid answers, return <em>any </em>one of them.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s1 = &quot;aba&quot;, s2 = &quot;bab&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abab&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;abab&quot;</code> is the shortest string that contains both <code>&quot;aba&quot;</code> and <code>&quot;bab&quot;</code> as substrings.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s1 = &quot;aa&quot;, s2 = &quot;aaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaa&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aa&quot;</code> is already contained within <code>&quot;aaa&quot;</code>, so the shortest superstring is <code>&quot;aaa&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="23" data-start="2"><code>1 &lt;= s1.length &lt;= 100</code></li> <li data-end="47" data-start="26"><code>1 &lt;= s2.length &lt;= 100</code></li> <li data-end="102" data-is-last-node="" data-start="50"><code>s1</code> and <code>s2</code> consist of lowercase English letters only.</li> </ul>
String
Go
func shortestSuperstring(s1 string, s2 string) string { m, n := len(s1), len(s2) if m > n { return shortestSuperstring(s2, s1) } if strings.Contains(s2, s1) { return s2 } for i := 0; i < m; i++ { if strings.HasPrefix(s2, s1[i:]) { return s1[:i] + s2 } if strings.HasSuffix(s2, s1[:m-i]) { return s2 + s1[m-i:] } } return s1 + s2 }
3,571
Find the Shortest Superstring II
Easy
<p>You are given <strong>two</strong> strings, <code>s1</code> and <code>s2</code>. Return the <strong>shortest</strong> <em>possible</em> string that contains both <code>s1</code> and <code>s2</code> as substrings. If there are multiple valid answers, return <em>any </em>one of them.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s1 = &quot;aba&quot;, s2 = &quot;bab&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abab&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;abab&quot;</code> is the shortest string that contains both <code>&quot;aba&quot;</code> and <code>&quot;bab&quot;</code> as substrings.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s1 = &quot;aa&quot;, s2 = &quot;aaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaa&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aa&quot;</code> is already contained within <code>&quot;aaa&quot;</code>, so the shortest superstring is <code>&quot;aaa&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="23" data-start="2"><code>1 &lt;= s1.length &lt;= 100</code></li> <li data-end="47" data-start="26"><code>1 &lt;= s2.length &lt;= 100</code></li> <li data-end="102" data-is-last-node="" data-start="50"><code>s1</code> and <code>s2</code> consist of lowercase English letters only.</li> </ul>
String
Java
class Solution { public String shortestSuperstring(String s1, String s2) { int m = s1.length(), n = s2.length(); if (m > n) { return shortestSuperstring(s2, s1); } if (s2.contains(s1)) { return s2; } for (int i = 0; i < m; i++) { if (s2.startsWith(s1.substring(i))) { return s1.substring(0, i) + s2; } if (s2.endsWith(s1.substring(0, m - i))) { return s2 + s1.substring(m - i); } } return s1 + s2; } }
3,571
Find the Shortest Superstring II
Easy
<p>You are given <strong>two</strong> strings, <code>s1</code> and <code>s2</code>. Return the <strong>shortest</strong> <em>possible</em> string that contains both <code>s1</code> and <code>s2</code> as substrings. If there are multiple valid answers, return <em>any </em>one of them.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s1 = &quot;aba&quot;, s2 = &quot;bab&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abab&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;abab&quot;</code> is the shortest string that contains both <code>&quot;aba&quot;</code> and <code>&quot;bab&quot;</code> as substrings.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s1 = &quot;aa&quot;, s2 = &quot;aaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaa&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aa&quot;</code> is already contained within <code>&quot;aaa&quot;</code>, so the shortest superstring is <code>&quot;aaa&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="23" data-start="2"><code>1 &lt;= s1.length &lt;= 100</code></li> <li data-end="47" data-start="26"><code>1 &lt;= s2.length &lt;= 100</code></li> <li data-end="102" data-is-last-node="" data-start="50"><code>s1</code> and <code>s2</code> consist of lowercase English letters only.</li> </ul>
String
Python
class Solution: def shortestSuperstring(self, s1: str, s2: str) -> str: m, n = len(s1), len(s2) if m > n: return self.shortestSuperstring(s2, s1) if s1 in s2: return s2 for i in range(m): if s2.startswith(s1[i:]): return s1[:i] + s2 if s2.endswith(s1[: m - i]): return s2 + s1[m - i :] return s1 + s2
3,571
Find the Shortest Superstring II
Easy
<p>You are given <strong>two</strong> strings, <code>s1</code> and <code>s2</code>. Return the <strong>shortest</strong> <em>possible</em> string that contains both <code>s1</code> and <code>s2</code> as substrings. If there are multiple valid answers, return <em>any </em>one of them.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s1 = &quot;aba&quot;, s2 = &quot;bab&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abab&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;abab&quot;</code> is the shortest string that contains both <code>&quot;aba&quot;</code> and <code>&quot;bab&quot;</code> as substrings.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s1 = &quot;aa&quot;, s2 = &quot;aaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaa&quot;</span></p> <p><strong>Explanation:</strong></p> <p><code>&quot;aa&quot;</code> is already contained within <code>&quot;aaa&quot;</code>, so the shortest superstring is <code>&quot;aaa&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="23" data-start="2"><code>1 &lt;= s1.length &lt;= 100</code></li> <li data-end="47" data-start="26"><code>1 &lt;= s2.length &lt;= 100</code></li> <li data-end="102" data-is-last-node="" data-start="50"><code>s1</code> and <code>s2</code> consist of lowercase English letters only.</li> </ul>
String
TypeScript
function shortestSuperstring(s1: string, s2: string): string { const m = s1.length, n = s2.length; if (m > n) { return shortestSuperstring(s2, s1); } if (s2.includes(s1)) { return s2; } for (let i = 0; i < m; i++) { if (s2.startsWith(s1.slice(i))) { return s1.slice(0, i) + s2; } if (s2.endsWith(s1.slice(0, m - i))) { return s2 + s1.slice(m - i); } } return s1 + s2; }
3,572
Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
Medium
<p>You are given two integer arrays <code>x</code> and <code>y</code>, each of length <code>n</code>. You must choose three <strong>distinct</strong> indices <code>i</code>, <code>j</code>, and <code>k</code> such that:</p> <ul> <li><code>x[i] != x[j]</code></li> <li><code>x[j] != x[k]</code></li> <li><code>x[k] != x[i]</code></li> </ul> <p>Your goal is to <strong>maximize</strong> the value of <code>y[i] + y[j] + y[k]</code> under these conditions. Return the <strong>maximum</strong> possible sum that can be obtained by choosing such a triplet of indices.</p> <p>If no such triplet exists, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = [1,2,1,3,2], y = [5,3,4,6,2]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Choose <code>i = 0</code> (<code>x[i] = 1</code>, <code>y[i] = 5</code>), <code>j = 1</code> (<code>x[j] = 2</code>, <code>y[j] = 3</code>), <code>k = 3</code> (<code>x[k] = 3</code>, <code>y[k] = 6</code>).</li> <li>All three values chosen from <code>x</code> are distinct. <code>5 + 3 + 6 = 14</code> is the maximum we can obtain. Hence, the output is 14.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = [1,2,1,2], y = [4,5,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are only two distinct values in <code>x</code>. Hence, the output is -1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == x.length == y.length</code></li> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= x[i], y[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Hash Table; Sorting; Heap (Priority Queue)
C++
class Solution { public: int maxSumDistinctTriplet(vector<int>& x, vector<int>& y) { int n = x.size(); vector<array<int, 2>> arr(n); for (int i = 0; i < n; ++i) { arr[i] = {x[i], y[i]}; } ranges::sort(arr, [](auto& a, auto& b) { return b[1] < a[1]; }); int ans = 0; unordered_set<int> vis; for (int i = 0; i < n; ++i) { int a = arr[i][0], b = arr[i][1]; if (vis.insert(a).second) { ans += b; if (vis.size() == 3) { return ans; } } } return -1; } };
3,572
Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
Medium
<p>You are given two integer arrays <code>x</code> and <code>y</code>, each of length <code>n</code>. You must choose three <strong>distinct</strong> indices <code>i</code>, <code>j</code>, and <code>k</code> such that:</p> <ul> <li><code>x[i] != x[j]</code></li> <li><code>x[j] != x[k]</code></li> <li><code>x[k] != x[i]</code></li> </ul> <p>Your goal is to <strong>maximize</strong> the value of <code>y[i] + y[j] + y[k]</code> under these conditions. Return the <strong>maximum</strong> possible sum that can be obtained by choosing such a triplet of indices.</p> <p>If no such triplet exists, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = [1,2,1,3,2], y = [5,3,4,6,2]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Choose <code>i = 0</code> (<code>x[i] = 1</code>, <code>y[i] = 5</code>), <code>j = 1</code> (<code>x[j] = 2</code>, <code>y[j] = 3</code>), <code>k = 3</code> (<code>x[k] = 3</code>, <code>y[k] = 6</code>).</li> <li>All three values chosen from <code>x</code> are distinct. <code>5 + 3 + 6 = 14</code> is the maximum we can obtain. Hence, the output is 14.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = [1,2,1,2], y = [4,5,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are only two distinct values in <code>x</code>. Hence, the output is -1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == x.length == y.length</code></li> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= x[i], y[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Hash Table; Sorting; Heap (Priority Queue)
Go
func maxSumDistinctTriplet(x []int, y []int) int { n := len(x) arr := make([][2]int, n) for i := 0; i < n; i++ { arr[i] = [2]int{x[i], y[i]} } sort.Slice(arr, func(i, j int) bool { return arr[i][1] > arr[j][1] }) ans := 0 vis := make(map[int]bool) for i := 0; i < n; i++ { a, b := arr[i][0], arr[i][1] if !vis[a] { vis[a] = true ans += b if len(vis) == 3 { return ans } } } return -1 }
3,572
Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
Medium
<p>You are given two integer arrays <code>x</code> and <code>y</code>, each of length <code>n</code>. You must choose three <strong>distinct</strong> indices <code>i</code>, <code>j</code>, and <code>k</code> such that:</p> <ul> <li><code>x[i] != x[j]</code></li> <li><code>x[j] != x[k]</code></li> <li><code>x[k] != x[i]</code></li> </ul> <p>Your goal is to <strong>maximize</strong> the value of <code>y[i] + y[j] + y[k]</code> under these conditions. Return the <strong>maximum</strong> possible sum that can be obtained by choosing such a triplet of indices.</p> <p>If no such triplet exists, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = [1,2,1,3,2], y = [5,3,4,6,2]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Choose <code>i = 0</code> (<code>x[i] = 1</code>, <code>y[i] = 5</code>), <code>j = 1</code> (<code>x[j] = 2</code>, <code>y[j] = 3</code>), <code>k = 3</code> (<code>x[k] = 3</code>, <code>y[k] = 6</code>).</li> <li>All three values chosen from <code>x</code> are distinct. <code>5 + 3 + 6 = 14</code> is the maximum we can obtain. Hence, the output is 14.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = [1,2,1,2], y = [4,5,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are only two distinct values in <code>x</code>. Hence, the output is -1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == x.length == y.length</code></li> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= x[i], y[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Hash Table; Sorting; Heap (Priority Queue)
Java
class Solution { public int maxSumDistinctTriplet(int[] x, int[] y) { int n = x.length; int[][] arr = new int[n][0]; for (int i = 0; i < n; i++) { arr[i] = new int[] {x[i], y[i]}; } Arrays.sort(arr, (a, b) -> b[1] - a[1]); int ans = 0; Set<Integer> vis = new HashSet<>(); for (int i = 0; i < n; ++i) { int a = arr[i][0], b = arr[i][1]; if (vis.add(a)) { ans += b; if (vis.size() == 3) { return ans; } } } return -1; } }
3,572
Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
Medium
<p>You are given two integer arrays <code>x</code> and <code>y</code>, each of length <code>n</code>. You must choose three <strong>distinct</strong> indices <code>i</code>, <code>j</code>, and <code>k</code> such that:</p> <ul> <li><code>x[i] != x[j]</code></li> <li><code>x[j] != x[k]</code></li> <li><code>x[k] != x[i]</code></li> </ul> <p>Your goal is to <strong>maximize</strong> the value of <code>y[i] + y[j] + y[k]</code> under these conditions. Return the <strong>maximum</strong> possible sum that can be obtained by choosing such a triplet of indices.</p> <p>If no such triplet exists, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = [1,2,1,3,2], y = [5,3,4,6,2]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Choose <code>i = 0</code> (<code>x[i] = 1</code>, <code>y[i] = 5</code>), <code>j = 1</code> (<code>x[j] = 2</code>, <code>y[j] = 3</code>), <code>k = 3</code> (<code>x[k] = 3</code>, <code>y[k] = 6</code>).</li> <li>All three values chosen from <code>x</code> are distinct. <code>5 + 3 + 6 = 14</code> is the maximum we can obtain. Hence, the output is 14.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = [1,2,1,2], y = [4,5,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are only two distinct values in <code>x</code>. Hence, the output is -1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == x.length == y.length</code></li> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= x[i], y[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Hash Table; Sorting; Heap (Priority Queue)
Python
class Solution: def maxSumDistinctTriplet(self, x: List[int], y: List[int]) -> int: arr = [(a, b) for a, b in zip(x, y)] arr.sort(key=lambda x: -x[1]) vis = set() ans = 0 for a, b in arr: if a in vis: continue vis.add(a) ans += b if len(vis) == 3: return ans return -1
3,572
Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
Medium
<p>You are given two integer arrays <code>x</code> and <code>y</code>, each of length <code>n</code>. You must choose three <strong>distinct</strong> indices <code>i</code>, <code>j</code>, and <code>k</code> such that:</p> <ul> <li><code>x[i] != x[j]</code></li> <li><code>x[j] != x[k]</code></li> <li><code>x[k] != x[i]</code></li> </ul> <p>Your goal is to <strong>maximize</strong> the value of <code>y[i] + y[j] + y[k]</code> under these conditions. Return the <strong>maximum</strong> possible sum that can be obtained by choosing such a triplet of indices.</p> <p>If no such triplet exists, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = [1,2,1,3,2], y = [5,3,4,6,2]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Choose <code>i = 0</code> (<code>x[i] = 1</code>, <code>y[i] = 5</code>), <code>j = 1</code> (<code>x[j] = 2</code>, <code>y[j] = 3</code>), <code>k = 3</code> (<code>x[k] = 3</code>, <code>y[k] = 6</code>).</li> <li>All three values chosen from <code>x</code> are distinct. <code>5 + 3 + 6 = 14</code> is the maximum we can obtain. Hence, the output is 14.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = [1,2,1,2], y = [4,5,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are only two distinct values in <code>x</code>. Hence, the output is -1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == x.length == y.length</code></li> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= x[i], y[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Hash Table; Sorting; Heap (Priority Queue)
Rust
impl Solution { pub fn max_sum_distinct_triplet(x: Vec<i32>, y: Vec<i32>) -> i32 { let n = x.len(); let mut arr: Vec<(i32, i32)> = (0..n).map(|i| (x[i], y[i])).collect(); arr.sort_by(|a, b| b.1.cmp(&a.1)); let mut vis = std::collections::HashSet::new(); let mut ans = 0; for (a, b) in arr { if vis.insert(a) { ans += b; if vis.len() == 3 { return ans; } } } -1 } }
3,572
Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
Medium
<p>You are given two integer arrays <code>x</code> and <code>y</code>, each of length <code>n</code>. You must choose three <strong>distinct</strong> indices <code>i</code>, <code>j</code>, and <code>k</code> such that:</p> <ul> <li><code>x[i] != x[j]</code></li> <li><code>x[j] != x[k]</code></li> <li><code>x[k] != x[i]</code></li> </ul> <p>Your goal is to <strong>maximize</strong> the value of <code>y[i] + y[j] + y[k]</code> under these conditions. Return the <strong>maximum</strong> possible sum that can be obtained by choosing such a triplet of indices.</p> <p>If no such triplet exists, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = [1,2,1,3,2], y = [5,3,4,6,2]</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Choose <code>i = 0</code> (<code>x[i] = 1</code>, <code>y[i] = 5</code>), <code>j = 1</code> (<code>x[j] = 2</code>, <code>y[j] = 3</code>), <code>k = 3</code> (<code>x[k] = 3</code>, <code>y[k] = 6</code>).</li> <li>All three values chosen from <code>x</code> are distinct. <code>5 + 3 + 6 = 14</code> is the maximum we can obtain. Hence, the output is 14.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = [1,2,1,2], y = [4,5,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are only two distinct values in <code>x</code>. Hence, the output is -1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == x.length == y.length</code></li> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= x[i], y[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Hash Table; Sorting; Heap (Priority Queue)
TypeScript
function maxSumDistinctTriplet(x: number[], y: number[]): number { const n = x.length; const arr: [number, number][] = []; for (let i = 0; i < n; i++) { arr.push([x[i], y[i]]); } arr.sort((a, b) => b[1] - a[1]); const vis = new Set<number>(); let ans = 0; for (let i = 0; i < n; i++) { const [a, b] = arr[i]; if (!vis.has(a)) { vis.add(a); ans += b; if (vis.size === 3) { return ans; } } } return -1; }
3,573
Best Time to Buy and Sell Stock V
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a stock in dollars on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p> <p>You are allowed to make at most <code>k</code> transactions, where each transaction can be either of the following:</p> <ul> <li> <p><strong>Normal transaction</strong>: Buy on day <code>i</code>, then sell on a later day <code>j</code> where <code>i &lt; j</code>. You profit <code>prices[j] - prices[i]</code>.</p> </li> <li> <p><strong>Short selling transaction</strong>: Sell on day <code>i</code>, then buy back on a later day <code>j</code> where <code>i &lt; j</code>. You profit <code>prices[i] - prices[j]</code>.</p> </li> </ul> <p><strong>Note</strong> that you must complete each transaction before starting another. Additionally, you can't buy or sell on the same day you are selling or buying back as part of a previous transaction.</p> <p>Return the <strong>maximum</strong> total profit you can earn by making <strong>at most</strong> <code>k</code> transactions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [1,7,9,8,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> We can make $14 of profit through 2 transactions: <ul> <li>A normal transaction: buy the stock on day 0 for $1 then sell it on day 2 for $9.</li> <li>A short selling transaction: sell the stock on day 3 for $8 then buy back on day 4 for $2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [12,16,19,19,8,1,19,13,9], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">36</span></p> <p><strong>Explanation:</strong></p> We can make $36 of profit through 3 transactions: <ul> <li>A normal transaction: buy the stock on day 0 for $12 then sell it on day 2 for $19.</li> <li>A short selling transaction: sell the stock on day 3 for $19 then buy back on day 4 for $8.</li> <li>A normal transaction: buy the stock on day 5 for $1 then sell it on day 6 for $19.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= prices.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= prices.length / 2</code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: long long maximumProfit(vector<int>& prices, int k) { int n = prices.size(); long long f[n][k + 1][3]; memset(f, 0, sizeof(f)); for (int j = 1; j <= k; ++j) { f[0][j][1] = -prices[0]; f[0][j][2] = prices[0]; } for (int i = 1; i < n; ++i) { for (int j = 1; j <= k; ++j) { f[i][j][0] = max({f[i - 1][j][0], f[i - 1][j][1] + prices[i], f[i - 1][j][2] - prices[i]}); f[i][j][1] = max(f[i - 1][j][1], f[i - 1][j - 1][0] - prices[i]); f[i][j][2] = max(f[i - 1][j][2], f[i - 1][j - 1][0] + prices[i]); } } return f[n - 1][k][0]; } };
3,573
Best Time to Buy and Sell Stock V
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a stock in dollars on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p> <p>You are allowed to make at most <code>k</code> transactions, where each transaction can be either of the following:</p> <ul> <li> <p><strong>Normal transaction</strong>: Buy on day <code>i</code>, then sell on a later day <code>j</code> where <code>i &lt; j</code>. You profit <code>prices[j] - prices[i]</code>.</p> </li> <li> <p><strong>Short selling transaction</strong>: Sell on day <code>i</code>, then buy back on a later day <code>j</code> where <code>i &lt; j</code>. You profit <code>prices[i] - prices[j]</code>.</p> </li> </ul> <p><strong>Note</strong> that you must complete each transaction before starting another. Additionally, you can't buy or sell on the same day you are selling or buying back as part of a previous transaction.</p> <p>Return the <strong>maximum</strong> total profit you can earn by making <strong>at most</strong> <code>k</code> transactions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [1,7,9,8,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> We can make $14 of profit through 2 transactions: <ul> <li>A normal transaction: buy the stock on day 0 for $1 then sell it on day 2 for $9.</li> <li>A short selling transaction: sell the stock on day 3 for $8 then buy back on day 4 for $2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [12,16,19,19,8,1,19,13,9], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">36</span></p> <p><strong>Explanation:</strong></p> We can make $36 of profit through 3 transactions: <ul> <li>A normal transaction: buy the stock on day 0 for $12 then sell it on day 2 for $19.</li> <li>A short selling transaction: sell the stock on day 3 for $19 then buy back on day 4 for $8.</li> <li>A normal transaction: buy the stock on day 5 for $1 then sell it on day 6 for $19.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= prices.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= prices.length / 2</code></li> </ul>
Array; Dynamic Programming
Go
func maximumProfit(prices []int, k int) int64 { n := len(prices) f := make([][][3]int, n) for i := range f { f[i] = make([][3]int, k+1) } for j := 1; j <= k; j++ { f[0][j][1] = -prices[0] f[0][j][2] = prices[0] } for i := 1; i < n; i++ { for j := 1; j <= k; j++ { f[i][j][0] = max(f[i-1][j][0], f[i-1][j][1]+prices[i], f[i-1][j][2]-prices[i]) f[i][j][1] = max(f[i-1][j][1], f[i-1][j-1][0]-prices[i]) f[i][j][2] = max(f[i-1][j][2], f[i-1][j-1][0]+prices[i]) } } return int64(f[n-1][k][0]) }
3,573
Best Time to Buy and Sell Stock V
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a stock in dollars on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p> <p>You are allowed to make at most <code>k</code> transactions, where each transaction can be either of the following:</p> <ul> <li> <p><strong>Normal transaction</strong>: Buy on day <code>i</code>, then sell on a later day <code>j</code> where <code>i &lt; j</code>. You profit <code>prices[j] - prices[i]</code>.</p> </li> <li> <p><strong>Short selling transaction</strong>: Sell on day <code>i</code>, then buy back on a later day <code>j</code> where <code>i &lt; j</code>. You profit <code>prices[i] - prices[j]</code>.</p> </li> </ul> <p><strong>Note</strong> that you must complete each transaction before starting another. Additionally, you can't buy or sell on the same day you are selling or buying back as part of a previous transaction.</p> <p>Return the <strong>maximum</strong> total profit you can earn by making <strong>at most</strong> <code>k</code> transactions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [1,7,9,8,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> We can make $14 of profit through 2 transactions: <ul> <li>A normal transaction: buy the stock on day 0 for $1 then sell it on day 2 for $9.</li> <li>A short selling transaction: sell the stock on day 3 for $8 then buy back on day 4 for $2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [12,16,19,19,8,1,19,13,9], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">36</span></p> <p><strong>Explanation:</strong></p> We can make $36 of profit through 3 transactions: <ul> <li>A normal transaction: buy the stock on day 0 for $12 then sell it on day 2 for $19.</li> <li>A short selling transaction: sell the stock on day 3 for $19 then buy back on day 4 for $8.</li> <li>A normal transaction: buy the stock on day 5 for $1 then sell it on day 6 for $19.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= prices.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= prices.length / 2</code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public long maximumProfit(int[] prices, int k) { int n = prices.length; long[][][] f = new long[n][k + 1][3]; for (int j = 1; j <= k; ++j) { f[0][j][1] = -prices[0]; f[0][j][2] = prices[0]; } for (int i = 1; i < n; ++i) { for (int j = 1; j <= k; ++j) { f[i][j][0] = Math.max(f[i - 1][j][0], Math.max(f[i - 1][j][1] + prices[i], f[i - 1][j][2] - prices[i])); f[i][j][1] = Math.max(f[i - 1][j][1], f[i - 1][j - 1][0] - prices[i]); f[i][j][2] = Math.max(f[i - 1][j][2], f[i - 1][j - 1][0] + prices[i]); } } return f[n - 1][k][0]; } }
3,573
Best Time to Buy and Sell Stock V
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a stock in dollars on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p> <p>You are allowed to make at most <code>k</code> transactions, where each transaction can be either of the following:</p> <ul> <li> <p><strong>Normal transaction</strong>: Buy on day <code>i</code>, then sell on a later day <code>j</code> where <code>i &lt; j</code>. You profit <code>prices[j] - prices[i]</code>.</p> </li> <li> <p><strong>Short selling transaction</strong>: Sell on day <code>i</code>, then buy back on a later day <code>j</code> where <code>i &lt; j</code>. You profit <code>prices[i] - prices[j]</code>.</p> </li> </ul> <p><strong>Note</strong> that you must complete each transaction before starting another. Additionally, you can't buy or sell on the same day you are selling or buying back as part of a previous transaction.</p> <p>Return the <strong>maximum</strong> total profit you can earn by making <strong>at most</strong> <code>k</code> transactions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [1,7,9,8,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> We can make $14 of profit through 2 transactions: <ul> <li>A normal transaction: buy the stock on day 0 for $1 then sell it on day 2 for $9.</li> <li>A short selling transaction: sell the stock on day 3 for $8 then buy back on day 4 for $2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [12,16,19,19,8,1,19,13,9], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">36</span></p> <p><strong>Explanation:</strong></p> We can make $36 of profit through 3 transactions: <ul> <li>A normal transaction: buy the stock on day 0 for $12 then sell it on day 2 for $19.</li> <li>A short selling transaction: sell the stock on day 3 for $19 then buy back on day 4 for $8.</li> <li>A normal transaction: buy the stock on day 5 for $1 then sell it on day 6 for $19.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= prices.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= prices.length / 2</code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maximumProfit(self, prices: List[int], k: int) -> int: n = len(prices) f = [[[0] * 3 for _ in range(k + 1)] for _ in range(n)] for j in range(1, k + 1): f[0][j][1] = -prices[0] f[0][j][2] = prices[0] for i in range(1, n): for j in range(1, k + 1): f[i][j][0] = max( f[i - 1][j][0], f[i - 1][j][1] + prices[i], f[i - 1][j][2] - prices[i], ) f[i][j][1] = max(f[i - 1][j][1], f[i - 1][j - 1][0] - prices[i]) f[i][j][2] = max(f[i - 1][j][2], f[i - 1][j - 1][0] + prices[i]) return f[n - 1][k][0]
3,573
Best Time to Buy and Sell Stock V
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a stock in dollars on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p> <p>You are allowed to make at most <code>k</code> transactions, where each transaction can be either of the following:</p> <ul> <li> <p><strong>Normal transaction</strong>: Buy on day <code>i</code>, then sell on a later day <code>j</code> where <code>i &lt; j</code>. You profit <code>prices[j] - prices[i]</code>.</p> </li> <li> <p><strong>Short selling transaction</strong>: Sell on day <code>i</code>, then buy back on a later day <code>j</code> where <code>i &lt; j</code>. You profit <code>prices[i] - prices[j]</code>.</p> </li> </ul> <p><strong>Note</strong> that you must complete each transaction before starting another. Additionally, you can't buy or sell on the same day you are selling or buying back as part of a previous transaction.</p> <p>Return the <strong>maximum</strong> total profit you can earn by making <strong>at most</strong> <code>k</code> transactions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [1,7,9,8,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> We can make $14 of profit through 2 transactions: <ul> <li>A normal transaction: buy the stock on day 0 for $1 then sell it on day 2 for $9.</li> <li>A short selling transaction: sell the stock on day 3 for $8 then buy back on day 4 for $2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [12,16,19,19,8,1,19,13,9], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">36</span></p> <p><strong>Explanation:</strong></p> We can make $36 of profit through 3 transactions: <ul> <li>A normal transaction: buy the stock on day 0 for $12 then sell it on day 2 for $19.</li> <li>A short selling transaction: sell the stock on day 3 for $19 then buy back on day 4 for $8.</li> <li>A normal transaction: buy the stock on day 5 for $1 then sell it on day 6 for $19.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= prices.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= prices.length / 2</code></li> </ul>
Array; Dynamic Programming
Rust
impl Solution { pub fn maximum_profit(prices: Vec<i32>, k: i32) -> i64 { let n = prices.len(); let k = k as usize; let mut f = vec![vec![vec![0i64; 3]; k + 1]; n]; for j in 1..=k { f[0][j][1] = -(prices[0] as i64); f[0][j][2] = prices[0] as i64; } for i in 1..n { for j in 1..=k { f[i][j][0] = f[i - 1][j][0] .max(f[i - 1][j][1] + prices[i] as i64) .max(f[i - 1][j][2] - prices[i] as i64); f[i][j][1] = f[i - 1][j][1].max(f[i - 1][j - 1][0] - prices[i] as i64); f[i][j][2] = f[i - 1][j][2].max(f[i - 1][j - 1][0] + prices[i] as i64); } } f[n - 1][k][0] } }
3,573
Best Time to Buy and Sell Stock V
Medium
<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a stock in dollars on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p> <p>You are allowed to make at most <code>k</code> transactions, where each transaction can be either of the following:</p> <ul> <li> <p><strong>Normal transaction</strong>: Buy on day <code>i</code>, then sell on a later day <code>j</code> where <code>i &lt; j</code>. You profit <code>prices[j] - prices[i]</code>.</p> </li> <li> <p><strong>Short selling transaction</strong>: Sell on day <code>i</code>, then buy back on a later day <code>j</code> where <code>i &lt; j</code>. You profit <code>prices[i] - prices[j]</code>.</p> </li> </ul> <p><strong>Note</strong> that you must complete each transaction before starting another. Additionally, you can't buy or sell on the same day you are selling or buying back as part of a previous transaction.</p> <p>Return the <strong>maximum</strong> total profit you can earn by making <strong>at most</strong> <code>k</code> transactions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [1,7,9,8,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> We can make $14 of profit through 2 transactions: <ul> <li>A normal transaction: buy the stock on day 0 for $1 then sell it on day 2 for $9.</li> <li>A short selling transaction: sell the stock on day 3 for $8 then buy back on day 4 for $2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [12,16,19,19,8,1,19,13,9], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">36</span></p> <p><strong>Explanation:</strong></p> We can make $36 of profit through 3 transactions: <ul> <li>A normal transaction: buy the stock on day 0 for $12 then sell it on day 2 for $19.</li> <li>A short selling transaction: sell the stock on day 3 for $19 then buy back on day 4 for $8.</li> <li>A normal transaction: buy the stock on day 5 for $1 then sell it on day 6 for $19.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= prices.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= prices.length / 2</code></li> </ul>
Array; Dynamic Programming
TypeScript
function maximumProfit(prices: number[], k: number): number { const n = prices.length; const f: number[][][] = Array.from({ length: n }, () => Array.from({ length: k + 1 }, () => Array(3).fill(0)), ); for (let j = 1; j <= k; ++j) { f[0][j][1] = -prices[0]; f[0][j][2] = prices[0]; } for (let i = 1; i < n; ++i) { for (let j = 1; j <= k; ++j) { f[i][j][0] = Math.max( f[i - 1][j][0], f[i - 1][j][1] + prices[i], f[i - 1][j][2] - prices[i], ); f[i][j][1] = Math.max(f[i - 1][j][1], f[i - 1][j - 1][0] - prices[i]); f[i][j][2] = Math.max(f[i - 1][j][2], f[i - 1][j - 1][0] + prices[i]); } } return f[n - 1][k][0]; }
3,574
Maximize Subarray GCD Score
Hard
<p>You are given an array of positive integers <code>nums</code> and an integer <code>k</code>.</p> <p>You may perform at most <code>k</code> operations. In each operation, you can choose one element in the array and <strong>double</strong> its value. Each element can be doubled <strong>at most</strong> once.</p> <p>The <strong>score</strong> of a contiguous <strong><span data-keyword="subarray">subarray</span></strong> is defined as the <strong>product</strong> of its length and the <em>greatest common divisor (GCD)</em> of all its elements.</p> <p>Your task is to return the <strong>maximum</strong> <strong>score</strong> that can be achieved by selecting a contiguous subarray from the modified array.</p> <p><strong>Note:</strong></p> <ul> <li>The <strong>greatest common divisor (GCD)</strong> of an array is the largest integer that evenly divides all the array elements.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Double <code>nums[0]</code> to 4 using one operation. The modified array becomes <code>[4, 4]</code>.</li> <li>The GCD of the subarray <code>[4, 4]</code> is 4, and the length is 2.</li> <li>Thus, the maximum possible score is <code>2 &times; 4 = 8</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,5,7], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Double <code>nums[2]</code> to 14 using one operation. The modified array becomes <code>[3, 5, 14]</code>.</li> <li>The GCD of the subarray <code>[14]</code> is 14, and the length is 1.</li> <li>Thus, the maximum possible score is <code>1 &times; 14 = 14</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,5,5], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray <code>[5, 5, 5]</code> has a GCD of 5, and its length is 3.</li> <li>Since doubling any element doesn&#39;t improve the score, the maximum score is <code>3 &times; 5 = 15</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 1500</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Math; Enumeration; Number Theory
C++
class Solution { public: long long maxGCDScore(vector<int>& nums, int k) { int n = nums.size(); vector<int> cnt(n); for (int i = 0; i < n; ++i) { for (int x = nums[i]; x % 2 == 0; x /= 2) { ++cnt[i]; } } long long ans = 0; for (int l = 0; l < n; ++l) { int g = 0; int mi = INT32_MAX; int t = 0; for (int r = l; r < n; ++r) { g = gcd(g, nums[r]); if (cnt[r] < mi) { mi = cnt[r]; t = 1; } else if (cnt[r] == mi) { ++t; } long long score = static_cast<long long>(r - l + 1) * (t > k ? g : g * 2); ans = max(ans, score); } } return ans; } };
3,574
Maximize Subarray GCD Score
Hard
<p>You are given an array of positive integers <code>nums</code> and an integer <code>k</code>.</p> <p>You may perform at most <code>k</code> operations. In each operation, you can choose one element in the array and <strong>double</strong> its value. Each element can be doubled <strong>at most</strong> once.</p> <p>The <strong>score</strong> of a contiguous <strong><span data-keyword="subarray">subarray</span></strong> is defined as the <strong>product</strong> of its length and the <em>greatest common divisor (GCD)</em> of all its elements.</p> <p>Your task is to return the <strong>maximum</strong> <strong>score</strong> that can be achieved by selecting a contiguous subarray from the modified array.</p> <p><strong>Note:</strong></p> <ul> <li>The <strong>greatest common divisor (GCD)</strong> of an array is the largest integer that evenly divides all the array elements.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Double <code>nums[0]</code> to 4 using one operation. The modified array becomes <code>[4, 4]</code>.</li> <li>The GCD of the subarray <code>[4, 4]</code> is 4, and the length is 2.</li> <li>Thus, the maximum possible score is <code>2 &times; 4 = 8</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,5,7], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Double <code>nums[2]</code> to 14 using one operation. The modified array becomes <code>[3, 5, 14]</code>.</li> <li>The GCD of the subarray <code>[14]</code> is 14, and the length is 1.</li> <li>Thus, the maximum possible score is <code>1 &times; 14 = 14</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,5,5], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray <code>[5, 5, 5]</code> has a GCD of 5, and its length is 3.</li> <li>Since doubling any element doesn&#39;t improve the score, the maximum score is <code>3 &times; 5 = 15</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 1500</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Math; Enumeration; Number Theory
Go
func maxGCDScore(nums []int, k int) int64 { n := len(nums) cnt := make([]int, n) for i, x := range nums { for x%2 == 0 { cnt[i]++ x /= 2 } } ans := 0 for l := 0; l < n; l++ { g := 0 mi := math.MaxInt32 t := 0 for r := l; r < n; r++ { g = gcd(g, nums[r]) if cnt[r] < mi { mi = cnt[r] t = 1 } else if cnt[r] == mi { t++ } length := r - l + 1 score := g * length if t <= k { score *= 2 } ans = max(ans, score) } } return int64(ans) } func gcd(a, b int) int { for b != 0 { a, b = b, a%b } return a }
3,574
Maximize Subarray GCD Score
Hard
<p>You are given an array of positive integers <code>nums</code> and an integer <code>k</code>.</p> <p>You may perform at most <code>k</code> operations. In each operation, you can choose one element in the array and <strong>double</strong> its value. Each element can be doubled <strong>at most</strong> once.</p> <p>The <strong>score</strong> of a contiguous <strong><span data-keyword="subarray">subarray</span></strong> is defined as the <strong>product</strong> of its length and the <em>greatest common divisor (GCD)</em> of all its elements.</p> <p>Your task is to return the <strong>maximum</strong> <strong>score</strong> that can be achieved by selecting a contiguous subarray from the modified array.</p> <p><strong>Note:</strong></p> <ul> <li>The <strong>greatest common divisor (GCD)</strong> of an array is the largest integer that evenly divides all the array elements.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Double <code>nums[0]</code> to 4 using one operation. The modified array becomes <code>[4, 4]</code>.</li> <li>The GCD of the subarray <code>[4, 4]</code> is 4, and the length is 2.</li> <li>Thus, the maximum possible score is <code>2 &times; 4 = 8</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,5,7], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Double <code>nums[2]</code> to 14 using one operation. The modified array becomes <code>[3, 5, 14]</code>.</li> <li>The GCD of the subarray <code>[14]</code> is 14, and the length is 1.</li> <li>Thus, the maximum possible score is <code>1 &times; 14 = 14</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,5,5], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray <code>[5, 5, 5]</code> has a GCD of 5, and its length is 3.</li> <li>Since doubling any element doesn&#39;t improve the score, the maximum score is <code>3 &times; 5 = 15</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 1500</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Math; Enumeration; Number Theory
Java
class Solution { public long maxGCDScore(int[] nums, int k) { int n = nums.length; int[] cnt = new int[n]; for (int i = 0; i < n; ++i) { for (int x = nums[i]; x % 2 == 0; x /= 2) { ++cnt[i]; } } long ans = 0; for (int l = 0; l < n; ++l) { int g = 0; int mi = 1 << 30; int t = 0; for (int r = l; r < n; ++r) { g = gcd(g, nums[r]); if (cnt[r] < mi) { mi = cnt[r]; t = 1; } else if (cnt[r] == mi) { ++t; } ans = Math.max(ans, (r - l + 1L) * (t > k ? g : g * 2)); } } return ans; } private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } }
3,574
Maximize Subarray GCD Score
Hard
<p>You are given an array of positive integers <code>nums</code> and an integer <code>k</code>.</p> <p>You may perform at most <code>k</code> operations. In each operation, you can choose one element in the array and <strong>double</strong> its value. Each element can be doubled <strong>at most</strong> once.</p> <p>The <strong>score</strong> of a contiguous <strong><span data-keyword="subarray">subarray</span></strong> is defined as the <strong>product</strong> of its length and the <em>greatest common divisor (GCD)</em> of all its elements.</p> <p>Your task is to return the <strong>maximum</strong> <strong>score</strong> that can be achieved by selecting a contiguous subarray from the modified array.</p> <p><strong>Note:</strong></p> <ul> <li>The <strong>greatest common divisor (GCD)</strong> of an array is the largest integer that evenly divides all the array elements.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Double <code>nums[0]</code> to 4 using one operation. The modified array becomes <code>[4, 4]</code>.</li> <li>The GCD of the subarray <code>[4, 4]</code> is 4, and the length is 2.</li> <li>Thus, the maximum possible score is <code>2 &times; 4 = 8</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,5,7], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Double <code>nums[2]</code> to 14 using one operation. The modified array becomes <code>[3, 5, 14]</code>.</li> <li>The GCD of the subarray <code>[14]</code> is 14, and the length is 1.</li> <li>Thus, the maximum possible score is <code>1 &times; 14 = 14</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,5,5], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray <code>[5, 5, 5]</code> has a GCD of 5, and its length is 3.</li> <li>Since doubling any element doesn&#39;t improve the score, the maximum score is <code>3 &times; 5 = 15</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 1500</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Math; Enumeration; Number Theory
Python
class Solution: def maxGCDScore(self, nums: List[int], k: int) -> int: n = len(nums) cnt = [0] * n for i, x in enumerate(nums): while x % 2 == 0: cnt[i] += 1 x //= 2 ans = 0 for l in range(n): g = 0 mi = inf t = 0 for r in range(l, n): g = gcd(g, nums[r]) if cnt[r] < mi: mi = cnt[r] t = 1 elif cnt[r] == mi: t += 1 ans = max(ans, (g if t > k else g * 2) * (r - l + 1)) return ans
3,574
Maximize Subarray GCD Score
Hard
<p>You are given an array of positive integers <code>nums</code> and an integer <code>k</code>.</p> <p>You may perform at most <code>k</code> operations. In each operation, you can choose one element in the array and <strong>double</strong> its value. Each element can be doubled <strong>at most</strong> once.</p> <p>The <strong>score</strong> of a contiguous <strong><span data-keyword="subarray">subarray</span></strong> is defined as the <strong>product</strong> of its length and the <em>greatest common divisor (GCD)</em> of all its elements.</p> <p>Your task is to return the <strong>maximum</strong> <strong>score</strong> that can be achieved by selecting a contiguous subarray from the modified array.</p> <p><strong>Note:</strong></p> <ul> <li>The <strong>greatest common divisor (GCD)</strong> of an array is the largest integer that evenly divides all the array elements.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Double <code>nums[0]</code> to 4 using one operation. The modified array becomes <code>[4, 4]</code>.</li> <li>The GCD of the subarray <code>[4, 4]</code> is 4, and the length is 2.</li> <li>Thus, the maximum possible score is <code>2 &times; 4 = 8</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,5,7], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">14</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Double <code>nums[2]</code> to 14 using one operation. The modified array becomes <code>[3, 5, 14]</code>.</li> <li>The GCD of the subarray <code>[14]</code> is 14, and the length is 1.</li> <li>Thus, the maximum possible score is <code>1 &times; 14 = 14</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,5,5], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The subarray <code>[5, 5, 5]</code> has a GCD of 5, and its length is 3.</li> <li>Since doubling any element doesn&#39;t improve the score, the maximum score is <code>3 &times; 5 = 15</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 1500</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Array; Math; Enumeration; Number Theory
TypeScript
function maxGCDScore(nums: number[], k: number): number { const n = nums.length; const cnt: number[] = Array(n).fill(0); for (let i = 0; i < n; ++i) { let x = nums[i]; while (x % 2 === 0) { cnt[i]++; x /= 2; } } let ans = 0; for (let l = 0; l < n; ++l) { let g = 0; let mi = Number.MAX_SAFE_INTEGER; let t = 0; for (let r = l; r < n; ++r) { g = gcd(g, nums[r]); if (cnt[r] < mi) { mi = cnt[r]; t = 1; } else if (cnt[r] === mi) { t++; } const len = r - l + 1; const score = (t > k ? g : g * 2) * len; ans = Math.max(ans, score); } } return ans; } function gcd(a: number, b: number): number { while (b !== 0) { const temp = b; b = a % b; a = temp; } return a; }
3,576
Transform Array to All Equal Elements
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> containing only <code>1</code> and <code>-1</code>, and an integer <code>k</code>.</p> <p>You can perform the following operation at most <code>k</code> times:</p> <ul> <li> <p>Choose an index <code>i</code> (<code>0 &lt;= i &lt; n - 1</code>), and <strong>multiply</strong> both <code>nums[i]</code> and <code>nums[i + 1]</code> by <code>-1</code>.</p> </li> </ul> <p><strong>Note</strong> that you can choose the same index <code data-end="459" data-start="456">i</code> more than once in <strong>different</strong> operations.</p> <p>Return <code>true</code> if it is possible to make all elements of the array <strong>equal</strong> after at most <code>k</code> operations, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,1,-1,1], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>We can make all elements in the array equal in 2 operations as follows:</p> <ul> <li>Choose index <code>i = 1</code>, and multiply both <code>nums[1]</code> and <code>nums[2]</code> by -1. Now <code>nums = [1,1,-1,-1,1]</code>.</li> <li>Choose index <code>i = 2</code>, and multiply both <code>nums[2]</code> and <code>nums[3]</code> by -1. Now <code>nums = [1,1,1,1,1]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-1,-1,1,1,1], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>It is not possible to make all array elements equal in at most 5 operations.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either -1 or 1.</li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array
C++
class Solution { public: bool canMakeEqual(vector<int>& nums, int k) { auto check = [&](int target, int k) -> bool { int n = nums.size(); int cnt = 0, sign = 1; for (int i = 0; i < n - 1; ++i) { int x = nums[i] * sign; if (x == target) { sign = 1; } else { sign = -1; ++cnt; } } return cnt <= k && nums[n - 1] * sign == target; }; return check(nums[0], k) || check(-nums[0], k); } };
3,576
Transform Array to All Equal Elements
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> containing only <code>1</code> and <code>-1</code>, and an integer <code>k</code>.</p> <p>You can perform the following operation at most <code>k</code> times:</p> <ul> <li> <p>Choose an index <code>i</code> (<code>0 &lt;= i &lt; n - 1</code>), and <strong>multiply</strong> both <code>nums[i]</code> and <code>nums[i + 1]</code> by <code>-1</code>.</p> </li> </ul> <p><strong>Note</strong> that you can choose the same index <code data-end="459" data-start="456">i</code> more than once in <strong>different</strong> operations.</p> <p>Return <code>true</code> if it is possible to make all elements of the array <strong>equal</strong> after at most <code>k</code> operations, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,1,-1,1], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>We can make all elements in the array equal in 2 operations as follows:</p> <ul> <li>Choose index <code>i = 1</code>, and multiply both <code>nums[1]</code> and <code>nums[2]</code> by -1. Now <code>nums = [1,1,-1,-1,1]</code>.</li> <li>Choose index <code>i = 2</code>, and multiply both <code>nums[2]</code> and <code>nums[3]</code> by -1. Now <code>nums = [1,1,1,1,1]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-1,-1,1,1,1], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>It is not possible to make all array elements equal in at most 5 operations.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either -1 or 1.</li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array
Go
func canMakeEqual(nums []int, k int) bool { check := func(target, k int) bool { cnt, sign := 0, 1 for i := 0; i < len(nums)-1; i++ { x := nums[i] * sign if x == target { sign = 1 } else { sign = -1 cnt++ } } return cnt <= k && nums[len(nums)-1]*sign == target } return check(nums[0], k) || check(-nums[0], k) }
3,576
Transform Array to All Equal Elements
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> containing only <code>1</code> and <code>-1</code>, and an integer <code>k</code>.</p> <p>You can perform the following operation at most <code>k</code> times:</p> <ul> <li> <p>Choose an index <code>i</code> (<code>0 &lt;= i &lt; n - 1</code>), and <strong>multiply</strong> both <code>nums[i]</code> and <code>nums[i + 1]</code> by <code>-1</code>.</p> </li> </ul> <p><strong>Note</strong> that you can choose the same index <code data-end="459" data-start="456">i</code> more than once in <strong>different</strong> operations.</p> <p>Return <code>true</code> if it is possible to make all elements of the array <strong>equal</strong> after at most <code>k</code> operations, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,1,-1,1], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>We can make all elements in the array equal in 2 operations as follows:</p> <ul> <li>Choose index <code>i = 1</code>, and multiply both <code>nums[1]</code> and <code>nums[2]</code> by -1. Now <code>nums = [1,1,-1,-1,1]</code>.</li> <li>Choose index <code>i = 2</code>, and multiply both <code>nums[2]</code> and <code>nums[3]</code> by -1. Now <code>nums = [1,1,1,1,1]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-1,-1,1,1,1], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>It is not possible to make all array elements equal in at most 5 operations.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either -1 or 1.</li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array
Java
class Solution { public boolean canMakeEqual(int[] nums, int k) { return check(nums, nums[0], k) || check(nums, -nums[0], k); } private boolean check(int[] nums, int target, int k) { int cnt = 0, sign = 1; for (int i = 0; i < nums.length - 1; ++i) { int x = nums[i] * sign; if (x == target) { sign = 1; } else { sign = -1; ++cnt; } } return cnt <= k && nums[nums.length - 1] * sign == target; } }
3,576
Transform Array to All Equal Elements
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> containing only <code>1</code> and <code>-1</code>, and an integer <code>k</code>.</p> <p>You can perform the following operation at most <code>k</code> times:</p> <ul> <li> <p>Choose an index <code>i</code> (<code>0 &lt;= i &lt; n - 1</code>), and <strong>multiply</strong> both <code>nums[i]</code> and <code>nums[i + 1]</code> by <code>-1</code>.</p> </li> </ul> <p><strong>Note</strong> that you can choose the same index <code data-end="459" data-start="456">i</code> more than once in <strong>different</strong> operations.</p> <p>Return <code>true</code> if it is possible to make all elements of the array <strong>equal</strong> after at most <code>k</code> operations, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,1,-1,1], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>We can make all elements in the array equal in 2 operations as follows:</p> <ul> <li>Choose index <code>i = 1</code>, and multiply both <code>nums[1]</code> and <code>nums[2]</code> by -1. Now <code>nums = [1,1,-1,-1,1]</code>.</li> <li>Choose index <code>i = 2</code>, and multiply both <code>nums[2]</code> and <code>nums[3]</code> by -1. Now <code>nums = [1,1,1,1,1]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-1,-1,1,1,1], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>It is not possible to make all array elements equal in at most 5 operations.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either -1 or 1.</li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array
Python
class Solution: def canMakeEqual(self, nums: List[int], k: int) -> bool: def check(target: int, k: int) -> bool: cnt, sign = 0, 1 for i in range(len(nums) - 1): x = nums[i] * sign if x == target: sign = 1 else: sign = -1 cnt += 1 return cnt <= k and nums[-1] * sign == target return check(nums[0], k) or check(-nums[0], k)
3,576
Transform Array to All Equal Elements
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> containing only <code>1</code> and <code>-1</code>, and an integer <code>k</code>.</p> <p>You can perform the following operation at most <code>k</code> times:</p> <ul> <li> <p>Choose an index <code>i</code> (<code>0 &lt;= i &lt; n - 1</code>), and <strong>multiply</strong> both <code>nums[i]</code> and <code>nums[i + 1]</code> by <code>-1</code>.</p> </li> </ul> <p><strong>Note</strong> that you can choose the same index <code data-end="459" data-start="456">i</code> more than once in <strong>different</strong> operations.</p> <p>Return <code>true</code> if it is possible to make all elements of the array <strong>equal</strong> after at most <code>k</code> operations, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,1,-1,1], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>We can make all elements in the array equal in 2 operations as follows:</p> <ul> <li>Choose index <code>i = 1</code>, and multiply both <code>nums[1]</code> and <code>nums[2]</code> by -1. Now <code>nums = [1,1,-1,-1,1]</code>.</li> <li>Choose index <code>i = 2</code>, and multiply both <code>nums[2]</code> and <code>nums[3]</code> by -1. Now <code>nums = [1,1,1,1,1]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-1,-1,1,1,1], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>It is not possible to make all array elements equal in at most 5 operations.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either -1 or 1.</li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array
Rust
impl Solution { pub fn can_make_equal(nums: Vec<i32>, k: i32) -> bool { fn check(target: i32, k: i32, nums: &Vec<i32>) -> bool { let mut cnt = 0; let mut sign = 1; for i in 0..nums.len() - 1 { let x = nums[i] * sign; if x == target { sign = 1; } else { sign = -1; cnt += 1; } } cnt <= k && nums[nums.len() - 1] * sign == target } check(nums[0], k, &nums) || check(-nums[0], k, &nums) } }
3,576
Transform Array to All Equal Elements
Medium
<p>You are given an integer array <code>nums</code> of size <code>n</code> containing only <code>1</code> and <code>-1</code>, and an integer <code>k</code>.</p> <p>You can perform the following operation at most <code>k</code> times:</p> <ul> <li> <p>Choose an index <code>i</code> (<code>0 &lt;= i &lt; n - 1</code>), and <strong>multiply</strong> both <code>nums[i]</code> and <code>nums[i + 1]</code> by <code>-1</code>.</p> </li> </ul> <p><strong>Note</strong> that you can choose the same index <code data-end="459" data-start="456">i</code> more than once in <strong>different</strong> operations.</p> <p>Return <code>true</code> if it is possible to make all elements of the array <strong>equal</strong> after at most <code>k</code> operations, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,-1,1,-1,1], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>We can make all elements in the array equal in 2 operations as follows:</p> <ul> <li>Choose index <code>i = 1</code>, and multiply both <code>nums[1]</code> and <code>nums[2]</code> by -1. Now <code>nums = [1,1,-1,-1,1]</code>.</li> <li>Choose index <code>i = 2</code>, and multiply both <code>nums[2]</code> and <code>nums[3]</code> by -1. Now <code>nums = [1,1,1,1,1]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-1,-1,1,1,1], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>It is not possible to make all array elements equal in at most 5 operations.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either -1 or 1.</li> <li><code>1 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array
TypeScript
function canMakeEqual(nums: number[], k: number): boolean { function check(target: number, k: number): boolean { let [cnt, sign] = [0, 1]; for (let i = 0; i < nums.length - 1; i++) { const x = nums[i] * sign; if (x === target) { sign = 1; } else { sign = -1; cnt++; } } return cnt <= k && nums[nums.length - 1] * sign === target; } return check(nums[0], k) || check(-nums[0], k); }
3,577
Count the Number of Computer Unlocking Permutations
Medium
<p>You are given an array <code>complexity</code> of length <code>n</code>.</p> <p>There are <code>n</code> <strong>locked</strong> computers in a room with labels from 0 to <code>n - 1</code>, each with its own <strong>unique</strong> password. The password of the computer <code>i</code> has a complexity <code>complexity[i]</code>.</p> <p>The password for the computer labeled 0 is <strong>already</strong> decrypted and serves as the root. All other computers must be unlocked using it or another previously unlocked computer, following this information:</p> <ul> <li>You can decrypt the password for the computer <code>i</code> using the password for computer <code>j</code>, where <code>j</code> is <strong>any</strong> integer less than <code>i</code> with a lower complexity. (i.e. <code>j &lt; i</code> and <code>complexity[j] &lt; complexity[i]</code>)</li> <li>To decrypt the password for computer <code>i</code>, you must have already unlocked a computer <code>j</code> such that <code>j &lt; i</code> and <code>complexity[j] &lt; complexity[i]</code>.</li> </ul> <p>Find the number of <span data-keyword="permutation-array">permutations</span> of <code>[0, 1, 2, ..., (n - 1)]</code> that represent a valid order in which the computers can be unlocked, starting from computer 0 as the only initially unlocked one.</p> <p>Since the answer may be large, return it <strong>modulo</strong> 10<sup>9</sup> + 7.</p> <p><strong>Note</strong> that the password for the computer <strong>with label</strong> 0 is decrypted, and <em>not</em> the computer with the first position in the permutation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">complexity = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The valid permutations are:</p> <ul> <li>[0, 1, 2] <ul> <li>Unlock computer 0 first with root password.</li> <li>Unlock computer 1 with password of computer 0 since <code>complexity[0] &lt; complexity[1]</code>.</li> <li>Unlock computer 2 with password of computer 1 since <code>complexity[1] &lt; complexity[2]</code>.</li> </ul> </li> <li>[0, 2, 1] <ul> <li>Unlock computer 0 first with root password.</li> <li>Unlock computer 2 with password of computer 0 since <code>complexity[0] &lt; complexity[2]</code>.</li> <li>Unlock computer 1 with password of computer 0 since <code>complexity[0] &lt; complexity[1]</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">complexity = [3,3,3,4,4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are no possible permutations which can unlock all computers.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= complexity.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= complexity[i] &lt;= 10<sup>9</sup></code></li> </ul>
Brainteaser; Array; Math; Combinatorics
C++
class Solution { public: int countPermutations(vector<int>& complexity) { const int mod = 1e9 + 7; long long ans = 1; for (int i = 1; i < complexity.size(); ++i) { if (complexity[i] <= complexity[0]) { return 0; } ans = ans * i % mod; } return ans; } };
3,577
Count the Number of Computer Unlocking Permutations
Medium
<p>You are given an array <code>complexity</code> of length <code>n</code>.</p> <p>There are <code>n</code> <strong>locked</strong> computers in a room with labels from 0 to <code>n - 1</code>, each with its own <strong>unique</strong> password. The password of the computer <code>i</code> has a complexity <code>complexity[i]</code>.</p> <p>The password for the computer labeled 0 is <strong>already</strong> decrypted and serves as the root. All other computers must be unlocked using it or another previously unlocked computer, following this information:</p> <ul> <li>You can decrypt the password for the computer <code>i</code> using the password for computer <code>j</code>, where <code>j</code> is <strong>any</strong> integer less than <code>i</code> with a lower complexity. (i.e. <code>j &lt; i</code> and <code>complexity[j] &lt; complexity[i]</code>)</li> <li>To decrypt the password for computer <code>i</code>, you must have already unlocked a computer <code>j</code> such that <code>j &lt; i</code> and <code>complexity[j] &lt; complexity[i]</code>.</li> </ul> <p>Find the number of <span data-keyword="permutation-array">permutations</span> of <code>[0, 1, 2, ..., (n - 1)]</code> that represent a valid order in which the computers can be unlocked, starting from computer 0 as the only initially unlocked one.</p> <p>Since the answer may be large, return it <strong>modulo</strong> 10<sup>9</sup> + 7.</p> <p><strong>Note</strong> that the password for the computer <strong>with label</strong> 0 is decrypted, and <em>not</em> the computer with the first position in the permutation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">complexity = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The valid permutations are:</p> <ul> <li>[0, 1, 2] <ul> <li>Unlock computer 0 first with root password.</li> <li>Unlock computer 1 with password of computer 0 since <code>complexity[0] &lt; complexity[1]</code>.</li> <li>Unlock computer 2 with password of computer 1 since <code>complexity[1] &lt; complexity[2]</code>.</li> </ul> </li> <li>[0, 2, 1] <ul> <li>Unlock computer 0 first with root password.</li> <li>Unlock computer 2 with password of computer 0 since <code>complexity[0] &lt; complexity[2]</code>.</li> <li>Unlock computer 1 with password of computer 0 since <code>complexity[0] &lt; complexity[1]</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">complexity = [3,3,3,4,4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are no possible permutations which can unlock all computers.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= complexity.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= complexity[i] &lt;= 10<sup>9</sup></code></li> </ul>
Brainteaser; Array; Math; Combinatorics
Go
func countPermutations(complexity []int) int { mod := int64(1e9 + 7) ans := int64(1) for i := 1; i < len(complexity); i++ { if complexity[i] <= complexity[0] { return 0 } ans = ans * int64(i) % mod } return int(ans) }
3,577
Count the Number of Computer Unlocking Permutations
Medium
<p>You are given an array <code>complexity</code> of length <code>n</code>.</p> <p>There are <code>n</code> <strong>locked</strong> computers in a room with labels from 0 to <code>n - 1</code>, each with its own <strong>unique</strong> password. The password of the computer <code>i</code> has a complexity <code>complexity[i]</code>.</p> <p>The password for the computer labeled 0 is <strong>already</strong> decrypted and serves as the root. All other computers must be unlocked using it or another previously unlocked computer, following this information:</p> <ul> <li>You can decrypt the password for the computer <code>i</code> using the password for computer <code>j</code>, where <code>j</code> is <strong>any</strong> integer less than <code>i</code> with a lower complexity. (i.e. <code>j &lt; i</code> and <code>complexity[j] &lt; complexity[i]</code>)</li> <li>To decrypt the password for computer <code>i</code>, you must have already unlocked a computer <code>j</code> such that <code>j &lt; i</code> and <code>complexity[j] &lt; complexity[i]</code>.</li> </ul> <p>Find the number of <span data-keyword="permutation-array">permutations</span> of <code>[0, 1, 2, ..., (n - 1)]</code> that represent a valid order in which the computers can be unlocked, starting from computer 0 as the only initially unlocked one.</p> <p>Since the answer may be large, return it <strong>modulo</strong> 10<sup>9</sup> + 7.</p> <p><strong>Note</strong> that the password for the computer <strong>with label</strong> 0 is decrypted, and <em>not</em> the computer with the first position in the permutation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">complexity = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The valid permutations are:</p> <ul> <li>[0, 1, 2] <ul> <li>Unlock computer 0 first with root password.</li> <li>Unlock computer 1 with password of computer 0 since <code>complexity[0] &lt; complexity[1]</code>.</li> <li>Unlock computer 2 with password of computer 1 since <code>complexity[1] &lt; complexity[2]</code>.</li> </ul> </li> <li>[0, 2, 1] <ul> <li>Unlock computer 0 first with root password.</li> <li>Unlock computer 2 with password of computer 0 since <code>complexity[0] &lt; complexity[2]</code>.</li> <li>Unlock computer 1 with password of computer 0 since <code>complexity[0] &lt; complexity[1]</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">complexity = [3,3,3,4,4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are no possible permutations which can unlock all computers.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= complexity.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= complexity[i] &lt;= 10<sup>9</sup></code></li> </ul>
Brainteaser; Array; Math; Combinatorics
Java
class Solution { public int countPermutations(int[] complexity) { final int mod = (int) 1e9 + 7; long ans = 1; for (int i = 1; i < complexity.length; ++i) { if (complexity[i] <= complexity[0]) { return 0; } ans = ans * i % mod; } return (int) ans; } }
3,577
Count the Number of Computer Unlocking Permutations
Medium
<p>You are given an array <code>complexity</code> of length <code>n</code>.</p> <p>There are <code>n</code> <strong>locked</strong> computers in a room with labels from 0 to <code>n - 1</code>, each with its own <strong>unique</strong> password. The password of the computer <code>i</code> has a complexity <code>complexity[i]</code>.</p> <p>The password for the computer labeled 0 is <strong>already</strong> decrypted and serves as the root. All other computers must be unlocked using it or another previously unlocked computer, following this information:</p> <ul> <li>You can decrypt the password for the computer <code>i</code> using the password for computer <code>j</code>, where <code>j</code> is <strong>any</strong> integer less than <code>i</code> with a lower complexity. (i.e. <code>j &lt; i</code> and <code>complexity[j] &lt; complexity[i]</code>)</li> <li>To decrypt the password for computer <code>i</code>, you must have already unlocked a computer <code>j</code> such that <code>j &lt; i</code> and <code>complexity[j] &lt; complexity[i]</code>.</li> </ul> <p>Find the number of <span data-keyword="permutation-array">permutations</span> of <code>[0, 1, 2, ..., (n - 1)]</code> that represent a valid order in which the computers can be unlocked, starting from computer 0 as the only initially unlocked one.</p> <p>Since the answer may be large, return it <strong>modulo</strong> 10<sup>9</sup> + 7.</p> <p><strong>Note</strong> that the password for the computer <strong>with label</strong> 0 is decrypted, and <em>not</em> the computer with the first position in the permutation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">complexity = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The valid permutations are:</p> <ul> <li>[0, 1, 2] <ul> <li>Unlock computer 0 first with root password.</li> <li>Unlock computer 1 with password of computer 0 since <code>complexity[0] &lt; complexity[1]</code>.</li> <li>Unlock computer 2 with password of computer 1 since <code>complexity[1] &lt; complexity[2]</code>.</li> </ul> </li> <li>[0, 2, 1] <ul> <li>Unlock computer 0 first with root password.</li> <li>Unlock computer 2 with password of computer 0 since <code>complexity[0] &lt; complexity[2]</code>.</li> <li>Unlock computer 1 with password of computer 0 since <code>complexity[0] &lt; complexity[1]</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">complexity = [3,3,3,4,4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are no possible permutations which can unlock all computers.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= complexity.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= complexity[i] &lt;= 10<sup>9</sup></code></li> </ul>
Brainteaser; Array; Math; Combinatorics
Python
class Solution: def countPermutations(self, complexity: List[int]) -> int: mod = 10**9 + 7 ans = 1 for i in range(1, len(complexity)): if complexity[i] <= complexity[0]: return 0 ans = ans * i % mod return ans
3,577
Count the Number of Computer Unlocking Permutations
Medium
<p>You are given an array <code>complexity</code> of length <code>n</code>.</p> <p>There are <code>n</code> <strong>locked</strong> computers in a room with labels from 0 to <code>n - 1</code>, each with its own <strong>unique</strong> password. The password of the computer <code>i</code> has a complexity <code>complexity[i]</code>.</p> <p>The password for the computer labeled 0 is <strong>already</strong> decrypted and serves as the root. All other computers must be unlocked using it or another previously unlocked computer, following this information:</p> <ul> <li>You can decrypt the password for the computer <code>i</code> using the password for computer <code>j</code>, where <code>j</code> is <strong>any</strong> integer less than <code>i</code> with a lower complexity. (i.e. <code>j &lt; i</code> and <code>complexity[j] &lt; complexity[i]</code>)</li> <li>To decrypt the password for computer <code>i</code>, you must have already unlocked a computer <code>j</code> such that <code>j &lt; i</code> and <code>complexity[j] &lt; complexity[i]</code>.</li> </ul> <p>Find the number of <span data-keyword="permutation-array">permutations</span> of <code>[0, 1, 2, ..., (n - 1)]</code> that represent a valid order in which the computers can be unlocked, starting from computer 0 as the only initially unlocked one.</p> <p>Since the answer may be large, return it <strong>modulo</strong> 10<sup>9</sup> + 7.</p> <p><strong>Note</strong> that the password for the computer <strong>with label</strong> 0 is decrypted, and <em>not</em> the computer with the first position in the permutation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">complexity = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The valid permutations are:</p> <ul> <li>[0, 1, 2] <ul> <li>Unlock computer 0 first with root password.</li> <li>Unlock computer 1 with password of computer 0 since <code>complexity[0] &lt; complexity[1]</code>.</li> <li>Unlock computer 2 with password of computer 1 since <code>complexity[1] &lt; complexity[2]</code>.</li> </ul> </li> <li>[0, 2, 1] <ul> <li>Unlock computer 0 first with root password.</li> <li>Unlock computer 2 with password of computer 0 since <code>complexity[0] &lt; complexity[2]</code>.</li> <li>Unlock computer 1 with password of computer 0 since <code>complexity[0] &lt; complexity[1]</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">complexity = [3,3,3,4,4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are no possible permutations which can unlock all computers.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= complexity.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= complexity[i] &lt;= 10<sup>9</sup></code></li> </ul>
Brainteaser; Array; Math; Combinatorics
Rust
impl Solution { pub fn count_permutations(complexity: Vec<i32>) -> i32 { const MOD: i64 = 1_000_000_007; let mut ans = 1i64; for i in 1..complexity.len() { if complexity[i] <= complexity[0] { return 0; } ans = ans * i as i64 % MOD; } ans as i32 } }
3,577
Count the Number of Computer Unlocking Permutations
Medium
<p>You are given an array <code>complexity</code> of length <code>n</code>.</p> <p>There are <code>n</code> <strong>locked</strong> computers in a room with labels from 0 to <code>n - 1</code>, each with its own <strong>unique</strong> password. The password of the computer <code>i</code> has a complexity <code>complexity[i]</code>.</p> <p>The password for the computer labeled 0 is <strong>already</strong> decrypted and serves as the root. All other computers must be unlocked using it or another previously unlocked computer, following this information:</p> <ul> <li>You can decrypt the password for the computer <code>i</code> using the password for computer <code>j</code>, where <code>j</code> is <strong>any</strong> integer less than <code>i</code> with a lower complexity. (i.e. <code>j &lt; i</code> and <code>complexity[j] &lt; complexity[i]</code>)</li> <li>To decrypt the password for computer <code>i</code>, you must have already unlocked a computer <code>j</code> such that <code>j &lt; i</code> and <code>complexity[j] &lt; complexity[i]</code>.</li> </ul> <p>Find the number of <span data-keyword="permutation-array">permutations</span> of <code>[0, 1, 2, ..., (n - 1)]</code> that represent a valid order in which the computers can be unlocked, starting from computer 0 as the only initially unlocked one.</p> <p>Since the answer may be large, return it <strong>modulo</strong> 10<sup>9</sup> + 7.</p> <p><strong>Note</strong> that the password for the computer <strong>with label</strong> 0 is decrypted, and <em>not</em> the computer with the first position in the permutation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">complexity = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The valid permutations are:</p> <ul> <li>[0, 1, 2] <ul> <li>Unlock computer 0 first with root password.</li> <li>Unlock computer 1 with password of computer 0 since <code>complexity[0] &lt; complexity[1]</code>.</li> <li>Unlock computer 2 with password of computer 1 since <code>complexity[1] &lt; complexity[2]</code>.</li> </ul> </li> <li>[0, 2, 1] <ul> <li>Unlock computer 0 first with root password.</li> <li>Unlock computer 2 with password of computer 0 since <code>complexity[0] &lt; complexity[2]</code>.</li> <li>Unlock computer 1 with password of computer 0 since <code>complexity[0] &lt; complexity[1]</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">complexity = [3,3,3,4,4,4]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are no possible permutations which can unlock all computers.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= complexity.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= complexity[i] &lt;= 10<sup>9</sup></code></li> </ul>
Brainteaser; Array; Math; Combinatorics
TypeScript
function countPermutations(complexity: number[]): number { const mod = 1e9 + 7; let ans = 1; for (let i = 1; i < complexity.length; i++) { if (complexity[i] <= complexity[0]) { return 0; } ans = (ans * i) % mod; } return ans; }
3,578
Count Partitions With Max-Min Difference at Most K
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. Your task is to partition <code>nums</code> into one or more <strong>non-empty</strong> contiguous segments such that in each segment, the difference between its <strong>maximum</strong> and <strong>minimum</strong> elements is <strong>at most</strong> <code>k</code>.</p> <p>Return the total number of ways to partition <code>nums</code> under this condition.</p> <p>Since the answer may be too 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"> <p><strong>Input:</strong> <span class="example-io">nums = [9,4,1,3,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>There are 6 valid partitions where the difference between the maximum and minimum elements in each segment is at most <code>k = 4</code>:</p> <ul> <li><code>[[9], [4], [1], [3], [7]]</code></li> <li><code>[[9], [4], [1], [3, 7]]</code></li> <li><code>[[9], [4], [1, 3], [7]]</code></li> <li><code>[[9], [4, 1], [3], [7]]</code></li> <li><code>[[9], [4, 1], [3, 7]]</code></li> <li><code>[[9], [4, 1, 3], [7]]</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,3,4], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>There are 2 valid partitions that satisfy the given conditions:</p> <ul> <li><code>[[3], [3], [4]]</code></li> <li><code>[[3, 3], [4]]</code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Prefix Sum; Sliding Window; Monotonic Queue
C++
class Solution { public: int countPartitions(vector<int>& nums, int k) { const int mod = 1e9 + 7; multiset<int> sl; int n = nums.size(); vector<int> f(n + 1, 0), g(n + 1, 0); f[0] = 1; g[0] = 1; int l = 1; for (int r = 1; r <= n; ++r) { int x = nums[r - 1]; sl.insert(x); while (*sl.rbegin() - *sl.begin() > k) { sl.erase(sl.find(nums[l - 1])); ++l; } f[r] = (g[r - 1] - (l >= 2 ? g[l - 2] : 0) + mod) % mod; g[r] = (g[r - 1] + f[r]) % mod; } return f[n]; } };
3,578
Count Partitions With Max-Min Difference at Most K
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. Your task is to partition <code>nums</code> into one or more <strong>non-empty</strong> contiguous segments such that in each segment, the difference between its <strong>maximum</strong> and <strong>minimum</strong> elements is <strong>at most</strong> <code>k</code>.</p> <p>Return the total number of ways to partition <code>nums</code> under this condition.</p> <p>Since the answer may be too 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"> <p><strong>Input:</strong> <span class="example-io">nums = [9,4,1,3,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>There are 6 valid partitions where the difference between the maximum and minimum elements in each segment is at most <code>k = 4</code>:</p> <ul> <li><code>[[9], [4], [1], [3], [7]]</code></li> <li><code>[[9], [4], [1], [3, 7]]</code></li> <li><code>[[9], [4], [1, 3], [7]]</code></li> <li><code>[[9], [4, 1], [3], [7]]</code></li> <li><code>[[9], [4, 1], [3, 7]]</code></li> <li><code>[[9], [4, 1, 3], [7]]</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,3,4], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>There are 2 valid partitions that satisfy the given conditions:</p> <ul> <li><code>[[3], [3], [4]]</code></li> <li><code>[[3, 3], [4]]</code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Prefix Sum; Sliding Window; Monotonic Queue
Go
func countPartitions(nums []int, k int) int { const mod int = 1e9 + 7 sl := redblacktree.New[int, int]() merge := func(st *redblacktree.Tree[int, int], x, v int) { c, _ := st.Get(x) if c+v == 0 { st.Remove(x) } else { st.Put(x, c+v) } } n := len(nums) f := make([]int, n+1) g := make([]int, n+1) f[0], g[0] = 1, 1 for l, r := 1, 1; r <= n; r++ { merge(sl, nums[r-1], 1) for sl.Right().Key-sl.Left().Key > k { merge(sl, nums[l-1], -1) l++ } f[r] = g[r-1] if l >= 2 { f[r] = (f[r] - g[l-2] + mod) % mod } g[r] = (g[r-1] + f[r]) % mod } return f[n] }
3,578
Count Partitions With Max-Min Difference at Most K
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. Your task is to partition <code>nums</code> into one or more <strong>non-empty</strong> contiguous segments such that in each segment, the difference between its <strong>maximum</strong> and <strong>minimum</strong> elements is <strong>at most</strong> <code>k</code>.</p> <p>Return the total number of ways to partition <code>nums</code> under this condition.</p> <p>Since the answer may be too 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"> <p><strong>Input:</strong> <span class="example-io">nums = [9,4,1,3,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>There are 6 valid partitions where the difference between the maximum and minimum elements in each segment is at most <code>k = 4</code>:</p> <ul> <li><code>[[9], [4], [1], [3], [7]]</code></li> <li><code>[[9], [4], [1], [3, 7]]</code></li> <li><code>[[9], [4], [1, 3], [7]]</code></li> <li><code>[[9], [4, 1], [3], [7]]</code></li> <li><code>[[9], [4, 1], [3, 7]]</code></li> <li><code>[[9], [4, 1, 3], [7]]</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,3,4], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>There are 2 valid partitions that satisfy the given conditions:</p> <ul> <li><code>[[3], [3], [4]]</code></li> <li><code>[[3, 3], [4]]</code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Prefix Sum; Sliding Window; Monotonic Queue
Java
class Solution { public int countPartitions(int[] nums, int k) { final int mod = (int) 1e9 + 7; TreeMap<Integer, Integer> sl = new TreeMap<>(); int n = nums.length; int[] f = new int[n + 1]; int[] g = new int[n + 1]; f[0] = 1; g[0] = 1; int l = 1; for (int r = 1; r <= n; r++) { int x = nums[r - 1]; sl.merge(x, 1, Integer::sum); while (sl.lastKey() - sl.firstKey() > k) { if (sl.merge(nums[l - 1], -1, Integer::sum) == 0) { sl.remove(nums[l - 1]); } ++l; } f[r] = (g[r - 1] - (l >= 2 ? g[l - 2] : 0) + mod) % mod; g[r] = (g[r - 1] + f[r]) % mod; } return f[n]; } }
3,578
Count Partitions With Max-Min Difference at Most K
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. Your task is to partition <code>nums</code> into one or more <strong>non-empty</strong> contiguous segments such that in each segment, the difference between its <strong>maximum</strong> and <strong>minimum</strong> elements is <strong>at most</strong> <code>k</code>.</p> <p>Return the total number of ways to partition <code>nums</code> under this condition.</p> <p>Since the answer may be too 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"> <p><strong>Input:</strong> <span class="example-io">nums = [9,4,1,3,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>There are 6 valid partitions where the difference between the maximum and minimum elements in each segment is at most <code>k = 4</code>:</p> <ul> <li><code>[[9], [4], [1], [3], [7]]</code></li> <li><code>[[9], [4], [1], [3, 7]]</code></li> <li><code>[[9], [4], [1, 3], [7]]</code></li> <li><code>[[9], [4, 1], [3], [7]]</code></li> <li><code>[[9], [4, 1], [3, 7]]</code></li> <li><code>[[9], [4, 1, 3], [7]]</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,3,4], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>There are 2 valid partitions that satisfy the given conditions:</p> <ul> <li><code>[[3], [3], [4]]</code></li> <li><code>[[3, 3], [4]]</code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Prefix Sum; Sliding Window; Monotonic Queue
Python
class Solution: def countPartitions(self, nums: List[int], k: int) -> int: mod = 10**9 + 7 sl = SortedList() n = len(nums) f = [1] + [0] * n g = [1] + [0] * n l = 1 for r, x in enumerate(nums, 1): sl.add(x) while sl[-1] - sl[0] > k: sl.remove(nums[l - 1]) l += 1 f[r] = (g[r - 1] - (g[l - 2] if l >= 2 else 0) + mod) % mod g[r] = (g[r - 1] + f[r]) % mod return f[n]
3,578
Count Partitions With Max-Min Difference at Most K
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. Your task is to partition <code>nums</code> into one or more <strong>non-empty</strong> contiguous segments such that in each segment, the difference between its <strong>maximum</strong> and <strong>minimum</strong> elements is <strong>at most</strong> <code>k</code>.</p> <p>Return the total number of ways to partition <code>nums</code> under this condition.</p> <p>Since the answer may be too 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"> <p><strong>Input:</strong> <span class="example-io">nums = [9,4,1,3,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>There are 6 valid partitions where the difference between the maximum and minimum elements in each segment is at most <code>k = 4</code>:</p> <ul> <li><code>[[9], [4], [1], [3], [7]]</code></li> <li><code>[[9], [4], [1], [3, 7]]</code></li> <li><code>[[9], [4], [1, 3], [7]]</code></li> <li><code>[[9], [4, 1], [3], [7]]</code></li> <li><code>[[9], [4, 1], [3, 7]]</code></li> <li><code>[[9], [4, 1, 3], [7]]</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,3,4], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>There are 2 valid partitions that satisfy the given conditions:</p> <ul> <li><code>[[3], [3], [4]]</code></li> <li><code>[[3, 3], [4]]</code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Prefix Sum; Sliding Window; Monotonic Queue
Rust
use std::collections::BTreeMap; impl Solution { pub fn count_partitions(nums: Vec<i32>, k: i32) -> i32 { const mod_val: i32 = 1_000_000_007; let n = nums.len(); let mut f = vec![0; n + 1]; let mut g = vec![0; n + 1]; f[0] = 1; g[0] = 1; let mut sl = BTreeMap::new(); let mut l = 1; for r in 1..=n { let x = nums[r - 1]; *sl.entry(x).or_insert(0) += 1; while sl.keys().last().unwrap() - sl.keys().next().unwrap() > k { let val = nums[l - 1]; if let Some(cnt) = sl.get_mut(&val) { *cnt -= 1; if *cnt == 0 { sl.remove(&val); } } l += 1; } f[r] = (g[r - 1] - if l >= 2 { g[l - 2] } else { 0 } + mod_val) % mod_val; g[r] = (g[r - 1] + f[r]) % mod_val; } f[n] } }
3,578
Count Partitions With Max-Min Difference at Most K
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. Your task is to partition <code>nums</code> into one or more <strong>non-empty</strong> contiguous segments such that in each segment, the difference between its <strong>maximum</strong> and <strong>minimum</strong> elements is <strong>at most</strong> <code>k</code>.</p> <p>Return the total number of ways to partition <code>nums</code> under this condition.</p> <p>Since the answer may be too 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"> <p><strong>Input:</strong> <span class="example-io">nums = [9,4,1,3,7], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>There are 6 valid partitions where the difference between the maximum and minimum elements in each segment is at most <code>k = 4</code>:</p> <ul> <li><code>[[9], [4], [1], [3], [7]]</code></li> <li><code>[[9], [4], [1], [3, 7]]</code></li> <li><code>[[9], [4], [1, 3], [7]]</code></li> <li><code>[[9], [4, 1], [3], [7]]</code></li> <li><code>[[9], [4, 1], [3, 7]]</code></li> <li><code>[[9], [4, 1, 3], [7]]</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,3,4], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>There are 2 valid partitions that satisfy the given conditions:</p> <ul> <li><code>[[3], [3], [4]]</code></li> <li><code>[[3, 3], [4]]</code></li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Prefix Sum; Sliding Window; Monotonic Queue
TypeScript
function countPartitions(nums: number[], k: number): number { const mod = 10 ** 9 + 7; const n = nums.length; const sl = new TreapMultiSet<number>((a, b) => a - b); const f: number[] = Array(n + 1).fill(0); const g: number[] = Array(n + 1).fill(0); f[0] = 1; g[0] = 1; for (let l = 1, r = 1; r <= n; ++r) { const x = nums[r - 1]; sl.add(x); while (sl.last()! - sl.first()! > k) { sl.delete(nums[l - 1]); l++; } f[r] = (g[r - 1] - (l >= 2 ? g[l - 2] : 0) + mod) % mod; g[r] = (g[r - 1] + f[r]) % mod; } return f[n]; } type CompareFunction<T, R extends 'number' | 'boolean'> = ( a: T, b: T, ) => R extends 'number' ? number : boolean; interface ITreapMultiSet<T> extends Iterable<T> { add: (...value: T[]) => this; has: (value: T) => boolean; delete: (value: T) => void; bisectLeft: (value: T) => number; bisectRight: (value: T) => number; indexOf: (value: T) => number; lastIndexOf: (value: T) => number; at: (index: number) => T | undefined; first: () => T | undefined; last: () => T | undefined; lower: (value: T) => T | undefined; higher: (value: T) => T | undefined; floor: (value: T) => T | undefined; ceil: (value: T) => T | undefined; shift: () => T | undefined; pop: (index?: number) => T | undefined; count: (value: T) => number; keys: () => IterableIterator<T>; values: () => IterableIterator<T>; rvalues: () => IterableIterator<T>; entries: () => IterableIterator<[number, T]>; readonly size: number; } class TreapNode<T = number> { value: T; count: number; size: number; priority: number; left: TreapNode<T> | null; right: TreapNode<T> | null; constructor(value: T) { this.value = value; this.count = 1; this.size = 1; this.priority = Math.random(); this.left = null; this.right = null; } static getSize(node: TreapNode<any> | null): number { return node?.size ?? 0; } static getFac(node: TreapNode<any> | null): number { return node?.priority ?? 0; } pushUp(): void { let tmp = this.count; tmp += TreapNode.getSize(this.left); tmp += TreapNode.getSize(this.right); this.size = tmp; } rotateRight(): TreapNode<T> { // eslint-disable-next-line @typescript-eslint/no-this-alias let node: TreapNode<T> = this; const left = node.left; node.left = left?.right ?? null; left && (left.right = node); left && (node = left); node.right?.pushUp(); node.pushUp(); return node; } rotateLeft(): TreapNode<T> { // eslint-disable-next-line @typescript-eslint/no-this-alias let node: TreapNode<T> = this; const right = node.right; node.right = right?.left ?? null; right && (right.left = node); right && (node = right); node.left?.pushUp(); node.pushUp(); return node; } } class TreapMultiSet<T = number> implements ITreapMultiSet<T> { private readonly root: TreapNode<T>; private readonly compareFn: CompareFunction<T, 'number'>; private readonly leftBound: T; private readonly rightBound: T; constructor(compareFn?: CompareFunction<T, 'number'>); constructor(compareFn: CompareFunction<T, 'number'>, leftBound: T, rightBound: T); constructor( compareFn: CompareFunction<T, any> = (a: any, b: any) => a - b, leftBound: any = -Infinity, rightBound: any = Infinity, ) { this.root = new TreapNode<T>(rightBound); this.root.priority = Infinity; this.root.left = new TreapNode<T>(leftBound); this.root.left.priority = -Infinity; this.root.pushUp(); this.leftBound = leftBound; this.rightBound = rightBound; this.compareFn = compareFn; } get size(): number { return this.root.size - 2; } get height(): number { const getHeight = (node: TreapNode<T> | null): number => { if (node == null) return 0; return 1 + Math.max(getHeight(node.left), getHeight(node.right)); }; return getHeight(this.root); } /** * * @complexity `O(logn)` * @description Returns true if value is a member. */ has(value: T): boolean { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): boolean => { if (node == null) return false; if (compare(node.value, value) === 0) return true; if (compare(node.value, value) < 0) return dfs(node.right, value); return dfs(node.left, value); }; return dfs(this.root, value); } /** * * @complexity `O(logn)` * @description Add value to sorted set. */ add(...values: T[]): this { const compare = this.compareFn; const dfs = ( node: TreapNode<T> | null, value: T, parent: TreapNode<T>, direction: 'left' | 'right', ): void => { if (node == null) return; if (compare(node.value, value) === 0) { node.count++; node.pushUp(); } else if (compare(node.value, value) > 0) { if (node.left) { dfs(node.left, value, node, 'left'); } else { node.left = new TreapNode(value); node.pushUp(); } if (TreapNode.getFac(node.left) > node.priority) { parent[direction] = node.rotateRight(); } } else if (compare(node.value, value) < 0) { if (node.right) { dfs(node.right, value, node, 'right'); } else { node.right = new TreapNode(value); node.pushUp(); } if (TreapNode.getFac(node.right) > node.priority) { parent[direction] = node.rotateLeft(); } } parent.pushUp(); }; values.forEach(value => dfs(this.root.left, value, this.root, 'left')); return this; } /** * * @complexity `O(logn)` * @description Remove value from sorted set if it is a member. * If value is not a member, do nothing. */ delete(value: T): void { const compare = this.compareFn; const dfs = ( node: TreapNode<T> | null, value: T, parent: TreapNode<T>, direction: 'left' | 'right', ): void => { if (node == null) return; if (compare(node.value, value) === 0) { if (node.count > 1) { node.count--; node?.pushUp(); } else if (node.left == null && node.right == null) { parent[direction] = null; } else { // 旋到根节点 if ( node.right == null || TreapNode.getFac(node.left) > TreapNode.getFac(node.right) ) { parent[direction] = node.rotateRight(); dfs(parent[direction]?.right ?? null, value, parent[direction]!, 'right'); } else { parent[direction] = node.rotateLeft(); dfs(parent[direction]?.left ?? null, value, parent[direction]!, 'left'); } } } else if (compare(node.value, value) > 0) { dfs(node.left, value, node, 'left'); } else if (compare(node.value, value) < 0) { dfs(node.right, value, node, 'right'); } parent?.pushUp(); }; dfs(this.root.left, value, this.root, 'left'); } /** * * @complexity `O(logn)` * @description Returns an index to insert value in the sorted set. * If the value is already present, the insertion point will be before (to the left of) any existing values. */ bisectLeft(value: T): number { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) { return TreapNode.getSize(node.left); } else if (compare(node.value, value) > 0) { return dfs(node.left, value); } else if (compare(node.value, value) < 0) { return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; } return 0; }; return dfs(this.root, value) - 1; } /** * * @complexity `O(logn)` * @description Returns an index to insert value in the sorted set. * If the value is already present, the insertion point will be before (to the right of) any existing values. */ bisectRight(value: T): number { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) { return TreapNode.getSize(node.left) + node.count; } else if (compare(node.value, value) > 0) { return dfs(node.left, value); } else if (compare(node.value, value) < 0) { return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; } return 0; }; return dfs(this.root, value) - 1; } /** * * @complexity `O(logn)` * @description Returns the index of the first occurrence of a value in the set, or -1 if it is not present. */ indexOf(value: T): number { const compare = this.compareFn; let isExist = false; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) { isExist = true; return TreapNode.getSize(node.left); } else if (compare(node.value, value) > 0) { return dfs(node.left, value); } else if (compare(node.value, value) < 0) { return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; } return 0; }; const res = dfs(this.root, value) - 1; return isExist ? res : -1; } /** * * @complexity `O(logn)` * @description Returns the index of the last occurrence of a value in the set, or -1 if it is not present. */ lastIndexOf(value: T): number { const compare = this.compareFn; let isExist = false; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) { isExist = true; return TreapNode.getSize(node.left) + node.count - 1; } else if (compare(node.value, value) > 0) { return dfs(node.left, value); } else if (compare(node.value, value) < 0) { return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; } return 0; }; const res = dfs(this.root, value) - 1; return isExist ? res : -1; } /** * * @complexity `O(logn)` * @description Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. */ at(index: number): T | undefined { if (index < 0) index += this.size; if (index < 0 || index >= this.size) return undefined; const dfs = (node: TreapNode<T> | null, rank: number): T | undefined => { if (node == null) return undefined; if (TreapNode.getSize(node.left) >= rank) { return dfs(node.left, rank); } else if (TreapNode.getSize(node.left) + node.count >= rank) { return node.value; } else { return dfs(node.right, rank - TreapNode.getSize(node.left) - node.count); } }; const res = dfs(this.root, index + 2); return ([this.leftBound, this.rightBound] as any[]).includes(res) ? undefined : res; } /** * * @complexity `O(logn)` * @description Find and return the element less than `val`, return `undefined` if no such element found. */ lower(value: T): T | undefined { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): T | undefined => { if (node == null) return undefined; if (compare(node.value, value) >= 0) return dfs(node.left, value); const tmp = dfs(node.right, value); if (tmp == null || compare(node.value, tmp) > 0) { return node.value; } else { return tmp; } }; const res = dfs(this.root, value) as any; return res === this.leftBound ? undefined : res; } /** * * @complexity `O(logn)` * @description Find and return the element greater than `val`, return `undefined` if no such element found. */ higher(value: T): T | undefined { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): T | undefined => { if (node == null) return undefined; if (compare(node.value, value) <= 0) return dfs(node.right, value); const tmp = dfs(node.left, value); if (tmp == null || compare(node.value, tmp) < 0) { return node.value; } else { return tmp; } }; const res = dfs(this.root, value) as any; return res === this.rightBound ? undefined : res; } /** * * @complexity `O(logn)` * @description Find and return the element less than or equal to `val`, return `undefined` if no such element found. */ floor(value: T): T | undefined { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): T | undefined => { if (node == null) return undefined; if (compare(node.value, value) === 0) return node.value; if (compare(node.value, value) >= 0) return dfs(node.left, value); const tmp = dfs(node.right, value); if (tmp == null || compare(node.value, tmp) > 0) { return node.value; } else { return tmp; } }; const res = dfs(this.root, value) as any; return res === this.leftBound ? undefined : res; } /** * * @complexity `O(logn)` * @description Find and return the element greater than or equal to `val`, return `undefined` if no such element found. */ ceil(value: T): T | undefined { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): T | undefined => { if (node == null) return undefined; if (compare(node.value, value) === 0) return node.value; if (compare(node.value, value) <= 0) return dfs(node.right, value); const tmp = dfs(node.left, value); if (tmp == null || compare(node.value, tmp) < 0) { return node.value; } else { return tmp; } }; const res = dfs(this.root, value) as any; return res === this.rightBound ? undefined : res; } /** * @complexity `O(logn)` * @description * Returns the last element from set. * If the set is empty, undefined is returned. */ first(): T | undefined { const iter = this.inOrder(); iter.next(); const res = iter.next().value; return res === this.rightBound ? undefined : res; } /** * @complexity `O(logn)` * @description * Returns the last element from set. * If the set is empty, undefined is returned . */ last(): T | undefined { const iter = this.reverseInOrder(); iter.next(); const res = iter.next().value; return res === this.leftBound ? undefined : res; } /** * @complexity `O(logn)` * @description * Removes the first element from an set and returns it. * If the set is empty, undefined is returned and the set is not modified. */ shift(): T | undefined { const first = this.first(); if (first === undefined) return undefined; this.delete(first); return first; } /** * @complexity `O(logn)` * @description * Removes the last element from an set and returns it. * If the set is empty, undefined is returned and the set is not modified. */ pop(index?: number): T | undefined { if (index == null) { const last = this.last(); if (last === undefined) return undefined; this.delete(last); return last; } const toDelete = this.at(index); if (toDelete == null) return; this.delete(toDelete); return toDelete; } /** * * @complexity `O(logn)` * @description * Returns number of occurrences of value in the sorted set. */ count(value: T): number { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) return node.count; if (compare(node.value, value) < 0) return dfs(node.right, value); return dfs(node.left, value); }; return dfs(this.root, value); } *[Symbol.iterator](): Generator<T, any, any> { yield* this.values(); } /** * @description * Returns an iterable of keys in the set. */ *keys(): Generator<T, any, any> { yield* this.values(); } /** * @description * Returns an iterable of values in the set. */ *values(): Generator<T, any, any> { const iter = this.inOrder(); iter.next(); const steps = this.size; for (let _ = 0; _ < steps; _++) { yield iter.next().value; } } /** * @description * Returns a generator for reversed order traversing the set. */ *rvalues(): Generator<T, any, any> { const iter = this.reverseInOrder(); iter.next(); const steps = this.size; for (let _ = 0; _ < steps; _++) { yield iter.next().value; } } /** * @description * Returns an iterable of key, value pairs for every entry in the set. */ *entries(): IterableIterator<[number, T]> { const iter = this.inOrder(); iter.next(); const steps = this.size; for (let i = 0; i < steps; i++) { yield [i, iter.next().value]; } } private *inOrder(root: TreapNode<T> | null = this.root): Generator<T, any, any> { if (root == null) return; yield* this.inOrder(root.left); const count = root.count; for (let _ = 0; _ < count; _++) { yield root.value; } yield* this.inOrder(root.right); } private *reverseInOrder(root: TreapNode<T> | null = this.root): Generator<T, any, any> { if (root == null) return; yield* this.reverseInOrder(root.right); const count = root.count; for (let _ = 0; _ < count; _++) { yield root.value; } yield* this.reverseInOrder(root.left); } }
3,579
Minimum Steps to Convert String with Operations
Hard
<p>You are given two strings, <code>word1</code> and <code>word2</code>, of equal length. You need to transform <code>word1</code> into <code>word2</code>.</p> <p>For this, divide <code>word1</code> into one or more <strong>contiguous <span data-keyword="substring-nonempty">substrings</span></strong>. For each substring <code>substr</code> you can perform the following operations:</p> <ol> <li> <p><strong>Replace:</strong> Replace the character at any one index of <code>substr</code> with another lowercase English letter.</p> </li> <li> <p><strong>Swap:</strong> Swap any two characters in <code>substr</code>.</p> </li> <li> <p><strong>Reverse Substring:</strong> Reverse <code>substr</code>.</p> </li> </ol> <p>Each of these counts as <strong>one</strong> operation and each character of each substring can be used in each type of operation at most once (i.e. no single index may be involved in more than one replace, one swap, or one reverse).</p> <p>Return the <strong>minimum number of operations</strong> required to transform <code>word1</code> into <code>word2</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">word1 = &quot;abcdf&quot;, word2 = &quot;dacbe&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;ab&quot;</code>, <code>&quot;c&quot;</code>, and <code>&quot;df&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;ab&quot;</code>, <ul> <li>Perform operation of type 3 on <code>&quot;ab&quot; -&gt; &quot;ba&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;ba&quot; -&gt; &quot;da&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;c&quot;</code> do no operations.</li> <li>For the substring <code>&quot;df&quot;</code>, <ul> <li>Perform operation of type 1 on <code>&quot;df&quot; -&gt; &quot;bf&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;bf&quot; -&gt; &quot;be&quot;</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abceded&quot;, word2 = &quot;baecfef&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;ab&quot;</code>, <code>&quot;ce&quot;</code>, and <code>&quot;ded&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;ab&quot;</code>, <ul> <li>Perform operation of type 2 on <code>&quot;ab&quot; -&gt; &quot;ba&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;ce&quot;</code>, <ul> <li>Perform operation of type 2 on <code>&quot;ce&quot; -&gt; &quot;ec&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;ded&quot;</code>, <ul> <li>Perform operation of type 1 on <code>&quot;ded&quot; -&gt; &quot;fed&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;fed&quot; -&gt; &quot;fef&quot;</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcdef&quot;, word2 = &quot;fedabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;abcdef&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;abcdef&quot;</code>, <ul> <li>Perform operation of type 3 on <code>&quot;abcdef&quot; -&gt; &quot;fedcba&quot;</code>.</li> <li>Perform operation of type 2 on <code>&quot;fedcba&quot; -&gt; &quot;fedabc&quot;</code>.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length == word2.length &lt;= 100</code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Greedy; String; Dynamic Programming
C++
class Solution { public: int minOperations(string word1, string word2) { int n = word1.length(); vector<int> f(n + 1, INT_MAX); f[0] = 0; for (int i = 1; i <= n; ++i) { for (int j = 0; j < i; ++j) { int a = calc(word1, word2, j, i - 1, false); int b = 1 + calc(word1, word2, j, i - 1, true); int t = min(a, b); f[i] = min(f[i], f[j] + t); } } return f[n]; } private: int calc(const string& word1, const string& word2, int l, int r, bool rev) { int cnt[26][26] = {0}; int res = 0; for (int i = l; i <= r; ++i) { int j = rev ? r - (i - l) : i; int a = word1[j] - 'a'; int b = word2[i] - 'a'; if (a != b) { if (cnt[b][a] > 0) { cnt[b][a]--; } else { cnt[a][b]++; res++; } } } return res; } };
3,579
Minimum Steps to Convert String with Operations
Hard
<p>You are given two strings, <code>word1</code> and <code>word2</code>, of equal length. You need to transform <code>word1</code> into <code>word2</code>.</p> <p>For this, divide <code>word1</code> into one or more <strong>contiguous <span data-keyword="substring-nonempty">substrings</span></strong>. For each substring <code>substr</code> you can perform the following operations:</p> <ol> <li> <p><strong>Replace:</strong> Replace the character at any one index of <code>substr</code> with another lowercase English letter.</p> </li> <li> <p><strong>Swap:</strong> Swap any two characters in <code>substr</code>.</p> </li> <li> <p><strong>Reverse Substring:</strong> Reverse <code>substr</code>.</p> </li> </ol> <p>Each of these counts as <strong>one</strong> operation and each character of each substring can be used in each type of operation at most once (i.e. no single index may be involved in more than one replace, one swap, or one reverse).</p> <p>Return the <strong>minimum number of operations</strong> required to transform <code>word1</code> into <code>word2</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">word1 = &quot;abcdf&quot;, word2 = &quot;dacbe&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;ab&quot;</code>, <code>&quot;c&quot;</code>, and <code>&quot;df&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;ab&quot;</code>, <ul> <li>Perform operation of type 3 on <code>&quot;ab&quot; -&gt; &quot;ba&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;ba&quot; -&gt; &quot;da&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;c&quot;</code> do no operations.</li> <li>For the substring <code>&quot;df&quot;</code>, <ul> <li>Perform operation of type 1 on <code>&quot;df&quot; -&gt; &quot;bf&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;bf&quot; -&gt; &quot;be&quot;</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abceded&quot;, word2 = &quot;baecfef&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;ab&quot;</code>, <code>&quot;ce&quot;</code>, and <code>&quot;ded&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;ab&quot;</code>, <ul> <li>Perform operation of type 2 on <code>&quot;ab&quot; -&gt; &quot;ba&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;ce&quot;</code>, <ul> <li>Perform operation of type 2 on <code>&quot;ce&quot; -&gt; &quot;ec&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;ded&quot;</code>, <ul> <li>Perform operation of type 1 on <code>&quot;ded&quot; -&gt; &quot;fed&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;fed&quot; -&gt; &quot;fef&quot;</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcdef&quot;, word2 = &quot;fedabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;abcdef&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;abcdef&quot;</code>, <ul> <li>Perform operation of type 3 on <code>&quot;abcdef&quot; -&gt; &quot;fedcba&quot;</code>.</li> <li>Perform operation of type 2 on <code>&quot;fedcba&quot; -&gt; &quot;fedabc&quot;</code>.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length == word2.length &lt;= 100</code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Greedy; String; Dynamic Programming
Go
func minOperations(word1 string, word2 string) int { n := len(word1) f := make([]int, n+1) for i := range f { f[i] = math.MaxInt32 } f[0] = 0 calc := func(l, r int, rev bool) int { var cnt [26][26]int res := 0 for i := l; i <= r; i++ { j := i if rev { j = r - (i - l) } a := word1[j] - 'a' b := word2[i] - 'a' if a != b { if cnt[b][a] > 0 { cnt[b][a]-- } else { cnt[a][b]++ res++ } } } return res } for i := 1; i <= n; i++ { for j := 0; j < i; j++ { a := calc(j, i-1, false) b := 1 + calc(j, i-1, true) t := min(a, b) f[i] = min(f[i], f[j]+t) } } return f[n] }
3,579
Minimum Steps to Convert String with Operations
Hard
<p>You are given two strings, <code>word1</code> and <code>word2</code>, of equal length. You need to transform <code>word1</code> into <code>word2</code>.</p> <p>For this, divide <code>word1</code> into one or more <strong>contiguous <span data-keyword="substring-nonempty">substrings</span></strong>. For each substring <code>substr</code> you can perform the following operations:</p> <ol> <li> <p><strong>Replace:</strong> Replace the character at any one index of <code>substr</code> with another lowercase English letter.</p> </li> <li> <p><strong>Swap:</strong> Swap any two characters in <code>substr</code>.</p> </li> <li> <p><strong>Reverse Substring:</strong> Reverse <code>substr</code>.</p> </li> </ol> <p>Each of these counts as <strong>one</strong> operation and each character of each substring can be used in each type of operation at most once (i.e. no single index may be involved in more than one replace, one swap, or one reverse).</p> <p>Return the <strong>minimum number of operations</strong> required to transform <code>word1</code> into <code>word2</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">word1 = &quot;abcdf&quot;, word2 = &quot;dacbe&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;ab&quot;</code>, <code>&quot;c&quot;</code>, and <code>&quot;df&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;ab&quot;</code>, <ul> <li>Perform operation of type 3 on <code>&quot;ab&quot; -&gt; &quot;ba&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;ba&quot; -&gt; &quot;da&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;c&quot;</code> do no operations.</li> <li>For the substring <code>&quot;df&quot;</code>, <ul> <li>Perform operation of type 1 on <code>&quot;df&quot; -&gt; &quot;bf&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;bf&quot; -&gt; &quot;be&quot;</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abceded&quot;, word2 = &quot;baecfef&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;ab&quot;</code>, <code>&quot;ce&quot;</code>, and <code>&quot;ded&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;ab&quot;</code>, <ul> <li>Perform operation of type 2 on <code>&quot;ab&quot; -&gt; &quot;ba&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;ce&quot;</code>, <ul> <li>Perform operation of type 2 on <code>&quot;ce&quot; -&gt; &quot;ec&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;ded&quot;</code>, <ul> <li>Perform operation of type 1 on <code>&quot;ded&quot; -&gt; &quot;fed&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;fed&quot; -&gt; &quot;fef&quot;</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcdef&quot;, word2 = &quot;fedabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;abcdef&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;abcdef&quot;</code>, <ul> <li>Perform operation of type 3 on <code>&quot;abcdef&quot; -&gt; &quot;fedcba&quot;</code>.</li> <li>Perform operation of type 2 on <code>&quot;fedcba&quot; -&gt; &quot;fedabc&quot;</code>.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length == word2.length &lt;= 100</code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Greedy; String; Dynamic Programming
Java
class Solution { public int minOperations(String word1, String word2) { int n = word1.length(); int[] f = new int[n + 1]; Arrays.fill(f, Integer.MAX_VALUE); f[0] = 0; for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) { int a = calc(word1, word2, j, i - 1, false); int b = 1 + calc(word1, word2, j, i - 1, true); int t = Math.min(a, b); f[i] = Math.min(f[i], f[j] + t); } } return f[n]; } private int calc(String word1, String word2, int l, int r, boolean rev) { int[][] cnt = new int[26][26]; int res = 0; for (int i = l; i <= r; i++) { int j = rev ? r - (i - l) : i; int a = word1.charAt(j) - 'a'; int b = word2.charAt(i) - 'a'; if (a != b) { if (cnt[b][a] > 0) { cnt[b][a]--; } else { cnt[a][b]++; res++; } } } return res; } }
3,579
Minimum Steps to Convert String with Operations
Hard
<p>You are given two strings, <code>word1</code> and <code>word2</code>, of equal length. You need to transform <code>word1</code> into <code>word2</code>.</p> <p>For this, divide <code>word1</code> into one or more <strong>contiguous <span data-keyword="substring-nonempty">substrings</span></strong>. For each substring <code>substr</code> you can perform the following operations:</p> <ol> <li> <p><strong>Replace:</strong> Replace the character at any one index of <code>substr</code> with another lowercase English letter.</p> </li> <li> <p><strong>Swap:</strong> Swap any two characters in <code>substr</code>.</p> </li> <li> <p><strong>Reverse Substring:</strong> Reverse <code>substr</code>.</p> </li> </ol> <p>Each of these counts as <strong>one</strong> operation and each character of each substring can be used in each type of operation at most once (i.e. no single index may be involved in more than one replace, one swap, or one reverse).</p> <p>Return the <strong>minimum number of operations</strong> required to transform <code>word1</code> into <code>word2</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">word1 = &quot;abcdf&quot;, word2 = &quot;dacbe&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;ab&quot;</code>, <code>&quot;c&quot;</code>, and <code>&quot;df&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;ab&quot;</code>, <ul> <li>Perform operation of type 3 on <code>&quot;ab&quot; -&gt; &quot;ba&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;ba&quot; -&gt; &quot;da&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;c&quot;</code> do no operations.</li> <li>For the substring <code>&quot;df&quot;</code>, <ul> <li>Perform operation of type 1 on <code>&quot;df&quot; -&gt; &quot;bf&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;bf&quot; -&gt; &quot;be&quot;</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abceded&quot;, word2 = &quot;baecfef&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;ab&quot;</code>, <code>&quot;ce&quot;</code>, and <code>&quot;ded&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;ab&quot;</code>, <ul> <li>Perform operation of type 2 on <code>&quot;ab&quot; -&gt; &quot;ba&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;ce&quot;</code>, <ul> <li>Perform operation of type 2 on <code>&quot;ce&quot; -&gt; &quot;ec&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;ded&quot;</code>, <ul> <li>Perform operation of type 1 on <code>&quot;ded&quot; -&gt; &quot;fed&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;fed&quot; -&gt; &quot;fef&quot;</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcdef&quot;, word2 = &quot;fedabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;abcdef&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;abcdef&quot;</code>, <ul> <li>Perform operation of type 3 on <code>&quot;abcdef&quot; -&gt; &quot;fedcba&quot;</code>.</li> <li>Perform operation of type 2 on <code>&quot;fedcba&quot; -&gt; &quot;fedabc&quot;</code>.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length == word2.length &lt;= 100</code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Greedy; String; Dynamic Programming
Python
class Solution: def minOperations(self, word1: str, word2: str) -> int: def calc(l: int, r: int, rev: bool) -> int: cnt = Counter() res = 0 for i in range(l, r + 1): j = r - (i - l) if rev else i a, b = word1[j], word2[i] if a != b: if cnt[(b, a)] > 0: cnt[(b, a)] -= 1 else: cnt[(a, b)] += 1 res += 1 return res n = len(word1) f = [inf] * (n + 1) f[0] = 0 for i in range(1, n + 1): for j in range(i): t = min(calc(j, i - 1, False), 1 + calc(j, i - 1, True)) f[i] = min(f[i], f[j] + t) return f[n]
3,579
Minimum Steps to Convert String with Operations
Hard
<p>You are given two strings, <code>word1</code> and <code>word2</code>, of equal length. You need to transform <code>word1</code> into <code>word2</code>.</p> <p>For this, divide <code>word1</code> into one or more <strong>contiguous <span data-keyword="substring-nonempty">substrings</span></strong>. For each substring <code>substr</code> you can perform the following operations:</p> <ol> <li> <p><strong>Replace:</strong> Replace the character at any one index of <code>substr</code> with another lowercase English letter.</p> </li> <li> <p><strong>Swap:</strong> Swap any two characters in <code>substr</code>.</p> </li> <li> <p><strong>Reverse Substring:</strong> Reverse <code>substr</code>.</p> </li> </ol> <p>Each of these counts as <strong>one</strong> operation and each character of each substring can be used in each type of operation at most once (i.e. no single index may be involved in more than one replace, one swap, or one reverse).</p> <p>Return the <strong>minimum number of operations</strong> required to transform <code>word1</code> into <code>word2</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">word1 = &quot;abcdf&quot;, word2 = &quot;dacbe&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;ab&quot;</code>, <code>&quot;c&quot;</code>, and <code>&quot;df&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;ab&quot;</code>, <ul> <li>Perform operation of type 3 on <code>&quot;ab&quot; -&gt; &quot;ba&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;ba&quot; -&gt; &quot;da&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;c&quot;</code> do no operations.</li> <li>For the substring <code>&quot;df&quot;</code>, <ul> <li>Perform operation of type 1 on <code>&quot;df&quot; -&gt; &quot;bf&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;bf&quot; -&gt; &quot;be&quot;</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abceded&quot;, word2 = &quot;baecfef&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;ab&quot;</code>, <code>&quot;ce&quot;</code>, and <code>&quot;ded&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;ab&quot;</code>, <ul> <li>Perform operation of type 2 on <code>&quot;ab&quot; -&gt; &quot;ba&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;ce&quot;</code>, <ul> <li>Perform operation of type 2 on <code>&quot;ce&quot; -&gt; &quot;ec&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;ded&quot;</code>, <ul> <li>Perform operation of type 1 on <code>&quot;ded&quot; -&gt; &quot;fed&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;fed&quot; -&gt; &quot;fef&quot;</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcdef&quot;, word2 = &quot;fedabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;abcdef&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;abcdef&quot;</code>, <ul> <li>Perform operation of type 3 on <code>&quot;abcdef&quot; -&gt; &quot;fedcba&quot;</code>.</li> <li>Perform operation of type 2 on <code>&quot;fedcba&quot; -&gt; &quot;fedabc&quot;</code>.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length == word2.length &lt;= 100</code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Greedy; String; Dynamic Programming
Rust
impl Solution { pub fn min_operations(word1: String, word2: String) -> i32 { let n = word1.len(); let word1 = word1.as_bytes(); let word2 = word2.as_bytes(); let mut f = vec![i32::MAX; n + 1]; f[0] = 0; for i in 1..=n { for j in 0..i { let a = Self::calc(word1, word2, j, i - 1, false); let b = 1 + Self::calc(word1, word2, j, i - 1, true); let t = a.min(b); f[i] = f[i].min(f[j] + t); } } f[n] } fn calc(word1: &[u8], word2: &[u8], l: usize, r: usize, rev: bool) -> i32 { let mut cnt = [[0i32; 26]; 26]; let mut res = 0; for i in l..=r { let j = if rev { r - (i - l) } else { i }; let a = (word1[j] - b'a') as usize; let b = (word2[i] - b'a') as usize; if a != b { if cnt[b][a] > 0 { cnt[b][a] -= 1; } else { cnt[a][b] += 1; res += 1; } } } res } }
3,579
Minimum Steps to Convert String with Operations
Hard
<p>You are given two strings, <code>word1</code> and <code>word2</code>, of equal length. You need to transform <code>word1</code> into <code>word2</code>.</p> <p>For this, divide <code>word1</code> into one or more <strong>contiguous <span data-keyword="substring-nonempty">substrings</span></strong>. For each substring <code>substr</code> you can perform the following operations:</p> <ol> <li> <p><strong>Replace:</strong> Replace the character at any one index of <code>substr</code> with another lowercase English letter.</p> </li> <li> <p><strong>Swap:</strong> Swap any two characters in <code>substr</code>.</p> </li> <li> <p><strong>Reverse Substring:</strong> Reverse <code>substr</code>.</p> </li> </ol> <p>Each of these counts as <strong>one</strong> operation and each character of each substring can be used in each type of operation at most once (i.e. no single index may be involved in more than one replace, one swap, or one reverse).</p> <p>Return the <strong>minimum number of operations</strong> required to transform <code>word1</code> into <code>word2</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">word1 = &quot;abcdf&quot;, word2 = &quot;dacbe&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;ab&quot;</code>, <code>&quot;c&quot;</code>, and <code>&quot;df&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;ab&quot;</code>, <ul> <li>Perform operation of type 3 on <code>&quot;ab&quot; -&gt; &quot;ba&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;ba&quot; -&gt; &quot;da&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;c&quot;</code> do no operations.</li> <li>For the substring <code>&quot;df&quot;</code>, <ul> <li>Perform operation of type 1 on <code>&quot;df&quot; -&gt; &quot;bf&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;bf&quot; -&gt; &quot;be&quot;</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abceded&quot;, word2 = &quot;baecfef&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;ab&quot;</code>, <code>&quot;ce&quot;</code>, and <code>&quot;ded&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;ab&quot;</code>, <ul> <li>Perform operation of type 2 on <code>&quot;ab&quot; -&gt; &quot;ba&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;ce&quot;</code>, <ul> <li>Perform operation of type 2 on <code>&quot;ce&quot; -&gt; &quot;ec&quot;</code>.</li> </ul> </li> <li>For the substring <code>&quot;ded&quot;</code>, <ul> <li>Perform operation of type 1 on <code>&quot;ded&quot; -&gt; &quot;fed&quot;</code>.</li> <li>Perform operation of type 1 on <code>&quot;fed&quot; -&gt; &quot;fef&quot;</code>.</li> </ul> </li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcdef&quot;, word2 = &quot;fedabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Divide <code>word1</code> into <code>&quot;abcdef&quot;</code>. The operations are:</p> <ul> <li>For the substring <code>&quot;abcdef&quot;</code>, <ul> <li>Perform operation of type 3 on <code>&quot;abcdef&quot; -&gt; &quot;fedcba&quot;</code>.</li> <li>Perform operation of type 2 on <code>&quot;fedcba&quot; -&gt; &quot;fedabc&quot;</code>.</li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length == word2.length &lt;= 100</code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Greedy; String; Dynamic Programming
TypeScript
function minOperations(word1: string, word2: string): number { const n = word1.length; const f = Array(n + 1).fill(Number.MAX_SAFE_INTEGER); f[0] = 0; function calc(l: number, r: number, rev: boolean): number { const cnt: number[][] = Array.from({ length: 26 }, () => Array(26).fill(0)); let res = 0; for (let i = l; i <= r; i++) { const j = rev ? r - (i - l) : i; const a = word1.charCodeAt(j) - 97; const b = word2.charCodeAt(i) - 97; if (a !== b) { if (cnt[b][a] > 0) { cnt[b][a]--; } else { cnt[a][b]++; res++; } } } return res; } for (let i = 1; i <= n; i++) { for (let j = 0; j < i; j++) { const a = calc(j, i - 1, false); const b = 1 + calc(j, i - 1, true); const t = Math.min(a, b); f[i] = Math.min(f[i], f[j] + t); } } return f[n]; }
3,580
Find Consistently Improving Employees
Medium
<p>Table: <code>employees</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | employee_id | int | | name | varchar | +-------------+---------+ employee_id is the unique identifier for this table. Each row contains information about an employee. </pre> <p>Table: <code>performance_reviews</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | review_id | int | | employee_id | int | | review_date | date | | rating | int | +-------------+------+ review_id is the unique identifier for this table. Each row represents a performance review for an employee. The rating is on a scale of 1-5 where 5 is excellent and 1 is poor. </pre> <p>Write a solution to find employees who have consistently improved their performance over <strong>their last three reviews</strong>.</p> <ul> <li>An employee must have <strong>at least </strong><code>3</code><strong> review</strong> to be considered</li> <li>The employee&#39;s <strong>last </strong><code>3</code><strong> reviews</strong> must show <strong>strictly increasing ratings</strong> (each review better than the previous)</li> <li>Use the most recent <code>3</code> reviews based on <code>review_date</code> for each employee</li> <li>Calculate the <strong>improvement score</strong> as the difference between the latest rating and the earliest rating among the last <code>3</code> reviews</li> </ul> <p>Return <em>the result table ordered by <strong>improvement score</strong> in <strong>descending</strong> order, then by <strong>name</strong> in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>employees table:</p> <pre class="example-io"> +-------------+----------------+ | employee_id | name | +-------------+----------------+ | 1 | Alice Johnson | | 2 | Bob Smith | | 3 | Carol Davis | | 4 | David Wilson | | 5 | Emma Brown | +-------------+----------------+ </pre> <p>performance_reviews table:</p> <pre class="example-io"> +-----------+-------------+-------------+--------+ | review_id | employee_id | review_date | rating | +-----------+-------------+-------------+--------+ | 1 | 1 | 2023-01-15 | 2 | | 2 | 1 | 2023-04-15 | 3 | | 3 | 1 | 2023-07-15 | 4 | | 4 | 1 | 2023-10-15 | 5 | | 5 | 2 | 2023-02-01 | 3 | | 6 | 2 | 2023-05-01 | 2 | | 7 | 2 | 2023-08-01 | 4 | | 8 | 2 | 2023-11-01 | 5 | | 9 | 3 | 2023-03-10 | 1 | | 10 | 3 | 2023-06-10 | 2 | | 11 | 3 | 2023-09-10 | 3 | | 12 | 3 | 2023-12-10 | 4 | | 13 | 4 | 2023-01-20 | 4 | | 14 | 4 | 2023-04-20 | 4 | | 15 | 4 | 2023-07-20 | 4 | | 16 | 5 | 2023-02-15 | 3 | | 17 | 5 | 2023-05-15 | 2 | +-----------+-------------+-------------+--------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+----------------+-------------------+ | employee_id | name | improvement_score | +-------------+----------------+-------------------+ | 2 | Bob Smith | 3 | | 1 | Alice Johnson | 2 | | 3 | Carol Davis | 2 | +-------------+----------------+-------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Alice Johnson (employee_id = 1):</strong> <ul> <li>Has 4 reviews with ratings: 2, 3, 4, 5</li> <li>Last 3 reviews (by date): 2023-04-15 (3), 2023-07-15 (4), 2023-10-15 (5)</li> <li>Ratings are strictly increasing: 3 &rarr; 4 &rarr; 5</li> <li>Improvement score: 5 - 3 = 2</li> </ul> </li> <li><strong>Carol Davis (employee_id = 3):</strong> <ul> <li>Has 4 reviews with ratings: 1, 2, 3, 4</li> <li>Last 3 reviews (by date): 2023-06-10 (2), 2023-09-10 (3), 2023-12-10 (4)</li> <li>Ratings are strictly increasing: 2 &rarr; 3 &rarr; 4</li> <li>Improvement score: 4 - 2 = 2</li> </ul> </li> <li><strong>Bob Smith (employee_id = 2):</strong> <ul> <li>Has 4 reviews with ratings: 3, 2, 4, 5</li> <li>Last 3 reviews (by date): 2023-05-01 (2), 2023-08-01 (4), 2023-11-01 (5)</li> <li>Ratings are strictly increasing: 2 &rarr; 4 &rarr; 5</li> <li>Improvement score: 5 - 2 = 3</li> </ul> </li> <li><strong>Employees not included:</strong> <ul> <li>David Wilson (employee_id = 4): Last 3 reviews are all 4 (no improvement)</li> <li>Emma Brown (employee_id = 5): Only has 2 reviews (needs at least 3)</li> </ul> </li> </ul> <p>The output table is ordered by improvement_score in descending order, then by name in ascending order.</p> </div>
Database
Python
import pandas as pd def find_consistently_improving_employees( employees: pd.DataFrame, performance_reviews: pd.DataFrame ) -> pd.DataFrame: performance_reviews = performance_reviews.sort_values( ["employee_id", "review_date"], ascending=[True, False] ) performance_reviews["rn"] = ( performance_reviews.groupby("employee_id").cumcount() + 1 ) performance_reviews["lag_rating"] = performance_reviews.groupby("employee_id")[ "rating" ].shift(1) performance_reviews["delta"] = ( performance_reviews["lag_rating"] - performance_reviews["rating"] ) recent = performance_reviews[ (performance_reviews["rn"] > 1) & (performance_reviews["rn"] <= 3) ] improvement = ( recent.groupby("employee_id") .agg( improvement_score=("delta", "sum"), count=("delta", "count"), min_delta=("delta", "min"), ) .reset_index() ) improvement = improvement[ (improvement["count"] == 2) & (improvement["min_delta"] > 0) ] result = improvement.merge(employees[["employee_id", "name"]], on="employee_id") result = result.sort_values( by=["improvement_score", "name"], ascending=[False, True] ) return result[["employee_id", "name", "improvement_score"]]
3,580
Find Consistently Improving Employees
Medium
<p>Table: <code>employees</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | employee_id | int | | name | varchar | +-------------+---------+ employee_id is the unique identifier for this table. Each row contains information about an employee. </pre> <p>Table: <code>performance_reviews</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | review_id | int | | employee_id | int | | review_date | date | | rating | int | +-------------+------+ review_id is the unique identifier for this table. Each row represents a performance review for an employee. The rating is on a scale of 1-5 where 5 is excellent and 1 is poor. </pre> <p>Write a solution to find employees who have consistently improved their performance over <strong>their last three reviews</strong>.</p> <ul> <li>An employee must have <strong>at least </strong><code>3</code><strong> review</strong> to be considered</li> <li>The employee&#39;s <strong>last </strong><code>3</code><strong> reviews</strong> must show <strong>strictly increasing ratings</strong> (each review better than the previous)</li> <li>Use the most recent <code>3</code> reviews based on <code>review_date</code> for each employee</li> <li>Calculate the <strong>improvement score</strong> as the difference between the latest rating and the earliest rating among the last <code>3</code> reviews</li> </ul> <p>Return <em>the result table ordered by <strong>improvement score</strong> in <strong>descending</strong> order, then by <strong>name</strong> in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>employees table:</p> <pre class="example-io"> +-------------+----------------+ | employee_id | name | +-------------+----------------+ | 1 | Alice Johnson | | 2 | Bob Smith | | 3 | Carol Davis | | 4 | David Wilson | | 5 | Emma Brown | +-------------+----------------+ </pre> <p>performance_reviews table:</p> <pre class="example-io"> +-----------+-------------+-------------+--------+ | review_id | employee_id | review_date | rating | +-----------+-------------+-------------+--------+ | 1 | 1 | 2023-01-15 | 2 | | 2 | 1 | 2023-04-15 | 3 | | 3 | 1 | 2023-07-15 | 4 | | 4 | 1 | 2023-10-15 | 5 | | 5 | 2 | 2023-02-01 | 3 | | 6 | 2 | 2023-05-01 | 2 | | 7 | 2 | 2023-08-01 | 4 | | 8 | 2 | 2023-11-01 | 5 | | 9 | 3 | 2023-03-10 | 1 | | 10 | 3 | 2023-06-10 | 2 | | 11 | 3 | 2023-09-10 | 3 | | 12 | 3 | 2023-12-10 | 4 | | 13 | 4 | 2023-01-20 | 4 | | 14 | 4 | 2023-04-20 | 4 | | 15 | 4 | 2023-07-20 | 4 | | 16 | 5 | 2023-02-15 | 3 | | 17 | 5 | 2023-05-15 | 2 | +-----------+-------------+-------------+--------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+----------------+-------------------+ | employee_id | name | improvement_score | +-------------+----------------+-------------------+ | 2 | Bob Smith | 3 | | 1 | Alice Johnson | 2 | | 3 | Carol Davis | 2 | +-------------+----------------+-------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Alice Johnson (employee_id = 1):</strong> <ul> <li>Has 4 reviews with ratings: 2, 3, 4, 5</li> <li>Last 3 reviews (by date): 2023-04-15 (3), 2023-07-15 (4), 2023-10-15 (5)</li> <li>Ratings are strictly increasing: 3 &rarr; 4 &rarr; 5</li> <li>Improvement score: 5 - 3 = 2</li> </ul> </li> <li><strong>Carol Davis (employee_id = 3):</strong> <ul> <li>Has 4 reviews with ratings: 1, 2, 3, 4</li> <li>Last 3 reviews (by date): 2023-06-10 (2), 2023-09-10 (3), 2023-12-10 (4)</li> <li>Ratings are strictly increasing: 2 &rarr; 3 &rarr; 4</li> <li>Improvement score: 4 - 2 = 2</li> </ul> </li> <li><strong>Bob Smith (employee_id = 2):</strong> <ul> <li>Has 4 reviews with ratings: 3, 2, 4, 5</li> <li>Last 3 reviews (by date): 2023-05-01 (2), 2023-08-01 (4), 2023-11-01 (5)</li> <li>Ratings are strictly increasing: 2 &rarr; 4 &rarr; 5</li> <li>Improvement score: 5 - 2 = 3</li> </ul> </li> <li><strong>Employees not included:</strong> <ul> <li>David Wilson (employee_id = 4): Last 3 reviews are all 4 (no improvement)</li> <li>Emma Brown (employee_id = 5): Only has 2 reviews (needs at least 3)</li> </ul> </li> </ul> <p>The output table is ordered by improvement_score in descending order, then by name in ascending order.</p> </div>
Database
SQL
WITH recent AS ( SELECT employee_id, review_date, ROW_NUMBER() OVER ( PARTITION BY employee_id ORDER BY review_date DESC ) AS rn, ( LAG(rating) OVER ( PARTITION BY employee_id ORDER BY review_date DESC ) - rating ) AS delta FROM performance_reviews ) SELECT employee_id, name, SUM(delta) AS improvement_score FROM recent JOIN employees USING (employee_id) WHERE rn > 1 AND rn <= 3 GROUP BY 1 HAVING COUNT(*) = 2 AND MIN(delta) > 0 ORDER BY 3 DESC, 2;
3,581
Count Odd Letters from Number
Easy
<p>You are given an integer <code>n</code> perform the following steps:</p> <ul> <li>Convert each digit of <code>n</code> into its <em>lowercase English word</em> (e.g., 4 &rarr; &quot;four&quot;, 1 &rarr; &quot;one&quot;).</li> <li><strong>Concatenate</strong> those words in the <strong>original digit order</strong> to form a string <code>s</code>.</li> </ul> <p>Return the number of <strong>distinct</strong> characters in <code>s</code> that appear an <strong>odd</strong> number of times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 41</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>41 &rarr; <code>&quot;fourone&quot;</code></p> <p>Characters with odd frequencies: <code>&#39;f&#39;</code>, <code>&#39;u&#39;</code>, <code>&#39;r&#39;</code>, <code>&#39;n&#39;</code>, <code>&#39;e&#39;</code>. Thus, the answer is 5.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 20</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>20 &rarr; <code>&quot;twozero&quot;</code></p> <p>Characters with odd frequencies: <code>&#39;t&#39;</code>, <code>&#39;w&#39;</code>, <code>&#39;z&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;r&#39;</code>. Thus, the answer is 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Hash Table; String; Counting; Simulation
C++
class Solution { public: int countOddLetters(int n) { static const unordered_map<int, string> d = { {0, "zero"}, {1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}, {5, "five"}, {6, "six"}, {7, "seven"}, {8, "eight"}, {9, "nine"}}; int mask = 0; while (n > 0) { int x = n % 10; n /= 10; for (char c : d.at(x)) { mask ^= 1 << (c - 'a'); } } return __builtin_popcount(mask); } };
3,581
Count Odd Letters from Number
Easy
<p>You are given an integer <code>n</code> perform the following steps:</p> <ul> <li>Convert each digit of <code>n</code> into its <em>lowercase English word</em> (e.g., 4 &rarr; &quot;four&quot;, 1 &rarr; &quot;one&quot;).</li> <li><strong>Concatenate</strong> those words in the <strong>original digit order</strong> to form a string <code>s</code>.</li> </ul> <p>Return the number of <strong>distinct</strong> characters in <code>s</code> that appear an <strong>odd</strong> number of times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 41</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>41 &rarr; <code>&quot;fourone&quot;</code></p> <p>Characters with odd frequencies: <code>&#39;f&#39;</code>, <code>&#39;u&#39;</code>, <code>&#39;r&#39;</code>, <code>&#39;n&#39;</code>, <code>&#39;e&#39;</code>. Thus, the answer is 5.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 20</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>20 &rarr; <code>&quot;twozero&quot;</code></p> <p>Characters with odd frequencies: <code>&#39;t&#39;</code>, <code>&#39;w&#39;</code>, <code>&#39;z&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;r&#39;</code>. Thus, the answer is 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Hash Table; String; Counting; Simulation
Go
func countOddLetters(n int) int { d := map[int]string{ 0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", } mask := 0 for n > 0 { x := n % 10 n /= 10 for _, c := range d[x] { mask ^= 1 << (c - 'a') } } return bits.OnesCount32(uint32(mask)) }
3,581
Count Odd Letters from Number
Easy
<p>You are given an integer <code>n</code> perform the following steps:</p> <ul> <li>Convert each digit of <code>n</code> into its <em>lowercase English word</em> (e.g., 4 &rarr; &quot;four&quot;, 1 &rarr; &quot;one&quot;).</li> <li><strong>Concatenate</strong> those words in the <strong>original digit order</strong> to form a string <code>s</code>.</li> </ul> <p>Return the number of <strong>distinct</strong> characters in <code>s</code> that appear an <strong>odd</strong> number of times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 41</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>41 &rarr; <code>&quot;fourone&quot;</code></p> <p>Characters with odd frequencies: <code>&#39;f&#39;</code>, <code>&#39;u&#39;</code>, <code>&#39;r&#39;</code>, <code>&#39;n&#39;</code>, <code>&#39;e&#39;</code>. Thus, the answer is 5.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 20</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>20 &rarr; <code>&quot;twozero&quot;</code></p> <p>Characters with odd frequencies: <code>&#39;t&#39;</code>, <code>&#39;w&#39;</code>, <code>&#39;z&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;r&#39;</code>. Thus, the answer is 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Hash Table; String; Counting; Simulation
Java
class Solution { private static final Map<Integer, String> d = new HashMap<>(); static { d.put(0, "zero"); d.put(1, "one"); d.put(2, "two"); d.put(3, "three"); d.put(4, "four"); d.put(5, "five"); d.put(6, "six"); d.put(7, "seven"); d.put(8, "eight"); d.put(9, "nine"); } public int countOddLetters(int n) { int mask = 0; while (n > 0) { int x = n % 10; n /= 10; for (char c : d.get(x).toCharArray()) { mask ^= 1 << (c - 'a'); } } return Integer.bitCount(mask); } }
3,581
Count Odd Letters from Number
Easy
<p>You are given an integer <code>n</code> perform the following steps:</p> <ul> <li>Convert each digit of <code>n</code> into its <em>lowercase English word</em> (e.g., 4 &rarr; &quot;four&quot;, 1 &rarr; &quot;one&quot;).</li> <li><strong>Concatenate</strong> those words in the <strong>original digit order</strong> to form a string <code>s</code>.</li> </ul> <p>Return the number of <strong>distinct</strong> characters in <code>s</code> that appear an <strong>odd</strong> number of times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 41</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>41 &rarr; <code>&quot;fourone&quot;</code></p> <p>Characters with odd frequencies: <code>&#39;f&#39;</code>, <code>&#39;u&#39;</code>, <code>&#39;r&#39;</code>, <code>&#39;n&#39;</code>, <code>&#39;e&#39;</code>. Thus, the answer is 5.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 20</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>20 &rarr; <code>&quot;twozero&quot;</code></p> <p>Characters with odd frequencies: <code>&#39;t&#39;</code>, <code>&#39;w&#39;</code>, <code>&#39;z&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;r&#39;</code>. Thus, the answer is 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Hash Table; String; Counting; Simulation
Python
d = { 0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", } class Solution: def countOddLetters(self, n: int) -> int: mask = 0 while n: x = n % 10 n //= 10 for c in d[x]: mask ^= 1 << (ord(c) - ord("a")) return mask.bit_count()
3,581
Count Odd Letters from Number
Easy
<p>You are given an integer <code>n</code> perform the following steps:</p> <ul> <li>Convert each digit of <code>n</code> into its <em>lowercase English word</em> (e.g., 4 &rarr; &quot;four&quot;, 1 &rarr; &quot;one&quot;).</li> <li><strong>Concatenate</strong> those words in the <strong>original digit order</strong> to form a string <code>s</code>.</li> </ul> <p>Return the number of <strong>distinct</strong> characters in <code>s</code> that appear an <strong>odd</strong> number of times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 41</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>41 &rarr; <code>&quot;fourone&quot;</code></p> <p>Characters with odd frequencies: <code>&#39;f&#39;</code>, <code>&#39;u&#39;</code>, <code>&#39;r&#39;</code>, <code>&#39;n&#39;</code>, <code>&#39;e&#39;</code>. Thus, the answer is 5.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 20</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>20 &rarr; <code>&quot;twozero&quot;</code></p> <p>Characters with odd frequencies: <code>&#39;t&#39;</code>, <code>&#39;w&#39;</code>, <code>&#39;z&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;r&#39;</code>. Thus, the answer is 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Hash Table; String; Counting; Simulation
Rust
impl Solution { pub fn count_odd_letters(mut n: i32) -> i32 { use std::collections::HashMap; let d: HashMap<i32, &str> = [ (0, "zero"), (1, "one"), (2, "two"), (3, "three"), (4, "four"), (5, "five"), (6, "six"), (7, "seven"), (8, "eight"), (9, "nine"), ] .iter() .cloned() .collect(); let mut mask: u32 = 0; while n > 0 { let x = n % 10; n /= 10; if let Some(word) = d.get(&x) { for c in word.chars() { let bit = 1 << (c as u8 - b'a'); mask ^= bit as u32; } } } mask.count_ones() as i32 } }
3,581
Count Odd Letters from Number
Easy
<p>You are given an integer <code>n</code> perform the following steps:</p> <ul> <li>Convert each digit of <code>n</code> into its <em>lowercase English word</em> (e.g., 4 &rarr; &quot;four&quot;, 1 &rarr; &quot;one&quot;).</li> <li><strong>Concatenate</strong> those words in the <strong>original digit order</strong> to form a string <code>s</code>.</li> </ul> <p>Return the number of <strong>distinct</strong> characters in <code>s</code> that appear an <strong>odd</strong> number of times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 41</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>41 &rarr; <code>&quot;fourone&quot;</code></p> <p>Characters with odd frequencies: <code>&#39;f&#39;</code>, <code>&#39;u&#39;</code>, <code>&#39;r&#39;</code>, <code>&#39;n&#39;</code>, <code>&#39;e&#39;</code>. Thus, the answer is 5.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 20</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>20 &rarr; <code>&quot;twozero&quot;</code></p> <p>Characters with odd frequencies: <code>&#39;t&#39;</code>, <code>&#39;w&#39;</code>, <code>&#39;z&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;r&#39;</code>. Thus, the answer is 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Hash Table; String; Counting; Simulation
TypeScript
function countOddLetters(n: number): number { const d: Record<number, string> = { 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', }; let mask = 0; while (n > 0) { const x = n % 10; n = Math.floor(n / 10); for (const c of d[x]) { mask ^= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); } } return bitCount(mask); } function bitCount(i: number): number { i = i - ((i >>> 1) & 0x55555555); i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); i = (i + (i >>> 4)) & 0x0f0f0f0f; i = i + (i >>> 8); i = i + (i >>> 16); return i & 0x3f; }
3,582
Generate Tag for Video Caption
Easy
<p>You are given a string <code><font face="monospace">caption</font></code> representing the caption for a video.</p> <p>The following actions must be performed <strong>in order</strong> to generate a <strong>valid tag</strong> for the video:</p> <ol> <li> <p><strong>Combine all words</strong> in the string into a single <em>camelCase string</em> prefixed with <code>&#39;#&#39;</code>. A <em>camelCase string</em> is one where the first letter of all words <em>except</em> the first one is capitalized. All characters after the first character in <strong>each</strong> word must be lowercase.</p> </li> <li> <p><b>Remove</b> all characters that are not an English letter, <strong>except</strong> the first <code>&#39;#&#39;</code>.</p> </li> <li> <p><strong>Truncate</strong> the result to a maximum of 100 characters.</p> </li> </ol> <p>Return the <strong>tag</strong> after performing the actions on <code>caption</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">caption = &quot;Leetcode daily streak achieved&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#leetcodeDailyStreakAchieved&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The first letter for all words except <code>&quot;leetcode&quot;</code> should be capitalized.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">caption = &quot;can I Go There&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#canIGoThere&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The first letter for all words except <code>&quot;can&quot;</code> should be capitalized.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">caption = &quot;hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Since the first word has length 101, we need to truncate the last two letters from the word.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= caption.length &lt;= 150</code></li> <li><code>caption</code> consists only of English letters and <code>&#39; &#39;</code>.</li> </ul>
String; Simulation
C++
class Solution { public: string generateTag(string caption) { istringstream iss(caption); string word; ostringstream oss; oss << "#"; bool first = true; while (iss >> word) { transform(word.begin(), word.end(), word.begin(), ::tolower); if (first) { oss << word; first = false; } else { word[0] = toupper(word[0]); oss << word; } if (oss.str().length() >= 100) { break; } } string ans = oss.str(); if (ans.length() > 100) { ans = ans.substr(0, 100); } return ans; } };
3,582
Generate Tag for Video Caption
Easy
<p>You are given a string <code><font face="monospace">caption</font></code> representing the caption for a video.</p> <p>The following actions must be performed <strong>in order</strong> to generate a <strong>valid tag</strong> for the video:</p> <ol> <li> <p><strong>Combine all words</strong> in the string into a single <em>camelCase string</em> prefixed with <code>&#39;#&#39;</code>. A <em>camelCase string</em> is one where the first letter of all words <em>except</em> the first one is capitalized. All characters after the first character in <strong>each</strong> word must be lowercase.</p> </li> <li> <p><b>Remove</b> all characters that are not an English letter, <strong>except</strong> the first <code>&#39;#&#39;</code>.</p> </li> <li> <p><strong>Truncate</strong> the result to a maximum of 100 characters.</p> </li> </ol> <p>Return the <strong>tag</strong> after performing the actions on <code>caption</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">caption = &quot;Leetcode daily streak achieved&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#leetcodeDailyStreakAchieved&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The first letter for all words except <code>&quot;leetcode&quot;</code> should be capitalized.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">caption = &quot;can I Go There&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#canIGoThere&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The first letter for all words except <code>&quot;can&quot;</code> should be capitalized.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">caption = &quot;hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Since the first word has length 101, we need to truncate the last two letters from the word.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= caption.length &lt;= 150</code></li> <li><code>caption</code> consists only of English letters and <code>&#39; &#39;</code>.</li> </ul>
String; Simulation
Go
func generateTag(caption string) string { words := strings.Fields(caption) var builder strings.Builder builder.WriteString("#") for i, word := range words { word = strings.ToLower(word) if i == 0 { builder.WriteString(word) } else { runes := []rune(word) if len(runes) > 0 { runes[0] = unicode.ToUpper(runes[0]) } builder.WriteString(string(runes)) } if builder.Len() >= 100 { break } } ans := builder.String() if len(ans) > 100 { ans = ans[:100] } return ans }
3,582
Generate Tag for Video Caption
Easy
<p>You are given a string <code><font face="monospace">caption</font></code> representing the caption for a video.</p> <p>The following actions must be performed <strong>in order</strong> to generate a <strong>valid tag</strong> for the video:</p> <ol> <li> <p><strong>Combine all words</strong> in the string into a single <em>camelCase string</em> prefixed with <code>&#39;#&#39;</code>. A <em>camelCase string</em> is one where the first letter of all words <em>except</em> the first one is capitalized. All characters after the first character in <strong>each</strong> word must be lowercase.</p> </li> <li> <p><b>Remove</b> all characters that are not an English letter, <strong>except</strong> the first <code>&#39;#&#39;</code>.</p> </li> <li> <p><strong>Truncate</strong> the result to a maximum of 100 characters.</p> </li> </ol> <p>Return the <strong>tag</strong> after performing the actions on <code>caption</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">caption = &quot;Leetcode daily streak achieved&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#leetcodeDailyStreakAchieved&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The first letter for all words except <code>&quot;leetcode&quot;</code> should be capitalized.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">caption = &quot;can I Go There&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#canIGoThere&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The first letter for all words except <code>&quot;can&quot;</code> should be capitalized.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">caption = &quot;hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Since the first word has length 101, we need to truncate the last two letters from the word.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= caption.length &lt;= 150</code></li> <li><code>caption</code> consists only of English letters and <code>&#39; &#39;</code>.</li> </ul>
String; Simulation
Java
class Solution { public String generateTag(String caption) { String[] words = caption.trim().split("\\s+"); StringBuilder sb = new StringBuilder("#"); for (int i = 0; i < words.length; i++) { String word = words[i]; if (word.isEmpty()) { continue; } word = word.toLowerCase(); if (i == 0) { sb.append(word); } else { sb.append(Character.toUpperCase(word.charAt(0))); if (word.length() > 1) { sb.append(word.substring(1)); } } if (sb.length() >= 100) { break; } } return sb.length() > 100 ? sb.substring(0, 100) : sb.toString(); } }
3,582
Generate Tag for Video Caption
Easy
<p>You are given a string <code><font face="monospace">caption</font></code> representing the caption for a video.</p> <p>The following actions must be performed <strong>in order</strong> to generate a <strong>valid tag</strong> for the video:</p> <ol> <li> <p><strong>Combine all words</strong> in the string into a single <em>camelCase string</em> prefixed with <code>&#39;#&#39;</code>. A <em>camelCase string</em> is one where the first letter of all words <em>except</em> the first one is capitalized. All characters after the first character in <strong>each</strong> word must be lowercase.</p> </li> <li> <p><b>Remove</b> all characters that are not an English letter, <strong>except</strong> the first <code>&#39;#&#39;</code>.</p> </li> <li> <p><strong>Truncate</strong> the result to a maximum of 100 characters.</p> </li> </ol> <p>Return the <strong>tag</strong> after performing the actions on <code>caption</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">caption = &quot;Leetcode daily streak achieved&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#leetcodeDailyStreakAchieved&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The first letter for all words except <code>&quot;leetcode&quot;</code> should be capitalized.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">caption = &quot;can I Go There&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#canIGoThere&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The first letter for all words except <code>&quot;can&quot;</code> should be capitalized.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">caption = &quot;hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Since the first word has length 101, we need to truncate the last two letters from the word.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= caption.length &lt;= 150</code></li> <li><code>caption</code> consists only of English letters and <code>&#39; &#39;</code>.</li> </ul>
String; Simulation
Python
class Solution: def generateTag(self, caption: str) -> str: words = [s.capitalize() for s in caption.split()] if words: words[0] = words[0].lower() return "#" + "".join(words)[:99]
3,582
Generate Tag for Video Caption
Easy
<p>You are given a string <code><font face="monospace">caption</font></code> representing the caption for a video.</p> <p>The following actions must be performed <strong>in order</strong> to generate a <strong>valid tag</strong> for the video:</p> <ol> <li> <p><strong>Combine all words</strong> in the string into a single <em>camelCase string</em> prefixed with <code>&#39;#&#39;</code>. A <em>camelCase string</em> is one where the first letter of all words <em>except</em> the first one is capitalized. All characters after the first character in <strong>each</strong> word must be lowercase.</p> </li> <li> <p><b>Remove</b> all characters that are not an English letter, <strong>except</strong> the first <code>&#39;#&#39;</code>.</p> </li> <li> <p><strong>Truncate</strong> the result to a maximum of 100 characters.</p> </li> </ol> <p>Return the <strong>tag</strong> after performing the actions on <code>caption</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">caption = &quot;Leetcode daily streak achieved&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#leetcodeDailyStreakAchieved&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The first letter for all words except <code>&quot;leetcode&quot;</code> should be capitalized.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">caption = &quot;can I Go There&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#canIGoThere&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The first letter for all words except <code>&quot;can&quot;</code> should be capitalized.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">caption = &quot;hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;#hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Since the first word has length 101, we need to truncate the last two letters from the word.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= caption.length &lt;= 150</code></li> <li><code>caption</code> consists only of English letters and <code>&#39; &#39;</code>.</li> </ul>
String; Simulation
TypeScript
function generateTag(caption: string): string { const words = caption.trim().split(/\s+/); let ans = '#'; for (let i = 0; i < words.length; i++) { const word = words[i].toLowerCase(); if (i === 0) { ans += word; } else { ans += word.charAt(0).toUpperCase() + word.slice(1); } if (ans.length >= 100) { ans = ans.slice(0, 100); break; } } return ans; }
3,583
Count Special Triplets
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>A <strong>special triplet</strong> is defined as a triplet of indices <code>(i, j, k)</code> such that:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; k &lt; n</code>, where <code>n = nums.length</code></li> <li><code>nums[i] == nums[j] * 2</code></li> <li><code>nums[k] == nums[j] * 2</code></li> </ul> <p>Return the total number of <strong>special triplets</strong> in the array.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [6,3,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only special triplet is <code>(i, j, k) = (0, 1, 2)</code>, where:</p> <ul> <li><code>nums[0] = 6</code>, <code>nums[1] = 3</code>, <code>nums[2] = 6</code></li> <li><code>nums[0] = nums[1] * 2 = 3 * 2 = 6</code></li> <li><code>nums[2] = nums[1] * 2 = 3 * 2 = 6</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only special triplet is <code>(i, j, k) = (0, 2, 3)</code>, where:</p> <ul> <li><code>nums[0] = 0</code>, <code>nums[2] = 0</code>, <code>nums[3] = 0</code></li> <li><code>nums[0] = nums[2] * 2 = 0 * 2 = 0</code></li> <li><code>nums[3] = nums[2] * 2 = 0 * 2 = 0</code></li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,4,2,8,4]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>There are exactly two special triplets:</p> <ul> <li><code>(i, j, k) = (0, 1, 3)</code> <ul> <li><code>nums[0] = 8</code>, <code>nums[1] = 4</code>, <code>nums[3] = 8</code></li> <li><code>nums[0] = nums[1] * 2 = 4 * 2 = 8</code></li> <li><code>nums[3] = nums[1] * 2 = 4 * 2 = 8</code></li> </ul> </li> <li><code>(i, j, k) = (1, 2, 4)</code> <ul> <li><code>nums[1] = 4</code>, <code>nums[2] = 2</code>, <code>nums[4] = 4</code></li> <li><code>nums[1] = nums[2] * 2 = 2 * 2 = 4</code></li> <li><code>nums[4] = nums[2] * 2 = 2 * 2 = 4</code></li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Counting
C++
class Solution { public: int specialTriplets(vector<int>& nums) { unordered_map<int, int> left, right; for (int x : nums) { right[x]++; } long long ans = 0; const int mod = 1e9 + 7; for (int x : nums) { right[x]--; ans = (ans + 1LL * left[x * 2] * right[x * 2] % mod) % mod; left[x]++; } return (int) ans; } };
3,583
Count Special Triplets
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>A <strong>special triplet</strong> is defined as a triplet of indices <code>(i, j, k)</code> such that:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; k &lt; n</code>, where <code>n = nums.length</code></li> <li><code>nums[i] == nums[j] * 2</code></li> <li><code>nums[k] == nums[j] * 2</code></li> </ul> <p>Return the total number of <strong>special triplets</strong> in the array.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [6,3,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only special triplet is <code>(i, j, k) = (0, 1, 2)</code>, where:</p> <ul> <li><code>nums[0] = 6</code>, <code>nums[1] = 3</code>, <code>nums[2] = 6</code></li> <li><code>nums[0] = nums[1] * 2 = 3 * 2 = 6</code></li> <li><code>nums[2] = nums[1] * 2 = 3 * 2 = 6</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only special triplet is <code>(i, j, k) = (0, 2, 3)</code>, where:</p> <ul> <li><code>nums[0] = 0</code>, <code>nums[2] = 0</code>, <code>nums[3] = 0</code></li> <li><code>nums[0] = nums[2] * 2 = 0 * 2 = 0</code></li> <li><code>nums[3] = nums[2] * 2 = 0 * 2 = 0</code></li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,4,2,8,4]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>There are exactly two special triplets:</p> <ul> <li><code>(i, j, k) = (0, 1, 3)</code> <ul> <li><code>nums[0] = 8</code>, <code>nums[1] = 4</code>, <code>nums[3] = 8</code></li> <li><code>nums[0] = nums[1] * 2 = 4 * 2 = 8</code></li> <li><code>nums[3] = nums[1] * 2 = 4 * 2 = 8</code></li> </ul> </li> <li><code>(i, j, k) = (1, 2, 4)</code> <ul> <li><code>nums[1] = 4</code>, <code>nums[2] = 2</code>, <code>nums[4] = 4</code></li> <li><code>nums[1] = nums[2] * 2 = 2 * 2 = 4</code></li> <li><code>nums[4] = nums[2] * 2 = 2 * 2 = 4</code></li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Counting
Go
func specialTriplets(nums []int) int { left := make(map[int]int) right := make(map[int]int) for _, x := range nums { right[x]++ } ans := int64(0) mod := int64(1e9 + 7) for _, x := range nums { right[x]-- ans = (ans + int64(left[x*2])*int64(right[x*2])%mod) % mod left[x]++ } return int(ans) }
3,583
Count Special Triplets
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>A <strong>special triplet</strong> is defined as a triplet of indices <code>(i, j, k)</code> such that:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; k &lt; n</code>, where <code>n = nums.length</code></li> <li><code>nums[i] == nums[j] * 2</code></li> <li><code>nums[k] == nums[j] * 2</code></li> </ul> <p>Return the total number of <strong>special triplets</strong> in the array.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [6,3,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only special triplet is <code>(i, j, k) = (0, 1, 2)</code>, where:</p> <ul> <li><code>nums[0] = 6</code>, <code>nums[1] = 3</code>, <code>nums[2] = 6</code></li> <li><code>nums[0] = nums[1] * 2 = 3 * 2 = 6</code></li> <li><code>nums[2] = nums[1] * 2 = 3 * 2 = 6</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only special triplet is <code>(i, j, k) = (0, 2, 3)</code>, where:</p> <ul> <li><code>nums[0] = 0</code>, <code>nums[2] = 0</code>, <code>nums[3] = 0</code></li> <li><code>nums[0] = nums[2] * 2 = 0 * 2 = 0</code></li> <li><code>nums[3] = nums[2] * 2 = 0 * 2 = 0</code></li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,4,2,8,4]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>There are exactly two special triplets:</p> <ul> <li><code>(i, j, k) = (0, 1, 3)</code> <ul> <li><code>nums[0] = 8</code>, <code>nums[1] = 4</code>, <code>nums[3] = 8</code></li> <li><code>nums[0] = nums[1] * 2 = 4 * 2 = 8</code></li> <li><code>nums[3] = nums[1] * 2 = 4 * 2 = 8</code></li> </ul> </li> <li><code>(i, j, k) = (1, 2, 4)</code> <ul> <li><code>nums[1] = 4</code>, <code>nums[2] = 2</code>, <code>nums[4] = 4</code></li> <li><code>nums[1] = nums[2] * 2 = 2 * 2 = 4</code></li> <li><code>nums[4] = nums[2] * 2 = 2 * 2 = 4</code></li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Counting
Java
class Solution { public int specialTriplets(int[] nums) { Map<Integer, Integer> left = new HashMap<>(); Map<Integer, Integer> right = new HashMap<>(); for (int x : nums) { right.merge(x, 1, Integer::sum); } long ans = 0; final int mod = (int) 1e9 + 7; for (int x : nums) { right.merge(x, -1, Integer::sum); ans = (ans + 1L * left.getOrDefault(x * 2, 0) * right.getOrDefault(x * 2, 0) % mod) % mod; left.merge(x, 1, Integer::sum); } return (int) ans; } }
3,583
Count Special Triplets
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>A <strong>special triplet</strong> is defined as a triplet of indices <code>(i, j, k)</code> such that:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; k &lt; n</code>, where <code>n = nums.length</code></li> <li><code>nums[i] == nums[j] * 2</code></li> <li><code>nums[k] == nums[j] * 2</code></li> </ul> <p>Return the total number of <strong>special triplets</strong> in the array.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [6,3,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only special triplet is <code>(i, j, k) = (0, 1, 2)</code>, where:</p> <ul> <li><code>nums[0] = 6</code>, <code>nums[1] = 3</code>, <code>nums[2] = 6</code></li> <li><code>nums[0] = nums[1] * 2 = 3 * 2 = 6</code></li> <li><code>nums[2] = nums[1] * 2 = 3 * 2 = 6</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only special triplet is <code>(i, j, k) = (0, 2, 3)</code>, where:</p> <ul> <li><code>nums[0] = 0</code>, <code>nums[2] = 0</code>, <code>nums[3] = 0</code></li> <li><code>nums[0] = nums[2] * 2 = 0 * 2 = 0</code></li> <li><code>nums[3] = nums[2] * 2 = 0 * 2 = 0</code></li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,4,2,8,4]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>There are exactly two special triplets:</p> <ul> <li><code>(i, j, k) = (0, 1, 3)</code> <ul> <li><code>nums[0] = 8</code>, <code>nums[1] = 4</code>, <code>nums[3] = 8</code></li> <li><code>nums[0] = nums[1] * 2 = 4 * 2 = 8</code></li> <li><code>nums[3] = nums[1] * 2 = 4 * 2 = 8</code></li> </ul> </li> <li><code>(i, j, k) = (1, 2, 4)</code> <ul> <li><code>nums[1] = 4</code>, <code>nums[2] = 2</code>, <code>nums[4] = 4</code></li> <li><code>nums[1] = nums[2] * 2 = 2 * 2 = 4</code></li> <li><code>nums[4] = nums[2] * 2 = 2 * 2 = 4</code></li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Counting
Python
class Solution: def specialTriplets(self, nums: List[int]) -> int: left = Counter() right = Counter(nums) ans = 0 mod = 10**9 + 7 for x in nums: right[x] -= 1 ans = (ans + left[x * 2] * right[x * 2] % mod) % mod left[x] += 1 return ans
3,583
Count Special Triplets
Medium
<p>You are given an integer array <code>nums</code>.</p> <p>A <strong>special triplet</strong> is defined as a triplet of indices <code>(i, j, k)</code> such that:</p> <ul> <li><code>0 &lt;= i &lt; j &lt; k &lt; n</code>, where <code>n = nums.length</code></li> <li><code>nums[i] == nums[j] * 2</code></li> <li><code>nums[k] == nums[j] * 2</code></li> </ul> <p>Return the total number of <strong>special triplets</strong> in the array.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [6,3,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only special triplet is <code>(i, j, k) = (0, 1, 2)</code>, where:</p> <ul> <li><code>nums[0] = 6</code>, <code>nums[1] = 3</code>, <code>nums[2] = 6</code></li> <li><code>nums[0] = nums[1] * 2 = 3 * 2 = 6</code></li> <li><code>nums[2] = nums[1] * 2 = 3 * 2 = 6</code></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only special triplet is <code>(i, j, k) = (0, 2, 3)</code>, where:</p> <ul> <li><code>nums[0] = 0</code>, <code>nums[2] = 0</code>, <code>nums[3] = 0</code></li> <li><code>nums[0] = nums[2] * 2 = 0 * 2 = 0</code></li> <li><code>nums[3] = nums[2] * 2 = 0 * 2 = 0</code></li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [8,4,2,8,4]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>There are exactly two special triplets:</p> <ul> <li><code>(i, j, k) = (0, 1, 3)</code> <ul> <li><code>nums[0] = 8</code>, <code>nums[1] = 4</code>, <code>nums[3] = 8</code></li> <li><code>nums[0] = nums[1] * 2 = 4 * 2 = 8</code></li> <li><code>nums[3] = nums[1] * 2 = 4 * 2 = 8</code></li> </ul> </li> <li><code>(i, j, k) = (1, 2, 4)</code> <ul> <li><code>nums[1] = 4</code>, <code>nums[2] = 2</code>, <code>nums[4] = 4</code></li> <li><code>nums[1] = nums[2] * 2 = 2 * 2 = 4</code></li> <li><code>nums[4] = nums[2] * 2 = 2 * 2 = 4</code></li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n == nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Counting
TypeScript
function specialTriplets(nums: number[]): number { const left = new Map<number, number>(); const right = new Map<number, number>(); for (const x of nums) { right.set(x, (right.get(x) || 0) + 1); } let ans = 0; const mod = 1e9 + 7; for (const x of nums) { right.set(x, (right.get(x) || 0) - 1); const lx = left.get(x * 2) || 0; const rx = right.get(x * 2) || 0; ans = (ans + ((lx * rx) % mod)) % mod; left.set(x, (left.get(x) || 0) + 1); } return ans; }
3,584
Maximum Product of First and Last Elements of a Subsequence
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>m</code>.</p> <p>Return the <strong>maximum</strong> product of the first and last elements of any <strong><span data-keyword="subsequence-array">subsequence</span></strong> of <code>nums</code> of size <code>m</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">nums = [-1,-9,2,3,-2,-3,1], m = 1</span></p> <p><strong>Output:</strong> <span class="example-io">81</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[-9]</code> has the largest product of the first and last elements: <code>-9 * -9 = 81</code>. Therefore, the answer is 81.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,-5,5,6,-4], m = 3</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[-5, 6, -4]</code> has the largest product of the first and last elements.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,-1,2,-6,5,2,-5,7], m = 2</span></p> <p><strong>Output:</strong> <span class="example-io">35</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[5, 7]</code> has the largest product of the first and last elements.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m &lt;= nums.length</code></li> </ul>
Array; Two Pointers
C++
class Solution { public: long long maximumProduct(vector<int>& nums, int m) { long long ans = LLONG_MIN; int mx = INT_MIN; int mi = INT_MAX; for (int i = m - 1; i < nums.size(); ++i) { int x = nums[i]; int y = nums[i - m + 1]; mi = min(mi, y); mx = max(mx, y); ans = max(ans, max(1LL * x * mi, 1LL * x * mx)); } return ans; } };
3,584
Maximum Product of First and Last Elements of a Subsequence
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>m</code>.</p> <p>Return the <strong>maximum</strong> product of the first and last elements of any <strong><span data-keyword="subsequence-array">subsequence</span></strong> of <code>nums</code> of size <code>m</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">nums = [-1,-9,2,3,-2,-3,1], m = 1</span></p> <p><strong>Output:</strong> <span class="example-io">81</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[-9]</code> has the largest product of the first and last elements: <code>-9 * -9 = 81</code>. Therefore, the answer is 81.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,-5,5,6,-4], m = 3</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[-5, 6, -4]</code> has the largest product of the first and last elements.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,-1,2,-6,5,2,-5,7], m = 2</span></p> <p><strong>Output:</strong> <span class="example-io">35</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[5, 7]</code> has the largest product of the first and last elements.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m &lt;= nums.length</code></li> </ul>
Array; Two Pointers
Go
func maximumProduct(nums []int, m int) int64 { ans := int64(math.MinInt64) mx := math.MinInt32 mi := math.MaxInt32 for i := m - 1; i < len(nums); i++ { x := nums[i] y := nums[i-m+1] mi = min(mi, y) mx = max(mx, y) ans = max(ans, max(int64(x)*int64(mi), int64(x)*int64(mx))) } return ans }
3,584
Maximum Product of First and Last Elements of a Subsequence
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>m</code>.</p> <p>Return the <strong>maximum</strong> product of the first and last elements of any <strong><span data-keyword="subsequence-array">subsequence</span></strong> of <code>nums</code> of size <code>m</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">nums = [-1,-9,2,3,-2,-3,1], m = 1</span></p> <p><strong>Output:</strong> <span class="example-io">81</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[-9]</code> has the largest product of the first and last elements: <code>-9 * -9 = 81</code>. Therefore, the answer is 81.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,-5,5,6,-4], m = 3</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[-5, 6, -4]</code> has the largest product of the first and last elements.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,-1,2,-6,5,2,-5,7], m = 2</span></p> <p><strong>Output:</strong> <span class="example-io">35</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[5, 7]</code> has the largest product of the first and last elements.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m &lt;= nums.length</code></li> </ul>
Array; Two Pointers
Java
class Solution { public long maximumProduct(int[] nums, int m) { long ans = Long.MIN_VALUE; int mx = Integer.MIN_VALUE; int mi = Integer.MAX_VALUE; for (int i = m - 1; i < nums.length; ++i) { int x = nums[i]; int y = nums[i - m + 1]; mi = Math.min(mi, y); mx = Math.max(mx, y); ans = Math.max(ans, Math.max(1L * x * mi, 1L * x * mx)); } return ans; } }
3,584
Maximum Product of First and Last Elements of a Subsequence
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>m</code>.</p> <p>Return the <strong>maximum</strong> product of the first and last elements of any <strong><span data-keyword="subsequence-array">subsequence</span></strong> of <code>nums</code> of size <code>m</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">nums = [-1,-9,2,3,-2,-3,1], m = 1</span></p> <p><strong>Output:</strong> <span class="example-io">81</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[-9]</code> has the largest product of the first and last elements: <code>-9 * -9 = 81</code>. Therefore, the answer is 81.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,-5,5,6,-4], m = 3</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[-5, 6, -4]</code> has the largest product of the first and last elements.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,-1,2,-6,5,2,-5,7], m = 2</span></p> <p><strong>Output:</strong> <span class="example-io">35</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[5, 7]</code> has the largest product of the first and last elements.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m &lt;= nums.length</code></li> </ul>
Array; Two Pointers
Python
class Solution: def maximumProduct(self, nums: List[int], m: int) -> int: ans = mx = -inf mi = inf for i in range(m - 1, len(nums)): x = nums[i] y = nums[i - m + 1] mi = min(mi, y) mx = max(mx, y) ans = max(ans, x * mi, x * mx) return ans
3,584
Maximum Product of First and Last Elements of a Subsequence
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>m</code>.</p> <p>Return the <strong>maximum</strong> product of the first and last elements of any <strong><span data-keyword="subsequence-array">subsequence</span></strong> of <code>nums</code> of size <code>m</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">nums = [-1,-9,2,3,-2,-3,1], m = 1</span></p> <p><strong>Output:</strong> <span class="example-io">81</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[-9]</code> has the largest product of the first and last elements: <code>-9 * -9 = 81</code>. Therefore, the answer is 81.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,-5,5,6,-4], m = 3</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[-5, 6, -4]</code> has the largest product of the first and last elements.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,-1,2,-6,5,2,-5,7], m = 2</span></p> <p><strong>Output:</strong> <span class="example-io">35</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[5, 7]</code> has the largest product of the first and last elements.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m &lt;= nums.length</code></li> </ul>
Array; Two Pointers
TypeScript
function maximumProduct(nums: number[], m: number): number { let ans = Number.MIN_SAFE_INTEGER; let mx = Number.MIN_SAFE_INTEGER; let mi = Number.MAX_SAFE_INTEGER; for (let i = m - 1; i < nums.length; i++) { const x = nums[i]; const y = nums[i - m + 1]; mi = Math.min(mi, y); mx = Math.max(mx, y); ans = Math.max(ans, x * mi, x * mx); } return ans; }
3,586
Find COVID Recovery Patients
Medium
<p>Table: <code>patients</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | patient_id | int | | patient_name| varchar | | age | int | +-------------+---------+ patient_id is the unique identifier for this table. Each row contains information about a patient. </pre> <p>Table: <code>covid_tests</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | test_id | int | | patient_id | int | | test_date | date | | result | varchar | +-------------+---------+ test_id is the unique identifier for this table. Each row represents a COVID test result. The result can be Positive, Negative, or Inconclusive. </pre> <p>Write a solution to find patients who have <strong>recovered from COVID</strong> - patients who tested positive but later tested negative.</p> <ul> <li>A patient is considered recovered if they have <strong>at least one</strong> <strong>Positive</strong> test followed by at least one <strong>Negative</strong> test on a <strong>later date</strong></li> <li>Calculate the <strong>recovery time</strong> in days as the <strong>difference</strong> between the <strong>first positive test</strong> and the <strong>first negative test</strong> after that <strong>positive test</strong></li> <li><strong>Only include</strong> patients who have both positive and negative test results</li> </ul> <p>Return <em>the result table ordered by </em><code>recovery_time</code><em> in <strong>ascending</strong> order, then by </em><code>patient_name</code><em> in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>patients table:</p> <pre class="example-io"> +------------+--------------+-----+ | patient_id | patient_name | age | +------------+--------------+-----+ | 1 | Alice Smith | 28 | | 2 | Bob Johnson | 35 | | 3 | Carol Davis | 42 | | 4 | David Wilson | 31 | | 5 | Emma Brown | 29 | +------------+--------------+-----+ </pre> <p>covid_tests table:</p> <pre class="example-io"> +---------+------------+------------+--------------+ | test_id | patient_id | test_date | result | +---------+------------+------------+--------------+ | 1 | 1 | 2023-01-15 | Positive | | 2 | 1 | 2023-01-25 | Negative | | 3 | 2 | 2023-02-01 | Positive | | 4 | 2 | 2023-02-05 | Inconclusive | | 5 | 2 | 2023-02-12 | Negative | | 6 | 3 | 2023-01-20 | Negative | | 7 | 3 | 2023-02-10 | Positive | | 8 | 3 | 2023-02-20 | Negative | | 9 | 4 | 2023-01-10 | Positive | | 10 | 4 | 2023-01-18 | Positive | | 11 | 5 | 2023-02-15 | Negative | | 12 | 5 | 2023-02-20 | Negative | +---------+------------+------------+--------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------+--------------+-----+---------------+ | patient_id | patient_name | age | recovery_time | +------------+--------------+-----+---------------+ | 1 | Alice Smith | 28 | 10 | | 3 | Carol Davis | 42 | 10 | | 2 | Bob Johnson | 35 | 11 | +------------+--------------+-----+---------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Alice Smith (patient_id = 1):</strong> <ul> <li>First positive test: 2023-01-15</li> <li>First negative test after positive: 2023-01-25</li> <li>Recovery time: 25 - 15 = 10 days</li> </ul> </li> <li><strong>Bob Johnson (patient_id = 2):</strong> <ul> <li>First positive test: 2023-02-01</li> <li>Inconclusive test on 2023-02-05 (ignored for recovery calculation)</li> <li>First negative test after positive: 2023-02-12</li> <li>Recovery time: 12 - 1 = 11 days</li> </ul> </li> <li><strong>Carol Davis (patient_id = 3):</strong> <ul> <li>Had negative test on 2023-01-20 (before positive test)</li> <li>First positive test: 2023-02-10</li> <li>First negative test after positive: 2023-02-20</li> <li>Recovery time: 20 - 10 = 10 days</li> </ul> </li> <li><strong>Patients not included:</strong> <ul> <li>David Wilson (patient_id = 4): Only has positive tests, no negative test after positive</li> <li>Emma Brown (patient_id = 5): Only has negative tests, never tested positive</li> </ul> </li> </ul> <p>Output table is ordered by recovery_time in ascending order, and then by patient_name in ascending order.</p> </div>
Database
Python
import pandas as pd def find_covid_recovery_patients( patients: pd.DataFrame, covid_tests: pd.DataFrame ) -> pd.DataFrame: covid_tests["test_date"] = pd.to_datetime(covid_tests["test_date"]) pos = ( covid_tests[covid_tests["result"] == "Positive"] .groupby("patient_id", as_index=False)["test_date"] .min() ) pos.rename(columns={"test_date": "first_positive_date"}, inplace=True) neg = covid_tests.merge(pos, on="patient_id") neg = neg[ (neg["result"] == "Negative") & (neg["test_date"] > neg["first_positive_date"]) ] neg = neg.groupby("patient_id", as_index=False)["test_date"].min() neg.rename(columns={"test_date": "first_negative_date"}, inplace=True) df = pos.merge(neg, on="patient_id") df["recovery_time"] = ( df["first_negative_date"] - df["first_positive_date"] ).dt.days out = df.merge(patients, on="patient_id")[ ["patient_id", "patient_name", "age", "recovery_time"] ] return out.sort_values(by=["recovery_time", "patient_name"]).reset_index(drop=True)
3,586
Find COVID Recovery Patients
Medium
<p>Table: <code>patients</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | patient_id | int | | patient_name| varchar | | age | int | +-------------+---------+ patient_id is the unique identifier for this table. Each row contains information about a patient. </pre> <p>Table: <code>covid_tests</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | test_id | int | | patient_id | int | | test_date | date | | result | varchar | +-------------+---------+ test_id is the unique identifier for this table. Each row represents a COVID test result. The result can be Positive, Negative, or Inconclusive. </pre> <p>Write a solution to find patients who have <strong>recovered from COVID</strong> - patients who tested positive but later tested negative.</p> <ul> <li>A patient is considered recovered if they have <strong>at least one</strong> <strong>Positive</strong> test followed by at least one <strong>Negative</strong> test on a <strong>later date</strong></li> <li>Calculate the <strong>recovery time</strong> in days as the <strong>difference</strong> between the <strong>first positive test</strong> and the <strong>first negative test</strong> after that <strong>positive test</strong></li> <li><strong>Only include</strong> patients who have both positive and negative test results</li> </ul> <p>Return <em>the result table ordered by </em><code>recovery_time</code><em> in <strong>ascending</strong> order, then by </em><code>patient_name</code><em> in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>patients table:</p> <pre class="example-io"> +------------+--------------+-----+ | patient_id | patient_name | age | +------------+--------------+-----+ | 1 | Alice Smith | 28 | | 2 | Bob Johnson | 35 | | 3 | Carol Davis | 42 | | 4 | David Wilson | 31 | | 5 | Emma Brown | 29 | +------------+--------------+-----+ </pre> <p>covid_tests table:</p> <pre class="example-io"> +---------+------------+------------+--------------+ | test_id | patient_id | test_date | result | +---------+------------+------------+--------------+ | 1 | 1 | 2023-01-15 | Positive | | 2 | 1 | 2023-01-25 | Negative | | 3 | 2 | 2023-02-01 | Positive | | 4 | 2 | 2023-02-05 | Inconclusive | | 5 | 2 | 2023-02-12 | Negative | | 6 | 3 | 2023-01-20 | Negative | | 7 | 3 | 2023-02-10 | Positive | | 8 | 3 | 2023-02-20 | Negative | | 9 | 4 | 2023-01-10 | Positive | | 10 | 4 | 2023-01-18 | Positive | | 11 | 5 | 2023-02-15 | Negative | | 12 | 5 | 2023-02-20 | Negative | +---------+------------+------------+--------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------+--------------+-----+---------------+ | patient_id | patient_name | age | recovery_time | +------------+--------------+-----+---------------+ | 1 | Alice Smith | 28 | 10 | | 3 | Carol Davis | 42 | 10 | | 2 | Bob Johnson | 35 | 11 | +------------+--------------+-----+---------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Alice Smith (patient_id = 1):</strong> <ul> <li>First positive test: 2023-01-15</li> <li>First negative test after positive: 2023-01-25</li> <li>Recovery time: 25 - 15 = 10 days</li> </ul> </li> <li><strong>Bob Johnson (patient_id = 2):</strong> <ul> <li>First positive test: 2023-02-01</li> <li>Inconclusive test on 2023-02-05 (ignored for recovery calculation)</li> <li>First negative test after positive: 2023-02-12</li> <li>Recovery time: 12 - 1 = 11 days</li> </ul> </li> <li><strong>Carol Davis (patient_id = 3):</strong> <ul> <li>Had negative test on 2023-01-20 (before positive test)</li> <li>First positive test: 2023-02-10</li> <li>First negative test after positive: 2023-02-20</li> <li>Recovery time: 20 - 10 = 10 days</li> </ul> </li> <li><strong>Patients not included:</strong> <ul> <li>David Wilson (patient_id = 4): Only has positive tests, no negative test after positive</li> <li>Emma Brown (patient_id = 5): Only has negative tests, never tested positive</li> </ul> </li> </ul> <p>Output table is ordered by recovery_time in ascending order, and then by patient_name in ascending order.</p> </div>
Database
SQL
# Write your MySQL query statement below WITH first_positive AS ( SELECT patient_id, MIN(test_date) AS first_positive_date FROM covid_tests WHERE result = 'Positive' GROUP BY patient_id ), first_negative_after_positive AS ( SELECT t.patient_id, MIN(t.test_date) AS first_negative_date FROM covid_tests t JOIN first_positive p ON t.patient_id = p.patient_id AND t.test_date > p.first_positive_date WHERE t.result = 'Negative' GROUP BY t.patient_id ) SELECT p.patient_id, p.patient_name, p.age, DATEDIFF(n.first_negative_date, f.first_positive_date) AS recovery_time FROM first_positive f JOIN first_negative_after_positive n ON f.patient_id = n.patient_id JOIN patients p ON p.patient_id = f.patient_id ORDER BY recovery_time ASC, patient_name ASC;
3,587
Minimum Adjacent Swaps to Alternate Parity
Medium
<p>You are given an array <code>nums</code> of <strong>distinct</strong> integers.</p> <p>In one operation, you can swap any two <strong>adjacent</strong> elements in the array.</p> <p>An arrangement of the array is considered <strong>valid</strong> if the parity of adjacent elements <strong>alternates</strong>, meaning every pair of neighboring elements consists of one even and one odd number.</p> <p>Return the <strong>minimum</strong> number of adjacent swaps required to transform <code>nums</code> into any valid arrangement.</p> <p>If it is impossible to rearrange <code>nums</code> such that no two adjacent elements have the same parity, return <code>-1</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">nums = [2,4,6,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Swapping 5 and 6, the array becomes <code>[2,4,5,6,7]</code></p> <p>Swapping 5 and 4, the array becomes <code>[2,5,4,6,7]</code></p> <p>Swapping 6 and 7, the array becomes <code>[2,5,4,7,6]</code>. The array is now a valid arrangement. Thus, the answer is 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>By swapping 4 and 5, the array becomes <code>[2,5,4,7]</code>, which is a valid arrangement. Thus, the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array is already a valid arrangement. Thus, no operations are needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,8]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>No valid arrangement is possible. Thus, the answer is -1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>All elements in <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Greedy; Array
C++
class Solution { public: int minSwaps(vector<int>& nums) { vector<int> pos[2]; for (int i = 0; i < nums.size(); ++i) { pos[nums[i] & 1].push_back(i); } if (abs(int(pos[0].size() - pos[1].size())) > 1) { return -1; } auto calc = [&](int k) { int res = 0; for (int i = 0; i < nums.size(); i += 2) { res += abs(pos[k][i / 2] - i); } return res; }; if (pos[0].size() > pos[1].size()) { return calc(0); } if (pos[0].size() < pos[1].size()) { return calc(1); } return min(calc(0), calc(1)); } };
3,587
Minimum Adjacent Swaps to Alternate Parity
Medium
<p>You are given an array <code>nums</code> of <strong>distinct</strong> integers.</p> <p>In one operation, you can swap any two <strong>adjacent</strong> elements in the array.</p> <p>An arrangement of the array is considered <strong>valid</strong> if the parity of adjacent elements <strong>alternates</strong>, meaning every pair of neighboring elements consists of one even and one odd number.</p> <p>Return the <strong>minimum</strong> number of adjacent swaps required to transform <code>nums</code> into any valid arrangement.</p> <p>If it is impossible to rearrange <code>nums</code> such that no two adjacent elements have the same parity, return <code>-1</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">nums = [2,4,6,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Swapping 5 and 6, the array becomes <code>[2,4,5,6,7]</code></p> <p>Swapping 5 and 4, the array becomes <code>[2,5,4,6,7]</code></p> <p>Swapping 6 and 7, the array becomes <code>[2,5,4,7,6]</code>. The array is now a valid arrangement. Thus, the answer is 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>By swapping 4 and 5, the array becomes <code>[2,5,4,7]</code>, which is a valid arrangement. Thus, the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array is already a valid arrangement. Thus, no operations are needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,8]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>No valid arrangement is possible. Thus, the answer is -1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>All elements in <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Greedy; Array
Go
func minSwaps(nums []int) int { pos := [2][]int{} for i, x := range nums { pos[x&1] = append(pos[x&1], i) } if abs(len(pos[0])-len(pos[1])) > 1 { return -1 } calc := func(k int) int { res := 0 for i := 0; i < len(nums); i += 2 { res += abs(pos[k][i/2] - i) } return res } if len(pos[0]) > len(pos[1]) { return calc(0) } if len(pos[0]) < len(pos[1]) { return calc(1) } return min(calc(0), calc(1)) } func abs(x int) int { if x < 0 { return -x } return x }
3,587
Minimum Adjacent Swaps to Alternate Parity
Medium
<p>You are given an array <code>nums</code> of <strong>distinct</strong> integers.</p> <p>In one operation, you can swap any two <strong>adjacent</strong> elements in the array.</p> <p>An arrangement of the array is considered <strong>valid</strong> if the parity of adjacent elements <strong>alternates</strong>, meaning every pair of neighboring elements consists of one even and one odd number.</p> <p>Return the <strong>minimum</strong> number of adjacent swaps required to transform <code>nums</code> into any valid arrangement.</p> <p>If it is impossible to rearrange <code>nums</code> such that no two adjacent elements have the same parity, return <code>-1</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">nums = [2,4,6,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Swapping 5 and 6, the array becomes <code>[2,4,5,6,7]</code></p> <p>Swapping 5 and 4, the array becomes <code>[2,5,4,6,7]</code></p> <p>Swapping 6 and 7, the array becomes <code>[2,5,4,7,6]</code>. The array is now a valid arrangement. Thus, the answer is 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>By swapping 4 and 5, the array becomes <code>[2,5,4,7]</code>, which is a valid arrangement. Thus, the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array is already a valid arrangement. Thus, no operations are needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,8]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>No valid arrangement is possible. Thus, the answer is -1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>All elements in <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Greedy; Array
Java
class Solution { private List<Integer>[] pos = new List[2]; private int[] nums; public int minSwaps(int[] nums) { this.nums = nums; Arrays.setAll(pos, k -> new ArrayList<>()); for (int i = 0; i < nums.length; ++i) { pos[nums[i] & 1].add(i); } if (Math.abs(pos[0].size() - pos[1].size()) > 1) { return -1; } if (pos[0].size() > pos[1].size()) { return calc(0); } if (pos[0].size() < pos[1].size()) { return calc(1); } return Math.min(calc(0), calc(1)); } private int calc(int k) { int res = 0; for (int i = 0; i < nums.length; i += 2) { res += Math.abs(pos[k].get(i / 2) - i); } return res; } }
3,587
Minimum Adjacent Swaps to Alternate Parity
Medium
<p>You are given an array <code>nums</code> of <strong>distinct</strong> integers.</p> <p>In one operation, you can swap any two <strong>adjacent</strong> elements in the array.</p> <p>An arrangement of the array is considered <strong>valid</strong> if the parity of adjacent elements <strong>alternates</strong>, meaning every pair of neighboring elements consists of one even and one odd number.</p> <p>Return the <strong>minimum</strong> number of adjacent swaps required to transform <code>nums</code> into any valid arrangement.</p> <p>If it is impossible to rearrange <code>nums</code> such that no two adjacent elements have the same parity, return <code>-1</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">nums = [2,4,6,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Swapping 5 and 6, the array becomes <code>[2,4,5,6,7]</code></p> <p>Swapping 5 and 4, the array becomes <code>[2,5,4,6,7]</code></p> <p>Swapping 6 and 7, the array becomes <code>[2,5,4,7,6]</code>. The array is now a valid arrangement. Thus, the answer is 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>By swapping 4 and 5, the array becomes <code>[2,5,4,7]</code>, which is a valid arrangement. Thus, the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array is already a valid arrangement. Thus, no operations are needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,8]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>No valid arrangement is possible. Thus, the answer is -1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>All elements in <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Greedy; Array
Python
class Solution: def minSwaps(self, nums: List[int]) -> int: def calc(k: int) -> int: return sum(abs(i - j) for i, j in zip(range(0, len(nums), 2), pos[k])) pos = [[], []] for i, x in enumerate(nums): pos[x & 1].append(i) if abs(len(pos[0]) - len(pos[1])) > 1: return -1 if len(pos[0]) > len(pos[1]): return calc(0) if len(pos[0]) < len(pos[1]): return calc(1) return min(calc(0), calc(1))
3,587
Minimum Adjacent Swaps to Alternate Parity
Medium
<p>You are given an array <code>nums</code> of <strong>distinct</strong> integers.</p> <p>In one operation, you can swap any two <strong>adjacent</strong> elements in the array.</p> <p>An arrangement of the array is considered <strong>valid</strong> if the parity of adjacent elements <strong>alternates</strong>, meaning every pair of neighboring elements consists of one even and one odd number.</p> <p>Return the <strong>minimum</strong> number of adjacent swaps required to transform <code>nums</code> into any valid arrangement.</p> <p>If it is impossible to rearrange <code>nums</code> such that no two adjacent elements have the same parity, return <code>-1</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">nums = [2,4,6,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Swapping 5 and 6, the array becomes <code>[2,4,5,6,7]</code></p> <p>Swapping 5 and 4, the array becomes <code>[2,5,4,6,7]</code></p> <p>Swapping 6 and 7, the array becomes <code>[2,5,4,7,6]</code>. The array is now a valid arrangement. Thus, the answer is 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>By swapping 4 and 5, the array becomes <code>[2,5,4,7]</code>, which is a valid arrangement. Thus, the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array is already a valid arrangement. Thus, no operations are needed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,8]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>No valid arrangement is possible. Thus, the answer is -1.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>All elements in <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Greedy; Array
TypeScript
function minSwaps(nums: number[]): number { const pos: number[][] = [[], []]; for (let i = 0; i < nums.length; ++i) { pos[nums[i] & 1].push(i); } if (Math.abs(pos[0].length - pos[1].length) > 1) { return -1; } const calc = (k: number): number => { let res = 0; for (let i = 0; i < nums.length; i += 2) { res += Math.abs(pos[k][i >> 1] - i); } return res; }; if (pos[0].length > pos[1].length) { return calc(0); } if (pos[0].length < pos[1].length) { return calc(1); } return Math.min(calc(0), calc(1)); }
3,588
Find Maximum Area of a Triangle
Medium
<p>You are given a 2D array <code>coords</code> of size <code>n x 2</code>, representing the coordinates of <code>n</code> points in an infinite Cartesian plane.</p> <p>Find <strong>twice</strong> the <strong>maximum</strong> area of a triangle with its corners at <em>any</em> three elements from <code>coords</code>, such that at least one side of this triangle is <strong>parallel</strong> to the x-axis or y-axis. Formally, if the maximum area of such a triangle is <code>A</code>, return <code>2 * A</code>.</p> <p>If no such triangle exists, return -1.</p> <p><strong>Note</strong> that a triangle <em>cannot</em> have zero area.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coords = [[1,1],[1,2],[3,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3588.Find%20Maximum%20Area%20of%20a%20Triangle/images/image-20250420010047-1.png" style="width: 300px; height: 289px;" /></p> <p>The triangle shown in the image has a base 1 and height 2. Hence its area is <code>1/2 * base * height = 1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coords = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible triangle has corners <code>(1, 1)</code>, <code>(2, 2)</code>, and <code>(3, 3)</code>. None of its sides are parallel to the x-axis or the y-axis.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == coords.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coords[i][0], coords[i][1] &lt;= 10<sup>6</sup></code></li> <li>All <code>coords[i]</code> are <strong>unique</strong>.</li> </ul>
Greedy; Geometry; Array; Hash Table; Math; Enumeration
C++
class Solution { public: long long maxArea(vector<vector<int>>& coords) { auto calc = [&]() -> long long { int mn = INT_MAX, mx = 0; unordered_map<int, int> f, g; for (auto& c : coords) { int x = c[0], y = c[1]; mn = min(mn, x); mx = max(mx, x); if (f.count(x)) { f[x] = min(f[x], y); g[x] = max(g[x], y); } else { f[x] = y; g[x] = y; } } long long ans = 0; for (auto& [x, y] : f) { int d = g[x] - y; ans = max(ans, 1LL * d * max(mx - x, x - mn)); } return ans; }; long long ans = calc(); for (auto& c : coords) { swap(c[0], c[1]); } ans = max(ans, calc()); return ans > 0 ? ans : -1; } };
3,588
Find Maximum Area of a Triangle
Medium
<p>You are given a 2D array <code>coords</code> of size <code>n x 2</code>, representing the coordinates of <code>n</code> points in an infinite Cartesian plane.</p> <p>Find <strong>twice</strong> the <strong>maximum</strong> area of a triangle with its corners at <em>any</em> three elements from <code>coords</code>, such that at least one side of this triangle is <strong>parallel</strong> to the x-axis or y-axis. Formally, if the maximum area of such a triangle is <code>A</code>, return <code>2 * A</code>.</p> <p>If no such triangle exists, return -1.</p> <p><strong>Note</strong> that a triangle <em>cannot</em> have zero area.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coords = [[1,1],[1,2],[3,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3588.Find%20Maximum%20Area%20of%20a%20Triangle/images/image-20250420010047-1.png" style="width: 300px; height: 289px;" /></p> <p>The triangle shown in the image has a base 1 and height 2. Hence its area is <code>1/2 * base * height = 1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coords = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible triangle has corners <code>(1, 1)</code>, <code>(2, 2)</code>, and <code>(3, 3)</code>. None of its sides are parallel to the x-axis or the y-axis.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == coords.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coords[i][0], coords[i][1] &lt;= 10<sup>6</sup></code></li> <li>All <code>coords[i]</code> are <strong>unique</strong>.</li> </ul>
Greedy; Geometry; Array; Hash Table; Math; Enumeration
Go
func maxArea(coords [][]int) int64 { calc := func() int64 { mn, mx := int(1e9), 0 f := make(map[int]int) g := make(map[int]int) for _, c := range coords { x, y := c[0], c[1] mn = min(mn, x) mx = max(mx, x) if _, ok := f[x]; ok { f[x] = min(f[x], y) g[x] = max(g[x], y) } else { f[x] = y g[x] = y } } var ans int64 for x, y := range f { d := g[x] - y ans = max(ans, int64(d)*int64(max(mx-x, x-mn))) } return ans } ans := calc() for _, c := range coords { c[0], c[1] = c[1], c[0] } ans = max(ans, calc()) if ans > 0 { return ans } return -1 }
3,588
Find Maximum Area of a Triangle
Medium
<p>You are given a 2D array <code>coords</code> of size <code>n x 2</code>, representing the coordinates of <code>n</code> points in an infinite Cartesian plane.</p> <p>Find <strong>twice</strong> the <strong>maximum</strong> area of a triangle with its corners at <em>any</em> three elements from <code>coords</code>, such that at least one side of this triangle is <strong>parallel</strong> to the x-axis or y-axis. Formally, if the maximum area of such a triangle is <code>A</code>, return <code>2 * A</code>.</p> <p>If no such triangle exists, return -1.</p> <p><strong>Note</strong> that a triangle <em>cannot</em> have zero area.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coords = [[1,1],[1,2],[3,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3588.Find%20Maximum%20Area%20of%20a%20Triangle/images/image-20250420010047-1.png" style="width: 300px; height: 289px;" /></p> <p>The triangle shown in the image has a base 1 and height 2. Hence its area is <code>1/2 * base * height = 1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coords = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible triangle has corners <code>(1, 1)</code>, <code>(2, 2)</code>, and <code>(3, 3)</code>. None of its sides are parallel to the x-axis or the y-axis.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == coords.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coords[i][0], coords[i][1] &lt;= 10<sup>6</sup></code></li> <li>All <code>coords[i]</code> are <strong>unique</strong>.</li> </ul>
Greedy; Geometry; Array; Hash Table; Math; Enumeration
Java
class Solution { public long maxArea(int[][] coords) { long ans = calc(coords); for (int[] c : coords) { int tmp = c[0]; c[0] = c[1]; c[1] = tmp; } ans = Math.max(ans, calc(coords)); return ans > 0 ? ans : -1; } private long calc(int[][] coords) { int mn = Integer.MAX_VALUE, mx = 0; Map<Integer, Integer> f = new HashMap<>(); Map<Integer, Integer> g = new HashMap<>(); for (int[] c : coords) { int x = c[0], y = c[1]; mn = Math.min(mn, x); mx = Math.max(mx, x); if (f.containsKey(x)) { f.put(x, Math.min(f.get(x), y)); g.put(x, Math.max(g.get(x), y)); } else { f.put(x, y); g.put(x, y); } } long ans = 0; for (var e : f.entrySet()) { int x = e.getKey(); int y = e.getValue(); int d = g.get(x) - y; ans = Math.max(ans, (long) d * Math.max(mx - x, x - mn)); } return ans; } }
3,588
Find Maximum Area of a Triangle
Medium
<p>You are given a 2D array <code>coords</code> of size <code>n x 2</code>, representing the coordinates of <code>n</code> points in an infinite Cartesian plane.</p> <p>Find <strong>twice</strong> the <strong>maximum</strong> area of a triangle with its corners at <em>any</em> three elements from <code>coords</code>, such that at least one side of this triangle is <strong>parallel</strong> to the x-axis or y-axis. Formally, if the maximum area of such a triangle is <code>A</code>, return <code>2 * A</code>.</p> <p>If no such triangle exists, return -1.</p> <p><strong>Note</strong> that a triangle <em>cannot</em> have zero area.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coords = [[1,1],[1,2],[3,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3588.Find%20Maximum%20Area%20of%20a%20Triangle/images/image-20250420010047-1.png" style="width: 300px; height: 289px;" /></p> <p>The triangle shown in the image has a base 1 and height 2. Hence its area is <code>1/2 * base * height = 1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coords = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible triangle has corners <code>(1, 1)</code>, <code>(2, 2)</code>, and <code>(3, 3)</code>. None of its sides are parallel to the x-axis or the y-axis.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == coords.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coords[i][0], coords[i][1] &lt;= 10<sup>6</sup></code></li> <li>All <code>coords[i]</code> are <strong>unique</strong>.</li> </ul>
Greedy; Geometry; Array; Hash Table; Math; Enumeration
Python
class Solution: def maxArea(self, coords: List[List[int]]) -> int: def calc() -> int: mn, mx = inf, 0 f = {} g = {} for x, y in coords: mn = min(mn, x) mx = max(mx, x) if x in f: f[x] = min(f[x], y) g[x] = max(g[x], y) else: f[x] = g[x] = y ans = 0 for x, y in f.items(): d = g[x] - y ans = max(ans, d * max(mx - x, x - mn)) return ans ans = calc() for c in coords: c[0], c[1] = c[1], c[0] ans = max(ans, calc()) return ans if ans else -1
3,588
Find Maximum Area of a Triangle
Medium
<p>You are given a 2D array <code>coords</code> of size <code>n x 2</code>, representing the coordinates of <code>n</code> points in an infinite Cartesian plane.</p> <p>Find <strong>twice</strong> the <strong>maximum</strong> area of a triangle with its corners at <em>any</em> three elements from <code>coords</code>, such that at least one side of this triangle is <strong>parallel</strong> to the x-axis or y-axis. Formally, if the maximum area of such a triangle is <code>A</code>, return <code>2 * A</code>.</p> <p>If no such triangle exists, return -1.</p> <p><strong>Note</strong> that a triangle <em>cannot</em> have zero area.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coords = [[1,1],[1,2],[3,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3588.Find%20Maximum%20Area%20of%20a%20Triangle/images/image-20250420010047-1.png" style="width: 300px; height: 289px;" /></p> <p>The triangle shown in the image has a base 1 and height 2. Hence its area is <code>1/2 * base * height = 1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coords = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible triangle has corners <code>(1, 1)</code>, <code>(2, 2)</code>, and <code>(3, 3)</code>. None of its sides are parallel to the x-axis or the y-axis.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == coords.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coords[i][0], coords[i][1] &lt;= 10<sup>6</sup></code></li> <li>All <code>coords[i]</code> are <strong>unique</strong>.</li> </ul>
Greedy; Geometry; Array; Hash Table; Math; Enumeration
TypeScript
function maxArea(coords: number[][]): number { function calc(): number { let [mn, mx] = [Infinity, 0]; const f = new Map<number, number>(); const g = new Map<number, number>(); for (const [x, y] of coords) { mn = Math.min(mn, x); mx = Math.max(mx, x); if (f.has(x)) { f.set(x, Math.min(f.get(x)!, y)); g.set(x, Math.max(g.get(x)!, y)); } else { f.set(x, y); g.set(x, y); } } let ans = 0; for (const [x, y] of f) { const d = g.get(x)! - y; ans = Math.max(ans, d * Math.max(mx - x, x - mn)); } return ans; } let ans = calc(); for (const c of coords) { [c[0], c[1]] = [c[1], c[0]]; } ans = Math.max(ans, calc()); return ans > 0 ? ans : -1; }