id
int64
1
3.64k
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,528
Unit Conversion I
Medium
<p>There are <code>n</code> types of units indexed from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>conversions</code> of length <code>n - 1</code>, where <code>conversions[i] = [sourceUnit<sub>i</sub>, targetUnit<sub>i</sub>, conversionFactor<sub>i</sub>]</code>. This indicates that a single unit of type <code>sourceUnit<sub>i</sub></code> is equivalent to <code>conversionFactor<sub>i</sub></code> units of type <code>targetUnit<sub>i</sub></code>.</p> <p>Return an array <code>baseUnitConversion</code> of length <code>n</code>, where <code>baseUnitConversion[i]</code> is the number of units of type <code>i</code> equivalent to a single unit of type 0. Since the answer may be large, return each <code>baseUnitConversion[i]</code> <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">conversions = [[0,1,2],[1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,6]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li> <li>Convert a single unit of type 0 into 6 units of type 2 using <code>conversions[0]</code>, then <code>conversions[1]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3528.Unit%20Conversion%20I/images/example1.png" style="width: 545px; height: 118px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[0,2,3],[1,3,4],[1,4,5],[2,5,2],[4,6,3],[5,7,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,8,10,6,30,24]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li> <li>Convert a single unit of type 0 into 3 units of type 2 using <code>conversions[1]</code>.</li> <li>Convert a single unit of type 0 into 8 units of type 3 using <code>conversions[0]</code>, then <code>conversions[2]</code>.</li> <li>Convert a single unit of type 0 into 10 units of type 4 using <code>conversions[0]</code>, then <code>conversions[3]</code>.</li> <li>Convert a single unit of type 0 into 6 units of type 5 using <code>conversions[1]</code>, then <code>conversions[4]</code>.</li> <li>Convert a single unit of type 0 into 30 units of type 6 using <code>conversions[0]</code>, <code>conversions[3]</code>, then <code>conversions[5]</code>.</li> <li>Convert a single unit of type 0 into 24 units of type 7 using <code>conversions[1]</code>, <code>conversions[4]</code>, then <code>conversions[6]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>conversions.length == n - 1</code></li> <li><code>0 &lt;= sourceUnit<sub>i</sub>, targetUnit<sub>i</sub> &lt; n</code></li> <li><code>1 &lt;= conversionFactor<sub>i</sub> &lt;= 10<sup>9</sup></code></li> <li>It is guaranteed that unit 0 can be converted into any other unit through a <strong>unique</strong> combination of conversions without using any conversions in the opposite direction.</li> </ul>
Depth-First Search; Breadth-First Search; Graph
Go
func baseUnitConversions(conversions [][]int) []int { const mod = int(1e9 + 7) n := len(conversions) + 1 g := make([][]struct{ t, w int }, n) for _, e := range conversions { s, t, w := e[0], e[1], e[2] g[s] = append(g[s], struct{ t, w int }{t, w}) } ans := make([]int, n) var dfs func(s int, mul int) dfs = func(s int, mul int) { ans[s] = mul for _, e := range g[s] { dfs(e.t, mul*e.w%mod) } } dfs(0, 1) return ans }
3,528
Unit Conversion I
Medium
<p>There are <code>n</code> types of units indexed from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>conversions</code> of length <code>n - 1</code>, where <code>conversions[i] = [sourceUnit<sub>i</sub>, targetUnit<sub>i</sub>, conversionFactor<sub>i</sub>]</code>. This indicates that a single unit of type <code>sourceUnit<sub>i</sub></code> is equivalent to <code>conversionFactor<sub>i</sub></code> units of type <code>targetUnit<sub>i</sub></code>.</p> <p>Return an array <code>baseUnitConversion</code> of length <code>n</code>, where <code>baseUnitConversion[i]</code> is the number of units of type <code>i</code> equivalent to a single unit of type 0. Since the answer may be large, return each <code>baseUnitConversion[i]</code> <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">conversions = [[0,1,2],[1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,6]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li> <li>Convert a single unit of type 0 into 6 units of type 2 using <code>conversions[0]</code>, then <code>conversions[1]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3528.Unit%20Conversion%20I/images/example1.png" style="width: 545px; height: 118px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[0,2,3],[1,3,4],[1,4,5],[2,5,2],[4,6,3],[5,7,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,8,10,6,30,24]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li> <li>Convert a single unit of type 0 into 3 units of type 2 using <code>conversions[1]</code>.</li> <li>Convert a single unit of type 0 into 8 units of type 3 using <code>conversions[0]</code>, then <code>conversions[2]</code>.</li> <li>Convert a single unit of type 0 into 10 units of type 4 using <code>conversions[0]</code>, then <code>conversions[3]</code>.</li> <li>Convert a single unit of type 0 into 6 units of type 5 using <code>conversions[1]</code>, then <code>conversions[4]</code>.</li> <li>Convert a single unit of type 0 into 30 units of type 6 using <code>conversions[0]</code>, <code>conversions[3]</code>, then <code>conversions[5]</code>.</li> <li>Convert a single unit of type 0 into 24 units of type 7 using <code>conversions[1]</code>, <code>conversions[4]</code>, then <code>conversions[6]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>conversions.length == n - 1</code></li> <li><code>0 &lt;= sourceUnit<sub>i</sub>, targetUnit<sub>i</sub> &lt; n</code></li> <li><code>1 &lt;= conversionFactor<sub>i</sub> &lt;= 10<sup>9</sup></code></li> <li>It is guaranteed that unit 0 can be converted into any other unit through a <strong>unique</strong> combination of conversions without using any conversions in the opposite direction.</li> </ul>
Depth-First Search; Breadth-First Search; Graph
Java
class Solution { private final int mod = (int) 1e9 + 7; private List<int[]>[] g; private int[] ans; private int n; public int[] baseUnitConversions(int[][] conversions) { n = conversions.length + 1; g = new List[n]; Arrays.setAll(g, k -> new ArrayList<>()); ans = new int[n]; for (var e : conversions) { g[e[0]].add(new int[] {e[1], e[2]}); } dfs(0, 1); return ans; } private void dfs(int s, long mul) { ans[s] = (int) mul; for (var e : g[s]) { dfs(e[0], mul * e[1] % mod); } } }
3,528
Unit Conversion I
Medium
<p>There are <code>n</code> types of units indexed from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>conversions</code> of length <code>n - 1</code>, where <code>conversions[i] = [sourceUnit<sub>i</sub>, targetUnit<sub>i</sub>, conversionFactor<sub>i</sub>]</code>. This indicates that a single unit of type <code>sourceUnit<sub>i</sub></code> is equivalent to <code>conversionFactor<sub>i</sub></code> units of type <code>targetUnit<sub>i</sub></code>.</p> <p>Return an array <code>baseUnitConversion</code> of length <code>n</code>, where <code>baseUnitConversion[i]</code> is the number of units of type <code>i</code> equivalent to a single unit of type 0. Since the answer may be large, return each <code>baseUnitConversion[i]</code> <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">conversions = [[0,1,2],[1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,6]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li> <li>Convert a single unit of type 0 into 6 units of type 2 using <code>conversions[0]</code>, then <code>conversions[1]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3528.Unit%20Conversion%20I/images/example1.png" style="width: 545px; height: 118px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[0,2,3],[1,3,4],[1,4,5],[2,5,2],[4,6,3],[5,7,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,8,10,6,30,24]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li> <li>Convert a single unit of type 0 into 3 units of type 2 using <code>conversions[1]</code>.</li> <li>Convert a single unit of type 0 into 8 units of type 3 using <code>conversions[0]</code>, then <code>conversions[2]</code>.</li> <li>Convert a single unit of type 0 into 10 units of type 4 using <code>conversions[0]</code>, then <code>conversions[3]</code>.</li> <li>Convert a single unit of type 0 into 6 units of type 5 using <code>conversions[1]</code>, then <code>conversions[4]</code>.</li> <li>Convert a single unit of type 0 into 30 units of type 6 using <code>conversions[0]</code>, <code>conversions[3]</code>, then <code>conversions[5]</code>.</li> <li>Convert a single unit of type 0 into 24 units of type 7 using <code>conversions[1]</code>, <code>conversions[4]</code>, then <code>conversions[6]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>conversions.length == n - 1</code></li> <li><code>0 &lt;= sourceUnit<sub>i</sub>, targetUnit<sub>i</sub> &lt; n</code></li> <li><code>1 &lt;= conversionFactor<sub>i</sub> &lt;= 10<sup>9</sup></code></li> <li>It is guaranteed that unit 0 can be converted into any other unit through a <strong>unique</strong> combination of conversions without using any conversions in the opposite direction.</li> </ul>
Depth-First Search; Breadth-First Search; Graph
Python
class Solution: def baseUnitConversions(self, conversions: List[List[int]]) -> List[int]: def dfs(s: int, mul: int) -> None: ans[s] = mul for t, w in g[s]: dfs(t, mul * w % mod) mod = 10**9 + 7 n = len(conversions) + 1 g = [[] for _ in range(n)] for s, t, w in conversions: g[s].append((t, w)) ans = [0] * n dfs(0, 1) return ans
3,528
Unit Conversion I
Medium
<p>There are <code>n</code> types of units indexed from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>conversions</code> of length <code>n - 1</code>, where <code>conversions[i] = [sourceUnit<sub>i</sub>, targetUnit<sub>i</sub>, conversionFactor<sub>i</sub>]</code>. This indicates that a single unit of type <code>sourceUnit<sub>i</sub></code> is equivalent to <code>conversionFactor<sub>i</sub></code> units of type <code>targetUnit<sub>i</sub></code>.</p> <p>Return an array <code>baseUnitConversion</code> of length <code>n</code>, where <code>baseUnitConversion[i]</code> is the number of units of type <code>i</code> equivalent to a single unit of type 0. Since the answer may be large, return each <code>baseUnitConversion[i]</code> <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">conversions = [[0,1,2],[1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,6]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li> <li>Convert a single unit of type 0 into 6 units of type 2 using <code>conversions[0]</code>, then <code>conversions[1]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3528.Unit%20Conversion%20I/images/example1.png" style="width: 545px; height: 118px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[0,2,3],[1,3,4],[1,4,5],[2,5,2],[4,6,3],[5,7,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,8,10,6,30,24]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li> <li>Convert a single unit of type 0 into 3 units of type 2 using <code>conversions[1]</code>.</li> <li>Convert a single unit of type 0 into 8 units of type 3 using <code>conversions[0]</code>, then <code>conversions[2]</code>.</li> <li>Convert a single unit of type 0 into 10 units of type 4 using <code>conversions[0]</code>, then <code>conversions[3]</code>.</li> <li>Convert a single unit of type 0 into 6 units of type 5 using <code>conversions[1]</code>, then <code>conversions[4]</code>.</li> <li>Convert a single unit of type 0 into 30 units of type 6 using <code>conversions[0]</code>, <code>conversions[3]</code>, then <code>conversions[5]</code>.</li> <li>Convert a single unit of type 0 into 24 units of type 7 using <code>conversions[1]</code>, <code>conversions[4]</code>, then <code>conversions[6]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>conversions.length == n - 1</code></li> <li><code>0 &lt;= sourceUnit<sub>i</sub>, targetUnit<sub>i</sub> &lt; n</code></li> <li><code>1 &lt;= conversionFactor<sub>i</sub> &lt;= 10<sup>9</sup></code></li> <li>It is guaranteed that unit 0 can be converted into any other unit through a <strong>unique</strong> combination of conversions without using any conversions in the opposite direction.</li> </ul>
Depth-First Search; Breadth-First Search; Graph
TypeScript
function baseUnitConversions(conversions: number[][]): number[] { const mod = BigInt(1e9 + 7); const n = conversions.length + 1; const g: { t: number; w: number }[][] = Array.from({ length: n }, () => []); for (const [s, t, w] of conversions) { g[s].push({ t, w }); } const ans: number[] = Array(n).fill(0); const dfs = (s: number, mul: number) => { ans[s] = mul; for (const { t, w } of g[s]) { dfs(t, Number((BigInt(mul) * BigInt(w)) % mod)); } }; dfs(0, 1); return ans; }
3,531
Count Covered Buildings
Medium
<p>You are given a positive integer <code>n</code>, representing an <code>n x n</code> city. You are also given a 2D grid <code>buildings</code>, where <code>buildings[i] = [x, y]</code> denotes a <strong>unique</strong> building located at coordinates <code>[x, y]</code>.</p> <p>A building is <strong>covered</strong> if there is at least one building in all <strong>four</strong> directions: left, right, above, and below.</p> <p>Return the number of <strong>covered</strong> buildings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101085-m.jpg" style="width: 200px; height: 204px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Only building <code>[2,2]</code> is covered as it has at least one building: <ul> <li>above (<code>[1,2]</code>)</li> <li>below (<code>[3,2]</code>)</li> <li>left (<code>[2,1]</code>)</li> <li>right (<code>[2,3]</code>)</li> </ul> </li> <li>Thus, the count of covered buildings is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101086-m.jpg" style="width: 200px; height: 204px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>No building has at least one building in all four directions.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6248862251436067566-x.jpg" style="width: 202px; height: 205px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Only building <code>[3,3]</code> is covered as it has at least one building: <ul> <li>above (<code>[1,3]</code>)</li> <li>below (<code>[5,3]</code>)</li> <li>left (<code>[3,2]</code>)</li> <li>right (<code>[3,5]</code>)</li> </ul> </li> <li>Thus, the count of covered buildings is 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= buildings.length &lt;= 10<sup>5</sup> </code></li> <li><code>buildings[i] = [x, y]</code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> <li>All coordinates of <code>buildings</code> are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Sorting
C++
class Solution { public: int countCoveredBuildings(int n, vector<vector<int>>& buildings) { unordered_map<int, vector<int>> g1; unordered_map<int, vector<int>> g2; for (const auto& building : buildings) { int x = building[0], y = building[1]; g1[x].push_back(y); g2[y].push_back(x); } for (auto& e : g1) { sort(e.second.begin(), e.second.end()); } for (auto& e : g2) { sort(e.second.begin(), e.second.end()); } int ans = 0; for (const auto& building : buildings) { int x = building[0], y = building[1]; const vector<int>& l1 = g1[x]; const vector<int>& l2 = g2[y]; if (l2[0] < x && x < l2[l2.size() - 1] && l1[0] < y && y < l1[l1.size() - 1]) { ans++; } } return ans; } };
3,531
Count Covered Buildings
Medium
<p>You are given a positive integer <code>n</code>, representing an <code>n x n</code> city. You are also given a 2D grid <code>buildings</code>, where <code>buildings[i] = [x, y]</code> denotes a <strong>unique</strong> building located at coordinates <code>[x, y]</code>.</p> <p>A building is <strong>covered</strong> if there is at least one building in all <strong>four</strong> directions: left, right, above, and below.</p> <p>Return the number of <strong>covered</strong> buildings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101085-m.jpg" style="width: 200px; height: 204px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Only building <code>[2,2]</code> is covered as it has at least one building: <ul> <li>above (<code>[1,2]</code>)</li> <li>below (<code>[3,2]</code>)</li> <li>left (<code>[2,1]</code>)</li> <li>right (<code>[2,3]</code>)</li> </ul> </li> <li>Thus, the count of covered buildings is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101086-m.jpg" style="width: 200px; height: 204px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>No building has at least one building in all four directions.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6248862251436067566-x.jpg" style="width: 202px; height: 205px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Only building <code>[3,3]</code> is covered as it has at least one building: <ul> <li>above (<code>[1,3]</code>)</li> <li>below (<code>[5,3]</code>)</li> <li>left (<code>[3,2]</code>)</li> <li>right (<code>[3,5]</code>)</li> </ul> </li> <li>Thus, the count of covered buildings is 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= buildings.length &lt;= 10<sup>5</sup> </code></li> <li><code>buildings[i] = [x, y]</code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> <li>All coordinates of <code>buildings</code> are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Sorting
Go
func countCoveredBuildings(n int, buildings [][]int) (ans int) { g1 := make(map[int][]int) g2 := make(map[int][]int) for _, building := range buildings { x, y := building[0], building[1] g1[x] = append(g1[x], y) g2[y] = append(g2[y], x) } for _, list := range g1 { sort.Ints(list) } for _, list := range g2 { sort.Ints(list) } for _, building := range buildings { x, y := building[0], building[1] l1 := g1[x] l2 := g2[y] if l2[0] < x && x < l2[len(l2)-1] && l1[0] < y && y < l1[len(l1)-1] { ans++ } } return }
3,531
Count Covered Buildings
Medium
<p>You are given a positive integer <code>n</code>, representing an <code>n x n</code> city. You are also given a 2D grid <code>buildings</code>, where <code>buildings[i] = [x, y]</code> denotes a <strong>unique</strong> building located at coordinates <code>[x, y]</code>.</p> <p>A building is <strong>covered</strong> if there is at least one building in all <strong>four</strong> directions: left, right, above, and below.</p> <p>Return the number of <strong>covered</strong> buildings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101085-m.jpg" style="width: 200px; height: 204px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Only building <code>[2,2]</code> is covered as it has at least one building: <ul> <li>above (<code>[1,2]</code>)</li> <li>below (<code>[3,2]</code>)</li> <li>left (<code>[2,1]</code>)</li> <li>right (<code>[2,3]</code>)</li> </ul> </li> <li>Thus, the count of covered buildings is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101086-m.jpg" style="width: 200px; height: 204px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>No building has at least one building in all four directions.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6248862251436067566-x.jpg" style="width: 202px; height: 205px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Only building <code>[3,3]</code> is covered as it has at least one building: <ul> <li>above (<code>[1,3]</code>)</li> <li>below (<code>[5,3]</code>)</li> <li>left (<code>[3,2]</code>)</li> <li>right (<code>[3,5]</code>)</li> </ul> </li> <li>Thus, the count of covered buildings is 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= buildings.length &lt;= 10<sup>5</sup> </code></li> <li><code>buildings[i] = [x, y]</code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> <li>All coordinates of <code>buildings</code> are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Sorting
Java
class Solution { public int countCoveredBuildings(int n, int[][] buildings) { Map<Integer, List<Integer>> g1 = new HashMap<>(); Map<Integer, List<Integer>> g2 = new HashMap<>(); for (int[] building : buildings) { int x = building[0], y = building[1]; g1.computeIfAbsent(x, k -> new ArrayList<>()).add(y); g2.computeIfAbsent(y, k -> new ArrayList<>()).add(x); } for (var e : g1.entrySet()) { Collections.sort(e.getValue()); } for (var e : g2.entrySet()) { Collections.sort(e.getValue()); } int ans = 0; for (int[] building : buildings) { int x = building[0], y = building[1]; List<Integer> l1 = g1.get(x); List<Integer> l2 = g2.get(y); if (l2.get(0) < x && x < l2.get(l2.size() - 1) && l1.get(0) < y && y < l1.get(l1.size() - 1)) { ans++; } } return ans; } }
3,531
Count Covered Buildings
Medium
<p>You are given a positive integer <code>n</code>, representing an <code>n x n</code> city. You are also given a 2D grid <code>buildings</code>, where <code>buildings[i] = [x, y]</code> denotes a <strong>unique</strong> building located at coordinates <code>[x, y]</code>.</p> <p>A building is <strong>covered</strong> if there is at least one building in all <strong>four</strong> directions: left, right, above, and below.</p> <p>Return the number of <strong>covered</strong> buildings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101085-m.jpg" style="width: 200px; height: 204px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Only building <code>[2,2]</code> is covered as it has at least one building: <ul> <li>above (<code>[1,2]</code>)</li> <li>below (<code>[3,2]</code>)</li> <li>left (<code>[2,1]</code>)</li> <li>right (<code>[2,3]</code>)</li> </ul> </li> <li>Thus, the count of covered buildings is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101086-m.jpg" style="width: 200px; height: 204px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>No building has at least one building in all four directions.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6248862251436067566-x.jpg" style="width: 202px; height: 205px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Only building <code>[3,3]</code> is covered as it has at least one building: <ul> <li>above (<code>[1,3]</code>)</li> <li>below (<code>[5,3]</code>)</li> <li>left (<code>[3,2]</code>)</li> <li>right (<code>[3,5]</code>)</li> </ul> </li> <li>Thus, the count of covered buildings is 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= buildings.length &lt;= 10<sup>5</sup> </code></li> <li><code>buildings[i] = [x, y]</code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> <li>All coordinates of <code>buildings</code> are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Sorting
Python
class Solution: def countCoveredBuildings(self, n: int, buildings: List[List[int]]) -> int: g1 = defaultdict(list) g2 = defaultdict(list) for x, y in buildings: g1[x].append(y) g2[y].append(x) for x in g1: g1[x].sort() for y in g2: g2[y].sort() ans = 0 for x, y in buildings: l1 = g1[x] l2 = g2[y] if l2[0] < x < l2[-1] and l1[0] < y < l1[-1]: ans += 1 return ans
3,531
Count Covered Buildings
Medium
<p>You are given a positive integer <code>n</code>, representing an <code>n x n</code> city. You are also given a 2D grid <code>buildings</code>, where <code>buildings[i] = [x, y]</code> denotes a <strong>unique</strong> building located at coordinates <code>[x, y]</code>.</p> <p>A building is <strong>covered</strong> if there is at least one building in all <strong>four</strong> directions: left, right, above, and below.</p> <p>Return the number of <strong>covered</strong> buildings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101085-m.jpg" style="width: 200px; height: 204px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Only building <code>[2,2]</code> is covered as it has at least one building: <ul> <li>above (<code>[1,2]</code>)</li> <li>below (<code>[3,2]</code>)</li> <li>left (<code>[2,1]</code>)</li> <li>right (<code>[2,3]</code>)</li> </ul> </li> <li>Thus, the count of covered buildings is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6212982906394101086-m.jpg" style="width: 200px; height: 204px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>No building has at least one building in all four directions.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3531.Count%20Covered%20Buildings/images/telegram-cloud-photo-size-5-6248862251436067566-x.jpg" style="width: 202px; height: 205px;" /></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Only building <code>[3,3]</code> is covered as it has at least one building: <ul> <li>above (<code>[1,3]</code>)</li> <li>below (<code>[5,3]</code>)</li> <li>left (<code>[3,2]</code>)</li> <li>right (<code>[3,5]</code>)</li> </ul> </li> <li>Thus, the count of covered buildings is 1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= buildings.length &lt;= 10<sup>5</sup> </code></li> <li><code>buildings[i] = [x, y]</code></li> <li><code>1 &lt;= x, y &lt;= n</code></li> <li>All coordinates of <code>buildings</code> are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Sorting
TypeScript
function countCoveredBuildings(n: number, buildings: number[][]): number { const g1: Map<number, number[]> = new Map(); const g2: Map<number, number[]> = new Map(); for (const [x, y] of buildings) { if (!g1.has(x)) g1.set(x, []); g1.get(x)?.push(y); if (!g2.has(y)) g2.set(y, []); g2.get(y)?.push(x); } for (const list of g1.values()) { list.sort((a, b) => a - b); } for (const list of g2.values()) { list.sort((a, b) => a - b); } let ans = 0; for (const [x, y] of buildings) { const l1 = g1.get(x)!; const l2 = g2.get(y)!; if (l2[0] < x && x < l2[l2.length - 1] && l1[0] < y && y < l1[l1.length - 1]) { ans++; } } return ans; }
3,532
Path Existence Queries in a Graph I
Medium
<p>You are given an integer <code>n</code> representing the number of nodes in a graph, labeled from 0 to <code>n - 1</code>.</p> <p>You are also given an integer array <code>nums</code> of length <code>n</code> sorted in <strong>non-decreasing</strong> order, and an integer <code>maxDiff</code>.</p> <p>An <strong>undirected </strong>edge exists between nodes <code>i</code> and <code>j</code> if the <strong>absolute</strong> difference between <code>nums[i]</code> and <code>nums[j]</code> is <strong>at most</strong> <code>maxDiff</code> (i.e., <code>|nums[i] - nums[j]| &lt;= maxDiff</code>).</p> <p>You are also given a 2D integer array <code>queries</code>. For each <code>queries[i] = [u<sub>i</sub>, v<sub>i</sub>]</code>, determine whether there exists a path between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p> <p>Return a boolean array <code>answer</code>, where <code>answer[i]</code> is <code>true</code> if there exists a path between <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the <code>i<sup>th</sup></code> query 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">n = 2, nums = [1,3], maxDiff = 1, queries = [[0,0],[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[true,false]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query <code>[0,0]</code>: Node 0 has a trivial path to itself.</li> <li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |1 - 3| = 2</code>, which is greater than <code>maxDiff</code>.</li> <li>Thus, the final answer after processing all the queries is <code>[true, false]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, nums = [2,5,6,8], maxDiff = 2, queries = [[0,1],[0,2],[1,3],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">[false,false,true,true]</span></p> <p><strong>Explanation:</strong></p> <p>The resulting graph is:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3532.Path%20Existence%20Queries%20in%20a%20Graph%20I/images/screenshot-2025-03-26-at-122249.png" style="width: 300px; height: 170px;" /></p> <ul> <li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |2 - 5| = 3</code>, which is greater than <code>maxDiff</code>.</li> <li>Query <code>[0,2]</code>: There is no edge between Node 0 and Node 2 because <code>|nums[0] - nums[2]| = |2 - 6| = 4</code>, which is greater than <code>maxDiff</code>.</li> <li>Query <code>[1,3]</code>: There is a path between Node 1 and Node 3 through Node 2 since <code>|nums[1] - nums[2]| = |5 - 6| = 1</code> and <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, both of which are within <code>maxDiff</code>.</li> <li>Query <code>[2,3]</code>: There is an edge between Node 2 and Node 3 because <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, which is equal to <code>maxDiff</code>.</li> <li>Thus, the final answer after processing all the queries is <code>[false, false, true, true]</code>.</li> </ul> </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>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> <li><code>0 &lt;= maxDiff &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> </ul>
Union Find; Graph; Array; Hash Table; Binary Search
C++
class Solution { public: vector<bool> pathExistenceQueries(int n, vector<int>& nums, int maxDiff, vector<vector<int>>& queries) { vector<int> g(n); int cnt = 0; for (int i = 1; i < n; ++i) { if (nums[i] - nums[i - 1] > maxDiff) { ++cnt; } g[i] = cnt; } vector<bool> ans; for (const auto& q : queries) { int u = q[0], v = q[1]; ans.push_back(g[u] == g[v]); } return ans; } };
3,532
Path Existence Queries in a Graph I
Medium
<p>You are given an integer <code>n</code> representing the number of nodes in a graph, labeled from 0 to <code>n - 1</code>.</p> <p>You are also given an integer array <code>nums</code> of length <code>n</code> sorted in <strong>non-decreasing</strong> order, and an integer <code>maxDiff</code>.</p> <p>An <strong>undirected </strong>edge exists between nodes <code>i</code> and <code>j</code> if the <strong>absolute</strong> difference between <code>nums[i]</code> and <code>nums[j]</code> is <strong>at most</strong> <code>maxDiff</code> (i.e., <code>|nums[i] - nums[j]| &lt;= maxDiff</code>).</p> <p>You are also given a 2D integer array <code>queries</code>. For each <code>queries[i] = [u<sub>i</sub>, v<sub>i</sub>]</code>, determine whether there exists a path between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p> <p>Return a boolean array <code>answer</code>, where <code>answer[i]</code> is <code>true</code> if there exists a path between <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the <code>i<sup>th</sup></code> query 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">n = 2, nums = [1,3], maxDiff = 1, queries = [[0,0],[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[true,false]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query <code>[0,0]</code>: Node 0 has a trivial path to itself.</li> <li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |1 - 3| = 2</code>, which is greater than <code>maxDiff</code>.</li> <li>Thus, the final answer after processing all the queries is <code>[true, false]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, nums = [2,5,6,8], maxDiff = 2, queries = [[0,1],[0,2],[1,3],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">[false,false,true,true]</span></p> <p><strong>Explanation:</strong></p> <p>The resulting graph is:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3532.Path%20Existence%20Queries%20in%20a%20Graph%20I/images/screenshot-2025-03-26-at-122249.png" style="width: 300px; height: 170px;" /></p> <ul> <li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |2 - 5| = 3</code>, which is greater than <code>maxDiff</code>.</li> <li>Query <code>[0,2]</code>: There is no edge between Node 0 and Node 2 because <code>|nums[0] - nums[2]| = |2 - 6| = 4</code>, which is greater than <code>maxDiff</code>.</li> <li>Query <code>[1,3]</code>: There is a path between Node 1 and Node 3 through Node 2 since <code>|nums[1] - nums[2]| = |5 - 6| = 1</code> and <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, both of which are within <code>maxDiff</code>.</li> <li>Query <code>[2,3]</code>: There is an edge between Node 2 and Node 3 because <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, which is equal to <code>maxDiff</code>.</li> <li>Thus, the final answer after processing all the queries is <code>[false, false, true, true]</code>.</li> </ul> </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>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> <li><code>0 &lt;= maxDiff &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> </ul>
Union Find; Graph; Array; Hash Table; Binary Search
Go
func pathExistenceQueries(n int, nums []int, maxDiff int, queries [][]int) (ans []bool) { g := make([]int, n) cnt := 0 for i := 1; i < n; i++ { if nums[i]-nums[i-1] > maxDiff { cnt++ } g[i] = cnt } for _, q := range queries { u, v := q[0], q[1] ans = append(ans, g[u] == g[v]) } return }
3,532
Path Existence Queries in a Graph I
Medium
<p>You are given an integer <code>n</code> representing the number of nodes in a graph, labeled from 0 to <code>n - 1</code>.</p> <p>You are also given an integer array <code>nums</code> of length <code>n</code> sorted in <strong>non-decreasing</strong> order, and an integer <code>maxDiff</code>.</p> <p>An <strong>undirected </strong>edge exists between nodes <code>i</code> and <code>j</code> if the <strong>absolute</strong> difference between <code>nums[i]</code> and <code>nums[j]</code> is <strong>at most</strong> <code>maxDiff</code> (i.e., <code>|nums[i] - nums[j]| &lt;= maxDiff</code>).</p> <p>You are also given a 2D integer array <code>queries</code>. For each <code>queries[i] = [u<sub>i</sub>, v<sub>i</sub>]</code>, determine whether there exists a path between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p> <p>Return a boolean array <code>answer</code>, where <code>answer[i]</code> is <code>true</code> if there exists a path between <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the <code>i<sup>th</sup></code> query 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">n = 2, nums = [1,3], maxDiff = 1, queries = [[0,0],[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[true,false]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query <code>[0,0]</code>: Node 0 has a trivial path to itself.</li> <li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |1 - 3| = 2</code>, which is greater than <code>maxDiff</code>.</li> <li>Thus, the final answer after processing all the queries is <code>[true, false]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, nums = [2,5,6,8], maxDiff = 2, queries = [[0,1],[0,2],[1,3],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">[false,false,true,true]</span></p> <p><strong>Explanation:</strong></p> <p>The resulting graph is:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3532.Path%20Existence%20Queries%20in%20a%20Graph%20I/images/screenshot-2025-03-26-at-122249.png" style="width: 300px; height: 170px;" /></p> <ul> <li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |2 - 5| = 3</code>, which is greater than <code>maxDiff</code>.</li> <li>Query <code>[0,2]</code>: There is no edge between Node 0 and Node 2 because <code>|nums[0] - nums[2]| = |2 - 6| = 4</code>, which is greater than <code>maxDiff</code>.</li> <li>Query <code>[1,3]</code>: There is a path between Node 1 and Node 3 through Node 2 since <code>|nums[1] - nums[2]| = |5 - 6| = 1</code> and <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, both of which are within <code>maxDiff</code>.</li> <li>Query <code>[2,3]</code>: There is an edge between Node 2 and Node 3 because <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, which is equal to <code>maxDiff</code>.</li> <li>Thus, the final answer after processing all the queries is <code>[false, false, true, true]</code>.</li> </ul> </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>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> <li><code>0 &lt;= maxDiff &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> </ul>
Union Find; Graph; Array; Hash Table; Binary Search
Java
class Solution { public boolean[] pathExistenceQueries(int n, int[] nums, int maxDiff, int[][] queries) { int[] g = new int[n]; int cnt = 0; for (int i = 1; i < n; ++i) { if (nums[i] - nums[i - 1] > maxDiff) { cnt++; } g[i] = cnt; } int m = queries.length; boolean[] ans = new boolean[m]; for (int i = 0; i < m; ++i) { int u = queries[i][0]; int v = queries[i][1]; ans[i] = g[u] == g[v]; } return ans; } }
3,532
Path Existence Queries in a Graph I
Medium
<p>You are given an integer <code>n</code> representing the number of nodes in a graph, labeled from 0 to <code>n - 1</code>.</p> <p>You are also given an integer array <code>nums</code> of length <code>n</code> sorted in <strong>non-decreasing</strong> order, and an integer <code>maxDiff</code>.</p> <p>An <strong>undirected </strong>edge exists between nodes <code>i</code> and <code>j</code> if the <strong>absolute</strong> difference between <code>nums[i]</code> and <code>nums[j]</code> is <strong>at most</strong> <code>maxDiff</code> (i.e., <code>|nums[i] - nums[j]| &lt;= maxDiff</code>).</p> <p>You are also given a 2D integer array <code>queries</code>. For each <code>queries[i] = [u<sub>i</sub>, v<sub>i</sub>]</code>, determine whether there exists a path between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p> <p>Return a boolean array <code>answer</code>, where <code>answer[i]</code> is <code>true</code> if there exists a path between <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the <code>i<sup>th</sup></code> query 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">n = 2, nums = [1,3], maxDiff = 1, queries = [[0,0],[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[true,false]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query <code>[0,0]</code>: Node 0 has a trivial path to itself.</li> <li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |1 - 3| = 2</code>, which is greater than <code>maxDiff</code>.</li> <li>Thus, the final answer after processing all the queries is <code>[true, false]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, nums = [2,5,6,8], maxDiff = 2, queries = [[0,1],[0,2],[1,3],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">[false,false,true,true]</span></p> <p><strong>Explanation:</strong></p> <p>The resulting graph is:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3532.Path%20Existence%20Queries%20in%20a%20Graph%20I/images/screenshot-2025-03-26-at-122249.png" style="width: 300px; height: 170px;" /></p> <ul> <li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |2 - 5| = 3</code>, which is greater than <code>maxDiff</code>.</li> <li>Query <code>[0,2]</code>: There is no edge between Node 0 and Node 2 because <code>|nums[0] - nums[2]| = |2 - 6| = 4</code>, which is greater than <code>maxDiff</code>.</li> <li>Query <code>[1,3]</code>: There is a path between Node 1 and Node 3 through Node 2 since <code>|nums[1] - nums[2]| = |5 - 6| = 1</code> and <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, both of which are within <code>maxDiff</code>.</li> <li>Query <code>[2,3]</code>: There is an edge between Node 2 and Node 3 because <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, which is equal to <code>maxDiff</code>.</li> <li>Thus, the final answer after processing all the queries is <code>[false, false, true, true]</code>.</li> </ul> </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>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> <li><code>0 &lt;= maxDiff &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> </ul>
Union Find; Graph; Array; Hash Table; Binary Search
Python
class Solution: def pathExistenceQueries( self, n: int, nums: List[int], maxDiff: int, queries: List[List[int]] ) -> List[bool]: g = [0] * n cnt = 0 for i in range(1, n): if nums[i] - nums[i - 1] > maxDiff: cnt += 1 g[i] = cnt return [g[u] == g[v] for u, v in queries]
3,532
Path Existence Queries in a Graph I
Medium
<p>You are given an integer <code>n</code> representing the number of nodes in a graph, labeled from 0 to <code>n - 1</code>.</p> <p>You are also given an integer array <code>nums</code> of length <code>n</code> sorted in <strong>non-decreasing</strong> order, and an integer <code>maxDiff</code>.</p> <p>An <strong>undirected </strong>edge exists between nodes <code>i</code> and <code>j</code> if the <strong>absolute</strong> difference between <code>nums[i]</code> and <code>nums[j]</code> is <strong>at most</strong> <code>maxDiff</code> (i.e., <code>|nums[i] - nums[j]| &lt;= maxDiff</code>).</p> <p>You are also given a 2D integer array <code>queries</code>. For each <code>queries[i] = [u<sub>i</sub>, v<sub>i</sub>]</code>, determine whether there exists a path between nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>.</p> <p>Return a boolean array <code>answer</code>, where <code>answer[i]</code> is <code>true</code> if there exists a path between <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> in the <code>i<sup>th</sup></code> query 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">n = 2, nums = [1,3], maxDiff = 1, queries = [[0,0],[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[true,false]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query <code>[0,0]</code>: Node 0 has a trivial path to itself.</li> <li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |1 - 3| = 2</code>, which is greater than <code>maxDiff</code>.</li> <li>Thus, the final answer after processing all the queries is <code>[true, false]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, nums = [2,5,6,8], maxDiff = 2, queries = [[0,1],[0,2],[1,3],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">[false,false,true,true]</span></p> <p><strong>Explanation:</strong></p> <p>The resulting graph is:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3532.Path%20Existence%20Queries%20in%20a%20Graph%20I/images/screenshot-2025-03-26-at-122249.png" style="width: 300px; height: 170px;" /></p> <ul> <li>Query <code>[0,1]</code>: There is no edge between Node 0 and Node 1 because <code>|nums[0] - nums[1]| = |2 - 5| = 3</code>, which is greater than <code>maxDiff</code>.</li> <li>Query <code>[0,2]</code>: There is no edge between Node 0 and Node 2 because <code>|nums[0] - nums[2]| = |2 - 6| = 4</code>, which is greater than <code>maxDiff</code>.</li> <li>Query <code>[1,3]</code>: There is a path between Node 1 and Node 3 through Node 2 since <code>|nums[1] - nums[2]| = |5 - 6| = 1</code> and <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, both of which are within <code>maxDiff</code>.</li> <li>Query <code>[2,3]</code>: There is an edge between Node 2 and Node 3 because <code>|nums[2] - nums[3]| = |6 - 8| = 2</code>, which is equal to <code>maxDiff</code>.</li> <li>Thus, the final answer after processing all the queries is <code>[false, false, true, true]</code>.</li> </ul> </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>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li> <li><code>0 &lt;= maxDiff &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i] == [u<sub>i</sub>, v<sub>i</sub>]</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> </ul>
Union Find; Graph; Array; Hash Table; Binary Search
TypeScript
function pathExistenceQueries( n: number, nums: number[], maxDiff: number, queries: number[][], ): boolean[] { const g: number[] = Array(n).fill(0); let cnt = 0; for (let i = 1; i < n; ++i) { if (nums[i] - nums[i - 1] > maxDiff) { ++cnt; } g[i] = cnt; } return queries.map(([u, v]) => g[u] === g[v]); }
3,536
Maximum Product of Two Digits
Easy
<p>You are given a positive integer <code>n</code>.</p> <p>Return the <strong>maximum</strong> product of any two digits in <code>n</code>.</p> <p><strong>Note:</strong> You may use the <strong>same</strong> digit twice if it appears more than once in <code>n</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">n = 31</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[3, 1]</code>.</li> <li>The possible products of any two digits are: <code>3 * 1 = 3</code>.</li> <li>The maximum product is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 22</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[2, 2]</code>.</li> <li>The possible products of any two digits are: <code>2 * 2 = 4</code>.</li> <li>The maximum product is 4.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 124</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[1, 2, 4]</code>.</li> <li>The possible products of any two digits are: <code>1 * 2 = 2</code>, <code>1 * 4 = 4</code>, <code>2 * 4 = 8</code>.</li> <li>The maximum product is 8.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>10 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Math; Sorting
C++
class Solution { public: int maxProduct(int n) { int a = 0, b = 0; for (; n; n /= 10) { int x = n % 10; if (a < x) { b = a; a = x; } else if (b < x) { b = x; } } return a * b; } };
3,536
Maximum Product of Two Digits
Easy
<p>You are given a positive integer <code>n</code>.</p> <p>Return the <strong>maximum</strong> product of any two digits in <code>n</code>.</p> <p><strong>Note:</strong> You may use the <strong>same</strong> digit twice if it appears more than once in <code>n</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">n = 31</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[3, 1]</code>.</li> <li>The possible products of any two digits are: <code>3 * 1 = 3</code>.</li> <li>The maximum product is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 22</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[2, 2]</code>.</li> <li>The possible products of any two digits are: <code>2 * 2 = 4</code>.</li> <li>The maximum product is 4.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 124</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[1, 2, 4]</code>.</li> <li>The possible products of any two digits are: <code>1 * 2 = 2</code>, <code>1 * 4 = 4</code>, <code>2 * 4 = 8</code>.</li> <li>The maximum product is 8.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>10 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Math; Sorting
Go
func maxProduct(n int) int { a, b := 0, 0 for ; n > 0; n /= 10 { x := n % 10 if a < x { b, a = a, x } else if b < x { b = x } } return a * b }
3,536
Maximum Product of Two Digits
Easy
<p>You are given a positive integer <code>n</code>.</p> <p>Return the <strong>maximum</strong> product of any two digits in <code>n</code>.</p> <p><strong>Note:</strong> You may use the <strong>same</strong> digit twice if it appears more than once in <code>n</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">n = 31</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[3, 1]</code>.</li> <li>The possible products of any two digits are: <code>3 * 1 = 3</code>.</li> <li>The maximum product is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 22</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[2, 2]</code>.</li> <li>The possible products of any two digits are: <code>2 * 2 = 4</code>.</li> <li>The maximum product is 4.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 124</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[1, 2, 4]</code>.</li> <li>The possible products of any two digits are: <code>1 * 2 = 2</code>, <code>1 * 4 = 4</code>, <code>2 * 4 = 8</code>.</li> <li>The maximum product is 8.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>10 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Math; Sorting
Java
class Solution { public int maxProduct(int n) { int a = 0, b = 0; for (; n > 0; n /= 10) { int x = n % 10; if (a < x) { b = a; a = x; } else if (b < x) { b = x; } } return a * b; } }
3,536
Maximum Product of Two Digits
Easy
<p>You are given a positive integer <code>n</code>.</p> <p>Return the <strong>maximum</strong> product of any two digits in <code>n</code>.</p> <p><strong>Note:</strong> You may use the <strong>same</strong> digit twice if it appears more than once in <code>n</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">n = 31</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[3, 1]</code>.</li> <li>The possible products of any two digits are: <code>3 * 1 = 3</code>.</li> <li>The maximum product is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 22</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[2, 2]</code>.</li> <li>The possible products of any two digits are: <code>2 * 2 = 4</code>.</li> <li>The maximum product is 4.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 124</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[1, 2, 4]</code>.</li> <li>The possible products of any two digits are: <code>1 * 2 = 2</code>, <code>1 * 4 = 4</code>, <code>2 * 4 = 8</code>.</li> <li>The maximum product is 8.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>10 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Math; Sorting
Python
class Solution: def maxProduct(self, n: int) -> int: a = b = 0 while n: n, x = divmod(n, 10) if a < x: a, b = x, a elif b < x: b = x return a * b
3,536
Maximum Product of Two Digits
Easy
<p>You are given a positive integer <code>n</code>.</p> <p>Return the <strong>maximum</strong> product of any two digits in <code>n</code>.</p> <p><strong>Note:</strong> You may use the <strong>same</strong> digit twice if it appears more than once in <code>n</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">n = 31</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[3, 1]</code>.</li> <li>The possible products of any two digits are: <code>3 * 1 = 3</code>.</li> <li>The maximum product is 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 22</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[2, 2]</code>.</li> <li>The possible products of any two digits are: <code>2 * 2 = 4</code>.</li> <li>The maximum product is 4.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 124</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The digits of <code>n</code> are <code>[1, 2, 4]</code>.</li> <li>The possible products of any two digits are: <code>1 * 2 = 2</code>, <code>1 * 4 = 4</code>, <code>2 * 4 = 8</code>.</li> <li>The maximum product is 8.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>10 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Math; Sorting
TypeScript
function maxProduct(n: number): number { let [a, b] = [0, 0]; for (; n; n = Math.floor(n / 10)) { const x = n % 10; if (a < x) { [a, b] = [x, a]; } else if (b < x) { b = x; } } return a * b; }
3,541
Find Most Frequent Vowel and Consonant
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters (<code>&#39;a&#39;</code> to <code>&#39;z&#39;</code>). </p> <p>Your task is to:</p> <ul> <li>Find the vowel (one of <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, or <code>&#39;u&#39;</code>) with the <strong>maximum</strong> frequency.</li> <li>Find the consonant (all other letters excluding vowels) with the <strong>maximum</strong> frequency.</li> </ul> <p>Return the sum of the two frequencies.</p> <p><strong>Note</strong>: If multiple vowels or consonants have the same maximum frequency, you may choose any one of them. If there are no vowels or no consonants in the string, consider their frequency as 0.</p> The <strong>frequency</strong> of a letter <code>x</code> is the number of times it occurs in the string. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;successes&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The vowels are: <code>&#39;u&#39;</code> (frequency 1), <code>&#39;e&#39;</code> (frequency 2). The maximum frequency is 2.</li> <li>The consonants are: <code>&#39;s&#39;</code> (frequency 4), <code>&#39;c&#39;</code> (frequency 2). The maximum frequency is 4.</li> <li>The output is <code>2 + 4 = 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">s = &quot;aeiaeia&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The vowels are: <code>&#39;a&#39;</code> (frequency 3), <code>&#39;e&#39;</code> ( frequency 2), <code>&#39;i&#39;</code> (frequency 2). The maximum frequency is 3.</li> <li>There are no consonants in <code>s</code>. Hence, maximum consonant frequency = 0.</li> <li>The output is <code>3 + 0 = 3</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
Hash Table; String; Counting
C++
class Solution { public: int maxFreqSum(string s) { int cnt[26]{}; for (char c : s) { ++cnt[c - 'a']; } int a = 0, b = 0; for (int i = 0; i < 26; ++i) { char c = 'a' + i; if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { a = max(a, cnt[i]); } else { b = max(b, cnt[i]); } } return a + b; } };
3,541
Find Most Frequent Vowel and Consonant
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters (<code>&#39;a&#39;</code> to <code>&#39;z&#39;</code>). </p> <p>Your task is to:</p> <ul> <li>Find the vowel (one of <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, or <code>&#39;u&#39;</code>) with the <strong>maximum</strong> frequency.</li> <li>Find the consonant (all other letters excluding vowels) with the <strong>maximum</strong> frequency.</li> </ul> <p>Return the sum of the two frequencies.</p> <p><strong>Note</strong>: If multiple vowels or consonants have the same maximum frequency, you may choose any one of them. If there are no vowels or no consonants in the string, consider their frequency as 0.</p> The <strong>frequency</strong> of a letter <code>x</code> is the number of times it occurs in the string. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;successes&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The vowels are: <code>&#39;u&#39;</code> (frequency 1), <code>&#39;e&#39;</code> (frequency 2). The maximum frequency is 2.</li> <li>The consonants are: <code>&#39;s&#39;</code> (frequency 4), <code>&#39;c&#39;</code> (frequency 2). The maximum frequency is 4.</li> <li>The output is <code>2 + 4 = 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">s = &quot;aeiaeia&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The vowels are: <code>&#39;a&#39;</code> (frequency 3), <code>&#39;e&#39;</code> ( frequency 2), <code>&#39;i&#39;</code> (frequency 2). The maximum frequency is 3.</li> <li>There are no consonants in <code>s</code>. Hence, maximum consonant frequency = 0.</li> <li>The output is <code>3 + 0 = 3</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
Hash Table; String; Counting
Go
func maxFreqSum(s string) int { cnt := [26]int{} for _, c := range s { cnt[c-'a']++ } a, b := 0, 0 for i := range cnt { c := byte(i + 'a') if c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' { a = max(a, cnt[i]) } else { b = max(b, cnt[i]) } } return a + b }
3,541
Find Most Frequent Vowel and Consonant
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters (<code>&#39;a&#39;</code> to <code>&#39;z&#39;</code>). </p> <p>Your task is to:</p> <ul> <li>Find the vowel (one of <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, or <code>&#39;u&#39;</code>) with the <strong>maximum</strong> frequency.</li> <li>Find the consonant (all other letters excluding vowels) with the <strong>maximum</strong> frequency.</li> </ul> <p>Return the sum of the two frequencies.</p> <p><strong>Note</strong>: If multiple vowels or consonants have the same maximum frequency, you may choose any one of them. If there are no vowels or no consonants in the string, consider their frequency as 0.</p> The <strong>frequency</strong> of a letter <code>x</code> is the number of times it occurs in the string. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;successes&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The vowels are: <code>&#39;u&#39;</code> (frequency 1), <code>&#39;e&#39;</code> (frequency 2). The maximum frequency is 2.</li> <li>The consonants are: <code>&#39;s&#39;</code> (frequency 4), <code>&#39;c&#39;</code> (frequency 2). The maximum frequency is 4.</li> <li>The output is <code>2 + 4 = 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">s = &quot;aeiaeia&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The vowels are: <code>&#39;a&#39;</code> (frequency 3), <code>&#39;e&#39;</code> ( frequency 2), <code>&#39;i&#39;</code> (frequency 2). The maximum frequency is 3.</li> <li>There are no consonants in <code>s</code>. Hence, maximum consonant frequency = 0.</li> <li>The output is <code>3 + 0 = 3</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
Hash Table; String; Counting
Java
class Solution { public int maxFreqSum(String s) { int[] cnt = new int[26]; for (char c : s.toCharArray()) { ++cnt[c - 'a']; } int a = 0, b = 0; for (int i = 0; i < cnt.length; ++i) { char c = (char) (i + 'a'); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { a = Math.max(a, cnt[i]); } else { b = Math.max(b, cnt[i]); } } return a + b; } }
3,541
Find Most Frequent Vowel and Consonant
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters (<code>&#39;a&#39;</code> to <code>&#39;z&#39;</code>). </p> <p>Your task is to:</p> <ul> <li>Find the vowel (one of <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, or <code>&#39;u&#39;</code>) with the <strong>maximum</strong> frequency.</li> <li>Find the consonant (all other letters excluding vowels) with the <strong>maximum</strong> frequency.</li> </ul> <p>Return the sum of the two frequencies.</p> <p><strong>Note</strong>: If multiple vowels or consonants have the same maximum frequency, you may choose any one of them. If there are no vowels or no consonants in the string, consider their frequency as 0.</p> The <strong>frequency</strong> of a letter <code>x</code> is the number of times it occurs in the string. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;successes&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The vowels are: <code>&#39;u&#39;</code> (frequency 1), <code>&#39;e&#39;</code> (frequency 2). The maximum frequency is 2.</li> <li>The consonants are: <code>&#39;s&#39;</code> (frequency 4), <code>&#39;c&#39;</code> (frequency 2). The maximum frequency is 4.</li> <li>The output is <code>2 + 4 = 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">s = &quot;aeiaeia&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The vowels are: <code>&#39;a&#39;</code> (frequency 3), <code>&#39;e&#39;</code> ( frequency 2), <code>&#39;i&#39;</code> (frequency 2). The maximum frequency is 3.</li> <li>There are no consonants in <code>s</code>. Hence, maximum consonant frequency = 0.</li> <li>The output is <code>3 + 0 = 3</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
Hash Table; String; Counting
Python
class Solution: def maxFreqSum(self, s: str) -> int: cnt = Counter(s) a = b = 0 for c, v in cnt.items(): if c in "aeiou": a = max(a, v) else: b = max(b, v) return a + b
3,541
Find Most Frequent Vowel and Consonant
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters (<code>&#39;a&#39;</code> to <code>&#39;z&#39;</code>). </p> <p>Your task is to:</p> <ul> <li>Find the vowel (one of <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, or <code>&#39;u&#39;</code>) with the <strong>maximum</strong> frequency.</li> <li>Find the consonant (all other letters excluding vowels) with the <strong>maximum</strong> frequency.</li> </ul> <p>Return the sum of the two frequencies.</p> <p><strong>Note</strong>: If multiple vowels or consonants have the same maximum frequency, you may choose any one of them. If there are no vowels or no consonants in the string, consider their frequency as 0.</p> The <strong>frequency</strong> of a letter <code>x</code> is the number of times it occurs in the string. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;successes&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The vowels are: <code>&#39;u&#39;</code> (frequency 1), <code>&#39;e&#39;</code> (frequency 2). The maximum frequency is 2.</li> <li>The consonants are: <code>&#39;s&#39;</code> (frequency 4), <code>&#39;c&#39;</code> (frequency 2). The maximum frequency is 4.</li> <li>The output is <code>2 + 4 = 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">s = &quot;aeiaeia&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The vowels are: <code>&#39;a&#39;</code> (frequency 3), <code>&#39;e&#39;</code> ( frequency 2), <code>&#39;i&#39;</code> (frequency 2). The maximum frequency is 3.</li> <li>There are no consonants in <code>s</code>. Hence, maximum consonant frequency = 0.</li> <li>The output is <code>3 + 0 = 3</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists of lowercase English letters only.</li> </ul>
Hash Table; String; Counting
TypeScript
function maxFreqSum(s: string): number { const cnt: number[] = Array(26).fill(0); for (const c of s) { ++cnt[c.charCodeAt(0) - 97]; } let [a, b] = [0, 0]; for (let i = 0; i < 26; ++i) { const c = String.fromCharCode(i + 97); if ('aeiou'.includes(c)) { a = Math.max(a, cnt[i]); } else { b = Math.max(b, cnt[i]); } } return a + b; }
3,545
Minimum Deletions for At Most K Distinct Characters
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters, and an integer <code>k</code>.</p> <p>Your task is to delete some (possibly none) of the characters in the string so that the number of <strong>distinct</strong> characters in the resulting string is <strong>at most</strong> <code>k</code>.</p> <p>Return the <strong>minimum</strong> number of deletions required to achieve this.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has three distinct characters: <code>&#39;a&#39;</code>, <code>&#39;b&#39;</code> and <code>&#39;c&#39;</code>, each with a frequency of 1.</li> <li>Since we can have at most <code>k = 2</code> distinct characters, remove all occurrences of any one character from the string.</li> <li>For example, removing all occurrences of <code>&#39;c&#39;</code> results in at most <code>k</code> distinct characters. Thus, the answer is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has two distinct characters (<code>&#39;a&#39;</code> and <code>&#39;b&#39;</code>) with frequencies of 2 and 2, respectively.</li> <li>Since we can have at most <code>k = 2</code> distinct characters, no deletions are required. Thus, the answer is 0.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;yyyzz&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has two distinct characters (<code>&#39;y&#39;</code> and <code>&#39;z&#39;</code>) with frequencies of 3 and 2, respectively.</li> <li>Since we can have at most <code>k = 1</code> distinct character, remove all occurrences of any one character from the string.</li> <li>Removing all <code>&#39;z&#39;</code> results in at most <code>k</code> distinct characters. Thus, the answer is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 16</code></li> <li><code>1 &lt;= k &lt;= 16</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul> <p> </p>
Greedy; Hash Table; String; Counting; Sorting
C++
class Solution { public: int minDeletion(string s, int k) { vector<int> cnt(26); for (char c : s) { ++cnt[c - 'a']; } ranges::sort(cnt); int ans = 0; for (int i = 0; i + k < 26; ++i) { ans += cnt[i]; } return ans; } };
3,545
Minimum Deletions for At Most K Distinct Characters
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters, and an integer <code>k</code>.</p> <p>Your task is to delete some (possibly none) of the characters in the string so that the number of <strong>distinct</strong> characters in the resulting string is <strong>at most</strong> <code>k</code>.</p> <p>Return the <strong>minimum</strong> number of deletions required to achieve this.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has three distinct characters: <code>&#39;a&#39;</code>, <code>&#39;b&#39;</code> and <code>&#39;c&#39;</code>, each with a frequency of 1.</li> <li>Since we can have at most <code>k = 2</code> distinct characters, remove all occurrences of any one character from the string.</li> <li>For example, removing all occurrences of <code>&#39;c&#39;</code> results in at most <code>k</code> distinct characters. Thus, the answer is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has two distinct characters (<code>&#39;a&#39;</code> and <code>&#39;b&#39;</code>) with frequencies of 2 and 2, respectively.</li> <li>Since we can have at most <code>k = 2</code> distinct characters, no deletions are required. Thus, the answer is 0.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;yyyzz&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has two distinct characters (<code>&#39;y&#39;</code> and <code>&#39;z&#39;</code>) with frequencies of 3 and 2, respectively.</li> <li>Since we can have at most <code>k = 1</code> distinct character, remove all occurrences of any one character from the string.</li> <li>Removing all <code>&#39;z&#39;</code> results in at most <code>k</code> distinct characters. Thus, the answer is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 16</code></li> <li><code>1 &lt;= k &lt;= 16</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul> <p> </p>
Greedy; Hash Table; String; Counting; Sorting
Go
func minDeletion(s string, k int) (ans int) { cnt := make([]int, 26) for _, c := range s { cnt[c-'a']++ } sort.Ints(cnt) for i := 0; i+k < len(cnt); i++ { ans += cnt[i] } return }
3,545
Minimum Deletions for At Most K Distinct Characters
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters, and an integer <code>k</code>.</p> <p>Your task is to delete some (possibly none) of the characters in the string so that the number of <strong>distinct</strong> characters in the resulting string is <strong>at most</strong> <code>k</code>.</p> <p>Return the <strong>minimum</strong> number of deletions required to achieve this.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has three distinct characters: <code>&#39;a&#39;</code>, <code>&#39;b&#39;</code> and <code>&#39;c&#39;</code>, each with a frequency of 1.</li> <li>Since we can have at most <code>k = 2</code> distinct characters, remove all occurrences of any one character from the string.</li> <li>For example, removing all occurrences of <code>&#39;c&#39;</code> results in at most <code>k</code> distinct characters. Thus, the answer is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has two distinct characters (<code>&#39;a&#39;</code> and <code>&#39;b&#39;</code>) with frequencies of 2 and 2, respectively.</li> <li>Since we can have at most <code>k = 2</code> distinct characters, no deletions are required. Thus, the answer is 0.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;yyyzz&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has two distinct characters (<code>&#39;y&#39;</code> and <code>&#39;z&#39;</code>) with frequencies of 3 and 2, respectively.</li> <li>Since we can have at most <code>k = 1</code> distinct character, remove all occurrences of any one character from the string.</li> <li>Removing all <code>&#39;z&#39;</code> results in at most <code>k</code> distinct characters. Thus, the answer is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 16</code></li> <li><code>1 &lt;= k &lt;= 16</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul> <p> </p>
Greedy; Hash Table; String; Counting; Sorting
Java
class Solution { public int minDeletion(String s, int k) { int[] cnt = new int[26]; for (char c : s.toCharArray()) { ++cnt[c - 'a']; } Arrays.sort(cnt); int ans = 0; for (int i = 0; i + k < 26; ++i) { ans += cnt[i]; } return ans; } }
3,545
Minimum Deletions for At Most K Distinct Characters
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters, and an integer <code>k</code>.</p> <p>Your task is to delete some (possibly none) of the characters in the string so that the number of <strong>distinct</strong> characters in the resulting string is <strong>at most</strong> <code>k</code>.</p> <p>Return the <strong>minimum</strong> number of deletions required to achieve this.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has three distinct characters: <code>&#39;a&#39;</code>, <code>&#39;b&#39;</code> and <code>&#39;c&#39;</code>, each with a frequency of 1.</li> <li>Since we can have at most <code>k = 2</code> distinct characters, remove all occurrences of any one character from the string.</li> <li>For example, removing all occurrences of <code>&#39;c&#39;</code> results in at most <code>k</code> distinct characters. Thus, the answer is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has two distinct characters (<code>&#39;a&#39;</code> and <code>&#39;b&#39;</code>) with frequencies of 2 and 2, respectively.</li> <li>Since we can have at most <code>k = 2</code> distinct characters, no deletions are required. Thus, the answer is 0.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;yyyzz&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has two distinct characters (<code>&#39;y&#39;</code> and <code>&#39;z&#39;</code>) with frequencies of 3 and 2, respectively.</li> <li>Since we can have at most <code>k = 1</code> distinct character, remove all occurrences of any one character from the string.</li> <li>Removing all <code>&#39;z&#39;</code> results in at most <code>k</code> distinct characters. Thus, the answer is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 16</code></li> <li><code>1 &lt;= k &lt;= 16</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul> <p> </p>
Greedy; Hash Table; String; Counting; Sorting
Python
class Solution: def minDeletion(self, s: str, k: int) -> int: return sum(sorted(Counter(s).values())[:-k])
3,545
Minimum Deletions for At Most K Distinct Characters
Easy
<p>You are given a string <code>s</code> consisting of lowercase English letters, and an integer <code>k</code>.</p> <p>Your task is to delete some (possibly none) of the characters in the string so that the number of <strong>distinct</strong> characters in the resulting string is <strong>at most</strong> <code>k</code>.</p> <p>Return the <strong>minimum</strong> number of deletions required to achieve this.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has three distinct characters: <code>&#39;a&#39;</code>, <code>&#39;b&#39;</code> and <code>&#39;c&#39;</code>, each with a frequency of 1.</li> <li>Since we can have at most <code>k = 2</code> distinct characters, remove all occurrences of any one character from the string.</li> <li>For example, removing all occurrences of <code>&#39;c&#39;</code> results in at most <code>k</code> distinct characters. Thus, the answer is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabb&quot;, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has two distinct characters (<code>&#39;a&#39;</code> and <code>&#39;b&#39;</code>) with frequencies of 2 and 2, respectively.</li> <li>Since we can have at most <code>k = 2</code> distinct characters, no deletions are required. Thus, the answer is 0.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;yyyzz&quot;, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>s</code> has two distinct characters (<code>&#39;y&#39;</code> and <code>&#39;z&#39;</code>) with frequencies of 3 and 2, respectively.</li> <li>Since we can have at most <code>k = 1</code> distinct character, remove all occurrences of any one character from the string.</li> <li>Removing all <code>&#39;z&#39;</code> results in at most <code>k</code> distinct characters. Thus, the answer is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 16</code></li> <li><code>1 &lt;= k &lt;= 16</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul> <p> </p>
Greedy; Hash Table; String; Counting; Sorting
TypeScript
function minDeletion(s: string, k: number): number { const cnt: number[] = Array(26).fill(0); for (const c of s) { ++cnt[c.charCodeAt(0) - 97]; } cnt.sort((a, b) => a - b); return cnt.slice(0, 26 - k).reduce((a, b) => a + b, 0); }
3,546
Equal Sum Grid Partition I
Medium
<p>You are given an <code>m x n</code> matrix <code>grid</code> of positive integers. Your task is to determine if it is possible to make <strong>either one horizontal or one vertical cut</strong> on the grid such that:</p> <ul> <li>Each of the two resulting sections formed by the cut is <strong>non-empty</strong>.</li> <li>The sum of the elements in both sections is <strong>equal</strong>.</li> </ul> <p>Return <code>true</code> if such a partition exists; otherwise return <code>false</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">grid = [[1,4],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3546.Equal%20Sum%20Grid%20Partition%20I/images/lc.png" style="width: 200px;" /><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3546.Equal%20Sum%20Grid%20Partition%20I/images/lc.jpeg" style="width: 200px; height: 200px;" /></p> <p>A horizontal cut between row 0 and row 1 results in two non-empty sections, each with a sum of 5. Thus, the answer is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,3],[2,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>No horizontal or vertical cut results in two non-empty sections with equal sums. Thus, the answer is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == grid.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= n == grid[i].length &lt;= 10<sup>5</sup></code></li> <li><code>2 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Enumeration; Matrix; Prefix Sum
C++
class Solution { public: bool canPartitionGrid(vector<vector<int>>& grid) { long long s = 0; for (const auto& row : grid) { for (int x : row) { s += x; } } if (s % 2 != 0) { return false; } int m = grid.size(), n = grid[0].size(); long long pre = 0; for (int i = 0; i < m; ++i) { for (int x : grid[i]) { pre += x; } if (pre * 2 == s && i + 1 < m) { return true; } } pre = 0; for (int j = 0; j < n; ++j) { for (int i = 0; i < m; ++i) { pre += grid[i][j]; } if (pre * 2 == s && j + 1 < n) { return true; } } return false; } };
3,546
Equal Sum Grid Partition I
Medium
<p>You are given an <code>m x n</code> matrix <code>grid</code> of positive integers. Your task is to determine if it is possible to make <strong>either one horizontal or one vertical cut</strong> on the grid such that:</p> <ul> <li>Each of the two resulting sections formed by the cut is <strong>non-empty</strong>.</li> <li>The sum of the elements in both sections is <strong>equal</strong>.</li> </ul> <p>Return <code>true</code> if such a partition exists; otherwise return <code>false</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">grid = [[1,4],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3546.Equal%20Sum%20Grid%20Partition%20I/images/lc.png" style="width: 200px;" /><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3546.Equal%20Sum%20Grid%20Partition%20I/images/lc.jpeg" style="width: 200px; height: 200px;" /></p> <p>A horizontal cut between row 0 and row 1 results in two non-empty sections, each with a sum of 5. Thus, the answer is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,3],[2,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>No horizontal or vertical cut results in two non-empty sections with equal sums. Thus, the answer is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == grid.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= n == grid[i].length &lt;= 10<sup>5</sup></code></li> <li><code>2 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Enumeration; Matrix; Prefix Sum
Go
func canPartitionGrid(grid [][]int) bool { s := 0 for _, row := range grid { for _, x := range row { s += x } } if s%2 != 0 { return false } m, n := len(grid), len(grid[0]) pre := 0 for i, row := range grid { for _, x := range row { pre += x } if pre*2 == s && i+1 < m { return true } } pre = 0 for j := 0; j < n; j++ { for i := 0; i < m; i++ { pre += grid[i][j] } if pre*2 == s && j+1 < n { return true } } return false }
3,546
Equal Sum Grid Partition I
Medium
<p>You are given an <code>m x n</code> matrix <code>grid</code> of positive integers. Your task is to determine if it is possible to make <strong>either one horizontal or one vertical cut</strong> on the grid such that:</p> <ul> <li>Each of the two resulting sections formed by the cut is <strong>non-empty</strong>.</li> <li>The sum of the elements in both sections is <strong>equal</strong>.</li> </ul> <p>Return <code>true</code> if such a partition exists; otherwise return <code>false</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">grid = [[1,4],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3546.Equal%20Sum%20Grid%20Partition%20I/images/lc.png" style="width: 200px;" /><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3546.Equal%20Sum%20Grid%20Partition%20I/images/lc.jpeg" style="width: 200px; height: 200px;" /></p> <p>A horizontal cut between row 0 and row 1 results in two non-empty sections, each with a sum of 5. Thus, the answer is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,3],[2,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>No horizontal or vertical cut results in two non-empty sections with equal sums. Thus, the answer is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == grid.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= n == grid[i].length &lt;= 10<sup>5</sup></code></li> <li><code>2 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Enumeration; Matrix; Prefix Sum
Java
class Solution { public boolean canPartitionGrid(int[][] grid) { long s = 0; for (var row : grid) { for (int x : row) { s += x; } } if (s % 2 != 0) { return false; } int m = grid.length, n = grid[0].length; long pre = 0; for (int i = 0; i < m; ++i) { for (int x : grid[i]) { pre += x; } if (pre * 2 == s && i < m - 1) { return true; } } pre = 0; for (int j = 0; j < n; ++j) { for (int i = 0; i < m; ++i) { pre += grid[i][j]; } if (pre * 2 == s && j < n - 1) { return true; } } return false; } }
3,546
Equal Sum Grid Partition I
Medium
<p>You are given an <code>m x n</code> matrix <code>grid</code> of positive integers. Your task is to determine if it is possible to make <strong>either one horizontal or one vertical cut</strong> on the grid such that:</p> <ul> <li>Each of the two resulting sections formed by the cut is <strong>non-empty</strong>.</li> <li>The sum of the elements in both sections is <strong>equal</strong>.</li> </ul> <p>Return <code>true</code> if such a partition exists; otherwise return <code>false</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">grid = [[1,4],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3546.Equal%20Sum%20Grid%20Partition%20I/images/lc.png" style="width: 200px;" /><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3546.Equal%20Sum%20Grid%20Partition%20I/images/lc.jpeg" style="width: 200px; height: 200px;" /></p> <p>A horizontal cut between row 0 and row 1 results in two non-empty sections, each with a sum of 5. Thus, the answer is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,3],[2,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>No horizontal or vertical cut results in two non-empty sections with equal sums. Thus, the answer is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == grid.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= n == grid[i].length &lt;= 10<sup>5</sup></code></li> <li><code>2 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Enumeration; Matrix; Prefix Sum
Python
class Solution: def canPartitionGrid(self, grid: List[List[int]]) -> bool: s = sum(sum(row) for row in grid) if s % 2: return False pre = 0 for i, row in enumerate(grid): pre += sum(row) if pre * 2 == s and i != len(grid) - 1: return True pre = 0 for j, col in enumerate(zip(*grid)): pre += sum(col) if pre * 2 == s and j != len(grid[0]) - 1: return True return False
3,546
Equal Sum Grid Partition I
Medium
<p>You are given an <code>m x n</code> matrix <code>grid</code> of positive integers. Your task is to determine if it is possible to make <strong>either one horizontal or one vertical cut</strong> on the grid such that:</p> <ul> <li>Each of the two resulting sections formed by the cut is <strong>non-empty</strong>.</li> <li>The sum of the elements in both sections is <strong>equal</strong>.</li> </ul> <p>Return <code>true</code> if such a partition exists; otherwise return <code>false</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">grid = [[1,4],[2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3546.Equal%20Sum%20Grid%20Partition%20I/images/lc.png" style="width: 200px;" /><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3546.Equal%20Sum%20Grid%20Partition%20I/images/lc.jpeg" style="width: 200px; height: 200px;" /></p> <p>A horizontal cut between row 0 and row 1 results in two non-empty sections, each with a sum of 5. Thus, the answer is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,3],[2,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>No horizontal or vertical cut results in two non-empty sections with equal sums. Thus, the answer is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == grid.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= n == grid[i].length &lt;= 10<sup>5</sup></code></li> <li><code>2 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Enumeration; Matrix; Prefix Sum
TypeScript
function canPartitionGrid(grid: number[][]): boolean { let s = 0; for (const row of grid) { s += row.reduce((a, b) => a + b, 0); } if (s % 2 !== 0) { return false; } const [m, n] = [grid.length, grid[0].length]; let pre = 0; for (let i = 0; i < m; ++i) { pre += grid[i].reduce((a, b) => a + b, 0); if (pre * 2 === s && i + 1 < m) { return true; } } pre = 0; for (let j = 0; j < n; ++j) { for (let i = 0; i < m; ++i) { pre += grid[i][j]; } if (pre * 2 === s && j + 1 < n) { return true; } } return false; }
3,549
Multiply Two Polynomials
Hard
<p data-end="315" data-start="119">You are given two integer arrays <code>poly1</code> and <code>poly2</code>, where the element at index <code>i</code> in each array represents the coefficient of <code>x<sup>i</sup></code> in a polynomial.</p> <p>Let <code>A(x)</code> and <code>B(x)</code> be the polynomials represented by <code>poly1</code> and <code>poly2</code>, respectively.</p> <p>Return an integer array <code>result</code> of length <code>(poly1.length + poly2.length - 1)</code> representing the coefficients of the product polynomial <code>R(x) = A(x) * B(x)</code>, where <code>result[i]</code> denotes the coefficient of <code>x<sup>i</sup></code> in <code>R(x)</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">poly1 = [3,2,5], poly2 = [1,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,14,13,20]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 3 + 2x + 5x<sup>2</sup></code> and <code>B(x) = 1 + 4x</code></li> <li><code>R(x) = (3 + 2x + 5x<sup>2</sup>) * (1 + 4x)</code></li> <li><code>R(x) = 3 * 1 + (3 * 4 + 2 * 1)x + (2 * 4 + 5 * 1)x<sup>2</sup> + (5 * 4)x<sup>3</sup></code></li> <li><code>R(x) = 3 + 14x + 13x<sup>2</sup> + 20x<sup>3</sup></code></li> <li>Thus, result = <code>[3, 14, 13, 20]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">poly1 = [1,0,-2], poly2 = [-1]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,0,2]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 1 + 0x - 2x<sup>2</sup></code> and <code>B(x) = -1</code></li> <li><code>R(x) = (1 + 0x - 2x<sup>2</sup>) * (-1)</code></li> <li><code>R(x) = -1 + 0x + 2x<sup>2</sup></code></li> <li>Thus, result = <code>[-1, 0, 2]</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">poly1 = [1,5,-3], poly2 = [-4,2,0]</span></p> <p><strong>Output:</strong> <span class="example-io">[-4,-18,22,-6,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 1 + 5x - 3x<sup>2</sup></code> and <code>B(x) = -4 + 2x + 0x<sup>2</sup></code></li> <li><code>R(x) = (1 + 5x - 3x<sup>2</sup>) * (-4 + 2x + 0x<sup>2</sup>)</code></li> <li><code>R(x) = 1 * -4 + (1 * 2 + 5 * -4)x + (5 * 2 + -3 * -4)x<sup>2</sup> + (-3 * 2)x<sup>3</sup> + 0x<sup>4</sup></code></li> <li><code>R(x) = -4 -18x + 22x<sup>2</sup> -6x<sup>3</sup> + 0x<sup>4</sup></code></li> <li>Thus, result = <code>[-4, -18, 22, -6, 0]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= poly1.length, poly2.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>3</sup> &lt;= poly1[i], poly2[i] &lt;= 10<sup>3</sup></code></li> <li><code>poly1</code> and <code>poly2</code> contain at least one non-zero coefficient.</li> </ul>
Array; Math
C++
class Solution { using cd = complex<double>; void fft(vector<cd>& a, bool invert) { int n = a.size(); for (int i = 1, j = 0; i < n; ++i) { int bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) swap(a[i], a[j]); } for (int len = 2; len <= n; len <<= 1) { double ang = 2 * M_PI / len * (invert ? -1 : 1); cd wlen(cos(ang), sin(ang)); for (int i = 0; i < n; i += len) { cd w(1, 0); int half = len >> 1; for (int j = 0; j < half; ++j) { cd u = a[i + j]; cd v = a[i + j + half] * w; a[i + j] = u + v; a[i + j + half] = u - v; w *= wlen; } } } if (invert) for (cd& x : a) x /= n; } public: vector<long long> multiply(vector<int>& poly1, vector<int>& poly2) { if (poly1.empty() || poly2.empty()) return {}; int m = poly1.size() + poly2.size() - 1; int n = 1; while (n < m) n <<= 1; vector<cd> fa(n), fb(n); for (int i = 0; i < n; ++i) { fa[i] = i < poly1.size() ? cd(poly1[i], 0) : cd(0, 0); fb[i] = i < poly2.size() ? cd(poly2[i], 0) : cd(0, 0); } fft(fa, false); fft(fb, false); for (int i = 0; i < n; ++i) fa[i] *= fb[i]; fft(fa, true); vector<long long> res(m); for (int i = 0; i < m; ++i) res[i] = llround(fa[i].real()); return res; } };
3,549
Multiply Two Polynomials
Hard
<p data-end="315" data-start="119">You are given two integer arrays <code>poly1</code> and <code>poly2</code>, where the element at index <code>i</code> in each array represents the coefficient of <code>x<sup>i</sup></code> in a polynomial.</p> <p>Let <code>A(x)</code> and <code>B(x)</code> be the polynomials represented by <code>poly1</code> and <code>poly2</code>, respectively.</p> <p>Return an integer array <code>result</code> of length <code>(poly1.length + poly2.length - 1)</code> representing the coefficients of the product polynomial <code>R(x) = A(x) * B(x)</code>, where <code>result[i]</code> denotes the coefficient of <code>x<sup>i</sup></code> in <code>R(x)</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">poly1 = [3,2,5], poly2 = [1,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,14,13,20]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 3 + 2x + 5x<sup>2</sup></code> and <code>B(x) = 1 + 4x</code></li> <li><code>R(x) = (3 + 2x + 5x<sup>2</sup>) * (1 + 4x)</code></li> <li><code>R(x) = 3 * 1 + (3 * 4 + 2 * 1)x + (2 * 4 + 5 * 1)x<sup>2</sup> + (5 * 4)x<sup>3</sup></code></li> <li><code>R(x) = 3 + 14x + 13x<sup>2</sup> + 20x<sup>3</sup></code></li> <li>Thus, result = <code>[3, 14, 13, 20]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">poly1 = [1,0,-2], poly2 = [-1]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,0,2]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 1 + 0x - 2x<sup>2</sup></code> and <code>B(x) = -1</code></li> <li><code>R(x) = (1 + 0x - 2x<sup>2</sup>) * (-1)</code></li> <li><code>R(x) = -1 + 0x + 2x<sup>2</sup></code></li> <li>Thus, result = <code>[-1, 0, 2]</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">poly1 = [1,5,-3], poly2 = [-4,2,0]</span></p> <p><strong>Output:</strong> <span class="example-io">[-4,-18,22,-6,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 1 + 5x - 3x<sup>2</sup></code> and <code>B(x) = -4 + 2x + 0x<sup>2</sup></code></li> <li><code>R(x) = (1 + 5x - 3x<sup>2</sup>) * (-4 + 2x + 0x<sup>2</sup>)</code></li> <li><code>R(x) = 1 * -4 + (1 * 2 + 5 * -4)x + (5 * 2 + -3 * -4)x<sup>2</sup> + (-3 * 2)x<sup>3</sup> + 0x<sup>4</sup></code></li> <li><code>R(x) = -4 -18x + 22x<sup>2</sup> -6x<sup>3</sup> + 0x<sup>4</sup></code></li> <li>Thus, result = <code>[-4, -18, 22, -6, 0]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= poly1.length, poly2.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>3</sup> &lt;= poly1[i], poly2[i] &lt;= 10<sup>3</sup></code></li> <li><code>poly1</code> and <code>poly2</code> contain at least one non-zero coefficient.</li> </ul>
Array; Math
Go
func multiply(poly1 []int, poly2 []int) []int64 { if len(poly1) == 0 || len(poly2) == 0 { return []int64{} } m := len(poly1) + len(poly2) - 1 n := 1 for n < m { n <<= 1 } fa := make([]complex128, n) fb := make([]complex128, n) for i := 0; i < len(poly1); i++ { fa[i] = complex(float64(poly1[i]), 0) } for i := 0; i < len(poly2); i++ { fb[i] = complex(float64(poly2[i]), 0) } fft(fa, false) fft(fb, false) for i := 0; i < n; i++ { fa[i] *= fb[i] } fft(fa, true) res := make([]int64, m) for i := 0; i < m; i++ { res[i] = int64(math.Round(real(fa[i]))) } return res } func fft(a []complex128, invert bool) { n := len(a) for i, j := 1, 0; i < n; i++ { bit := n >> 1 for ; j&bit != 0; bit >>= 1 { j ^= bit } j ^= bit if i < j { a[i], a[j] = a[j], a[i] } } for length := 2; length <= n; length <<= 1 { angle := 2 * math.Pi / float64(length) if invert { angle = -angle } wlen := cmplx.Rect(1, angle) for i := 0; i < n; i += length { w := complex(1, 0) half := length >> 1 for j := 0; j < half; j++ { u := a[i+j] v := a[i+j+half] * w a[i+j] = u + v a[i+j+half] = u - v w *= wlen } } } if invert { for i := range a { a[i] /= complex(float64(n), 0) } } }
3,549
Multiply Two Polynomials
Hard
<p data-end="315" data-start="119">You are given two integer arrays <code>poly1</code> and <code>poly2</code>, where the element at index <code>i</code> in each array represents the coefficient of <code>x<sup>i</sup></code> in a polynomial.</p> <p>Let <code>A(x)</code> and <code>B(x)</code> be the polynomials represented by <code>poly1</code> and <code>poly2</code>, respectively.</p> <p>Return an integer array <code>result</code> of length <code>(poly1.length + poly2.length - 1)</code> representing the coefficients of the product polynomial <code>R(x) = A(x) * B(x)</code>, where <code>result[i]</code> denotes the coefficient of <code>x<sup>i</sup></code> in <code>R(x)</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">poly1 = [3,2,5], poly2 = [1,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,14,13,20]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 3 + 2x + 5x<sup>2</sup></code> and <code>B(x) = 1 + 4x</code></li> <li><code>R(x) = (3 + 2x + 5x<sup>2</sup>) * (1 + 4x)</code></li> <li><code>R(x) = 3 * 1 + (3 * 4 + 2 * 1)x + (2 * 4 + 5 * 1)x<sup>2</sup> + (5 * 4)x<sup>3</sup></code></li> <li><code>R(x) = 3 + 14x + 13x<sup>2</sup> + 20x<sup>3</sup></code></li> <li>Thus, result = <code>[3, 14, 13, 20]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">poly1 = [1,0,-2], poly2 = [-1]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,0,2]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 1 + 0x - 2x<sup>2</sup></code> and <code>B(x) = -1</code></li> <li><code>R(x) = (1 + 0x - 2x<sup>2</sup>) * (-1)</code></li> <li><code>R(x) = -1 + 0x + 2x<sup>2</sup></code></li> <li>Thus, result = <code>[-1, 0, 2]</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">poly1 = [1,5,-3], poly2 = [-4,2,0]</span></p> <p><strong>Output:</strong> <span class="example-io">[-4,-18,22,-6,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 1 + 5x - 3x<sup>2</sup></code> and <code>B(x) = -4 + 2x + 0x<sup>2</sup></code></li> <li><code>R(x) = (1 + 5x - 3x<sup>2</sup>) * (-4 + 2x + 0x<sup>2</sup>)</code></li> <li><code>R(x) = 1 * -4 + (1 * 2 + 5 * -4)x + (5 * 2 + -3 * -4)x<sup>2</sup> + (-3 * 2)x<sup>3</sup> + 0x<sup>4</sup></code></li> <li><code>R(x) = -4 -18x + 22x<sup>2</sup> -6x<sup>3</sup> + 0x<sup>4</sup></code></li> <li>Thus, result = <code>[-4, -18, 22, -6, 0]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= poly1.length, poly2.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>3</sup> &lt;= poly1[i], poly2[i] &lt;= 10<sup>3</sup></code></li> <li><code>poly1</code> and <code>poly2</code> contain at least one non-zero coefficient.</li> </ul>
Array; Math
Java
class Solution { public long[] multiply(int[] poly1, int[] poly2) { if (poly1 == null || poly2 == null || poly1.length == 0 || poly2.length == 0) { return new long[0]; } int m = poly1.length + poly2.length - 1; int n = 1; while (n < m) n <<= 1; Complex[] fa = new Complex[n]; Complex[] fb = new Complex[n]; for (int i = 0; i < n; i++) { fa[i] = new Complex(i < poly1.length ? poly1[i] : 0, 0); fb[i] = new Complex(i < poly2.length ? poly2[i] : 0, 0); } fft(fa, false); fft(fb, false); for (int i = 0; i < n; i++) { fa[i] = fa[i].mul(fb[i]); } fft(fa, true); long[] res = new long[m]; for (int i = 0; i < m; i++) { res[i] = Math.round(fa[i].re); } return res; } private static void fft(Complex[] a, boolean invert) { int n = a.length; for (int i = 1, j = 0; i < n; i++) { int bit = n >>> 1; while ((j & bit) != 0) { j ^= bit; bit >>>= 1; } j ^= bit; if (i < j) { Complex tmp = a[i]; a[i] = a[j]; a[j] = tmp; } } for (int len = 2; len <= n; len <<= 1) { double ang = 2 * Math.PI / len * (invert ? -1 : 1); Complex wlen = new Complex(Math.cos(ang), Math.sin(ang)); for (int i = 0; i < n; i += len) { Complex w = new Complex(1, 0); int half = len >>> 1; for (int j = 0; j < half; j++) { Complex u = a[i + j]; Complex v = a[i + j + half].mul(w); a[i + j] = u.add(v); a[i + j + half] = u.sub(v); w = w.mul(wlen); } } } if (invert) { for (int i = 0; i < n; i++) { a[i].re /= n; a[i].im /= n; } } } private static final class Complex { double re, im; Complex(double re, double im) { this.re = re; this.im = im; } Complex add(Complex o) { return new Complex(re + o.re, im + o.im); } Complex sub(Complex o) { return new Complex(re - o.re, im - o.im); } Complex mul(Complex o) { return new Complex(re * o.re - im * o.im, re * o.im + im * o.re); } } }
3,549
Multiply Two Polynomials
Hard
<p data-end="315" data-start="119">You are given two integer arrays <code>poly1</code> and <code>poly2</code>, where the element at index <code>i</code> in each array represents the coefficient of <code>x<sup>i</sup></code> in a polynomial.</p> <p>Let <code>A(x)</code> and <code>B(x)</code> be the polynomials represented by <code>poly1</code> and <code>poly2</code>, respectively.</p> <p>Return an integer array <code>result</code> of length <code>(poly1.length + poly2.length - 1)</code> representing the coefficients of the product polynomial <code>R(x) = A(x) * B(x)</code>, where <code>result[i]</code> denotes the coefficient of <code>x<sup>i</sup></code> in <code>R(x)</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">poly1 = [3,2,5], poly2 = [1,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,14,13,20]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 3 + 2x + 5x<sup>2</sup></code> and <code>B(x) = 1 + 4x</code></li> <li><code>R(x) = (3 + 2x + 5x<sup>2</sup>) * (1 + 4x)</code></li> <li><code>R(x) = 3 * 1 + (3 * 4 + 2 * 1)x + (2 * 4 + 5 * 1)x<sup>2</sup> + (5 * 4)x<sup>3</sup></code></li> <li><code>R(x) = 3 + 14x + 13x<sup>2</sup> + 20x<sup>3</sup></code></li> <li>Thus, result = <code>[3, 14, 13, 20]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">poly1 = [1,0,-2], poly2 = [-1]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,0,2]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 1 + 0x - 2x<sup>2</sup></code> and <code>B(x) = -1</code></li> <li><code>R(x) = (1 + 0x - 2x<sup>2</sup>) * (-1)</code></li> <li><code>R(x) = -1 + 0x + 2x<sup>2</sup></code></li> <li>Thus, result = <code>[-1, 0, 2]</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">poly1 = [1,5,-3], poly2 = [-4,2,0]</span></p> <p><strong>Output:</strong> <span class="example-io">[-4,-18,22,-6,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 1 + 5x - 3x<sup>2</sup></code> and <code>B(x) = -4 + 2x + 0x<sup>2</sup></code></li> <li><code>R(x) = (1 + 5x - 3x<sup>2</sup>) * (-4 + 2x + 0x<sup>2</sup>)</code></li> <li><code>R(x) = 1 * -4 + (1 * 2 + 5 * -4)x + (5 * 2 + -3 * -4)x<sup>2</sup> + (-3 * 2)x<sup>3</sup> + 0x<sup>4</sup></code></li> <li><code>R(x) = -4 -18x + 22x<sup>2</sup> -6x<sup>3</sup> + 0x<sup>4</sup></code></li> <li>Thus, result = <code>[-4, -18, 22, -6, 0]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= poly1.length, poly2.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>3</sup> &lt;= poly1[i], poly2[i] &lt;= 10<sup>3</sup></code></li> <li><code>poly1</code> and <code>poly2</code> contain at least one non-zero coefficient.</li> </ul>
Array; Math
Python
class Solution: def multiply(self, poly1: List[int], poly2: List[int]) -> List[int]: if not poly1 or not poly2: return [] m = len(poly1) + len(poly2) - 1 n = 1 while n < m: n <<= 1 fa = list(map(complex, poly1)) + [0j] * (n - len(poly1)) fb = list(map(complex, poly2)) + [0j] * (n - len(poly2)) self._fft(fa, invert=False) self._fft(fb, invert=False) for i in range(n): fa[i] *= fb[i] self._fft(fa, invert=True) return [int(round(fa[i].real)) for i in range(m)] def _fft(self, a: List[complex], invert: bool) -> None: n = len(a) j = 0 for i in range(1, n): bit = n >> 1 while j & bit: j ^= bit bit >>= 1 j ^= bit if i < j: a[i], a[j] = a[j], a[i] len_ = 2 while len_ <= n: ang = 2 * math.pi / len_ * (-1 if invert else 1) wlen = complex(math.cos(ang), math.sin(ang)) for i in range(0, n, len_): w = 1 + 0j half = i + len_ // 2 for j in range(i, half): u = a[j] v = a[j + len_ // 2] * w a[j] = u + v a[j + len_ // 2] = u - v w *= wlen len_ <<= 1 if invert: for i in range(n): a[i] /= n
3,549
Multiply Two Polynomials
Hard
<p data-end="315" data-start="119">You are given two integer arrays <code>poly1</code> and <code>poly2</code>, where the element at index <code>i</code> in each array represents the coefficient of <code>x<sup>i</sup></code> in a polynomial.</p> <p>Let <code>A(x)</code> and <code>B(x)</code> be the polynomials represented by <code>poly1</code> and <code>poly2</code>, respectively.</p> <p>Return an integer array <code>result</code> of length <code>(poly1.length + poly2.length - 1)</code> representing the coefficients of the product polynomial <code>R(x) = A(x) * B(x)</code>, where <code>result[i]</code> denotes the coefficient of <code>x<sup>i</sup></code> in <code>R(x)</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">poly1 = [3,2,5], poly2 = [1,4]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,14,13,20]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 3 + 2x + 5x<sup>2</sup></code> and <code>B(x) = 1 + 4x</code></li> <li><code>R(x) = (3 + 2x + 5x<sup>2</sup>) * (1 + 4x)</code></li> <li><code>R(x) = 3 * 1 + (3 * 4 + 2 * 1)x + (2 * 4 + 5 * 1)x<sup>2</sup> + (5 * 4)x<sup>3</sup></code></li> <li><code>R(x) = 3 + 14x + 13x<sup>2</sup> + 20x<sup>3</sup></code></li> <li>Thus, result = <code>[3, 14, 13, 20]</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">poly1 = [1,0,-2], poly2 = [-1]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,0,2]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 1 + 0x - 2x<sup>2</sup></code> and <code>B(x) = -1</code></li> <li><code>R(x) = (1 + 0x - 2x<sup>2</sup>) * (-1)</code></li> <li><code>R(x) = -1 + 0x + 2x<sup>2</sup></code></li> <li>Thus, result = <code>[-1, 0, 2]</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">poly1 = [1,5,-3], poly2 = [-4,2,0]</span></p> <p><strong>Output:</strong> <span class="example-io">[-4,-18,22,-6,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>A(x) = 1 + 5x - 3x<sup>2</sup></code> and <code>B(x) = -4 + 2x + 0x<sup>2</sup></code></li> <li><code>R(x) = (1 + 5x - 3x<sup>2</sup>) * (-4 + 2x + 0x<sup>2</sup>)</code></li> <li><code>R(x) = 1 * -4 + (1 * 2 + 5 * -4)x + (5 * 2 + -3 * -4)x<sup>2</sup> + (-3 * 2)x<sup>3</sup> + 0x<sup>4</sup></code></li> <li><code>R(x) = -4 -18x + 22x<sup>2</sup> -6x<sup>3</sup> + 0x<sup>4</sup></code></li> <li>Thus, result = <code>[-4, -18, 22, -6, 0]</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= poly1.length, poly2.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>3</sup> &lt;= poly1[i], poly2[i] &lt;= 10<sup>3</sup></code></li> <li><code>poly1</code> and <code>poly2</code> contain at least one non-zero coefficient.</li> </ul>
Array; Math
TypeScript
export function multiply(poly1: number[], poly2: number[]): number[] { const n1 = poly1.length, n2 = poly2.length; if (!n1 || !n2) return []; if (Math.min(n1, n2) <= 64) { const m = n1 + n2 - 1, res = new Array<number>(m).fill(0); for (let i = 0; i < n1; ++i) for (let j = 0; j < n2; ++j) res[i + j] += poly1[i] * poly2[j]; return res.map(v => Math.round(v)); } let n = 1, m = n1 + n2 - 1; while (n < m) n <<= 1; const reA = new Float64Array(n); const imA = new Float64Array(n); for (let i = 0; i < n1; ++i) reA[i] = poly1[i]; const reB = new Float64Array(n); const imB = new Float64Array(n); for (let i = 0; i < n2; ++i) reB[i] = poly2[i]; fft(reA, imA, false); fft(reB, imB, false); for (let i = 0; i < n; ++i) { const a = reA[i], b = imA[i], c = reB[i], d = imB[i]; reA[i] = a * c - b * d; imA[i] = a * d + b * c; } fft(reA, imA, true); const out = new Array<number>(m); for (let i = 0; i < m; ++i) out[i] = Math.round(reA[i]); return out; } function fft(re: Float64Array, im: Float64Array, invert: boolean): void { const n = re.length; for (let i = 1, j = 0; i < n; ++i) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; } } for (let len = 2; len <= n; len <<= 1) { const ang = ((2 * Math.PI) / len) * (invert ? -1 : 1); const wlenCos = Math.cos(ang), wlenSin = Math.sin(ang); for (let i = 0; i < n; i += len) { let wRe = 1, wIm = 0; const half = len >> 1; for (let j = 0; j < half; ++j) { const uRe = re[i + j], uIm = im[i + j]; const vRe0 = re[i + j + half], vIm0 = im[i + j + half]; const vRe = vRe0 * wRe - vIm0 * wIm; const vIm = vRe0 * wIm + vIm0 * wRe; re[i + j] = uRe + vRe; im[i + j] = uIm + vIm; re[i + j + half] = uRe - vRe; im[i + j + half] = uIm - vIm; const nextWRe = wRe * wlenCos - wIm * wlenSin; wIm = wRe * wlenSin + wIm * wlenCos; wRe = nextWRe; } } } if (invert) { for (let i = 0; i < n; ++i) { re[i] /= n; im[i] /= n; } } }
3,550
Smallest Index With Digit Sum Equal to Index
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>Return the <strong>smallest</strong> index <code>i</code> such that the sum of the digits of <code>nums[i]</code> is equal to <code>i</code>.</p> <p>If no such index exists, 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 = [1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>nums[2] = 2</code>, the sum of digits is 2, which is equal to index <code>i = 2</code>. 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">nums = [1,10,11]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>nums[1] = 10</code>, the sum of digits is <code>1 + 0 = 1</code>, which is equal to index <code>i = 1</code>.</li> <li>For <code>nums[2] = 11</code>, the sum of digits is <code>1 + 1 = 2</code>, which is equal to index <code>i = 2</code>.</li> <li>Since index 1 is the smallest, the output is 1.</li> </ul> </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">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no index satisfies the condition, the output is -1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Math
C++
class Solution { public: int smallestIndex(vector<int>& nums) { for (int i = 0; i < nums.size(); ++i) { int s = 0; while (nums[i]) { s += nums[i] % 10; nums[i] /= 10; } if (s == i) { return i; } } return -1; } };
3,550
Smallest Index With Digit Sum Equal to Index
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>Return the <strong>smallest</strong> index <code>i</code> such that the sum of the digits of <code>nums[i]</code> is equal to <code>i</code>.</p> <p>If no such index exists, 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 = [1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>nums[2] = 2</code>, the sum of digits is 2, which is equal to index <code>i = 2</code>. 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">nums = [1,10,11]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>nums[1] = 10</code>, the sum of digits is <code>1 + 0 = 1</code>, which is equal to index <code>i = 1</code>.</li> <li>For <code>nums[2] = 11</code>, the sum of digits is <code>1 + 1 = 2</code>, which is equal to index <code>i = 2</code>.</li> <li>Since index 1 is the smallest, the output is 1.</li> </ul> </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">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no index satisfies the condition, the output is -1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Math
Go
func smallestIndex(nums []int) int { for i, x := range nums { s := 0 for ; x > 0; x /= 10 { s += x % 10 } if s == i { return i } } return -1 }
3,550
Smallest Index With Digit Sum Equal to Index
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>Return the <strong>smallest</strong> index <code>i</code> such that the sum of the digits of <code>nums[i]</code> is equal to <code>i</code>.</p> <p>If no such index exists, 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 = [1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>nums[2] = 2</code>, the sum of digits is 2, which is equal to index <code>i = 2</code>. 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">nums = [1,10,11]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>nums[1] = 10</code>, the sum of digits is <code>1 + 0 = 1</code>, which is equal to index <code>i = 1</code>.</li> <li>For <code>nums[2] = 11</code>, the sum of digits is <code>1 + 1 = 2</code>, which is equal to index <code>i = 2</code>.</li> <li>Since index 1 is the smallest, the output is 1.</li> </ul> </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">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no index satisfies the condition, the output is -1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Math
Java
class Solution { public int smallestIndex(int[] nums) { for (int i = 0; i < nums.length; ++i) { int s = 0; while (nums[i] != 0) { s += nums[i] % 10; nums[i] /= 10; } if (s == i) { return i; } } return -1; } }
3,550
Smallest Index With Digit Sum Equal to Index
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>Return the <strong>smallest</strong> index <code>i</code> such that the sum of the digits of <code>nums[i]</code> is equal to <code>i</code>.</p> <p>If no such index exists, 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 = [1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>nums[2] = 2</code>, the sum of digits is 2, which is equal to index <code>i = 2</code>. 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">nums = [1,10,11]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>nums[1] = 10</code>, the sum of digits is <code>1 + 0 = 1</code>, which is equal to index <code>i = 1</code>.</li> <li>For <code>nums[2] = 11</code>, the sum of digits is <code>1 + 1 = 2</code>, which is equal to index <code>i = 2</code>.</li> <li>Since index 1 is the smallest, the output is 1.</li> </ul> </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">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no index satisfies the condition, the output is -1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Math
Python
class Solution: def smallestIndex(self, nums: List[int]) -> int: for i, x in enumerate(nums): s = 0 while x: s += x % 10 x //= 10 if s == i: return i return -1
3,550
Smallest Index With Digit Sum Equal to Index
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>Return the <strong>smallest</strong> index <code>i</code> such that the sum of the digits of <code>nums[i]</code> is equal to <code>i</code>.</p> <p>If no such index exists, 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 = [1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>nums[2] = 2</code>, the sum of digits is 2, which is equal to index <code>i = 2</code>. 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">nums = [1,10,11]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>For <code>nums[1] = 10</code>, the sum of digits is <code>1 + 0 = 1</code>, which is equal to index <code>i = 1</code>.</li> <li>For <code>nums[2] = 11</code>, the sum of digits is <code>1 + 1 = 2</code>, which is equal to index <code>i = 2</code>.</li> <li>Since index 1 is the smallest, the output is 1.</li> </ul> </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">-1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Since no index satisfies the condition, the output is -1.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Math
TypeScript
function smallestIndex(nums: number[]): number { for (let i = 0; i < nums.length; ++i) { let s = 0; for (; nums[i] > 0; nums[i] = Math.floor(nums[i] / 10)) { s += nums[i] % 10; } if (s === i) { return i; } } return -1; }
3,551
Minimum Swaps to Sort by Digit Sum
Medium
<p>You are given an array <code>nums</code> of <strong>distinct</strong> positive integers. You need to sort the array in <strong>increasing</strong> order based on the sum of the digits of each number. If two numbers have the same digit sum, the <strong>smaller</strong> number appears first in the sorted order.</p> <p>Return the <strong>minimum</strong> number of swaps required to rearrange <code>nums</code> into this sorted order.</p> <p>A <strong>swap</strong> is defined as exchanging the values at two distinct positions in the 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">nums = [37,100]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[3 + 7 = 10, 1 + 0 + 0 = 1] &rarr; [10, 1]</code></li> <li>Sort the integers based on digit sum: <code>[100, 37]</code>. Swap <code>37</code> with <code>100</code> to obtain the sorted order.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [22,14,33,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[2 + 2 = 4, 1 + 4 = 5, 3 + 3 = 6, 7 = 7] &rarr; [4, 5, 6, 7]</code></li> <li>Sort the integers based on digit sum: <code>[22, 14, 33, 7]</code>. The array is already sorted.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 0.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [18,43,34,16]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[1 + 8 = 9, 4 + 3 = 7, 3 + 4 = 7, 1 + 6 = 7] &rarr; [9, 7, 7, 7]</code></li> <li>Sort the integers based on digit sum: <code>[16, 34, 43, 18]</code>. Swap <code>18</code> with <code>16</code>, and swap <code>43</code> with <code>34</code> to obtain the sorted order.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> consists of <strong>distinct</strong> positive integers.</li> </ul>
Array; Hash Table; Sorting
C++
class Solution { public: int f(int x) { int s = 0; while (x) { s += x % 10; x /= 10; } return s; } int minSwaps(vector<int>& nums) { int n = nums.size(); vector<pair<int, int>> arr(n); for (int i = 0; i < n; ++i) arr[i] = {f(nums[i]), nums[i]}; sort(arr.begin(), arr.end()); unordered_map<int, int> d; for (int i = 0; i < n; ++i) d[arr[i].second] = i; vector<char> vis(n, 0); int ans = n; for (int i = 0; i < n; ++i) { if (!vis[i]) { --ans; int j = i; while (!vis[j]) { vis[j] = 1; j = d[nums[j]]; } } } return ans; } };
3,551
Minimum Swaps to Sort by Digit Sum
Medium
<p>You are given an array <code>nums</code> of <strong>distinct</strong> positive integers. You need to sort the array in <strong>increasing</strong> order based on the sum of the digits of each number. If two numbers have the same digit sum, the <strong>smaller</strong> number appears first in the sorted order.</p> <p>Return the <strong>minimum</strong> number of swaps required to rearrange <code>nums</code> into this sorted order.</p> <p>A <strong>swap</strong> is defined as exchanging the values at two distinct positions in the 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">nums = [37,100]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[3 + 7 = 10, 1 + 0 + 0 = 1] &rarr; [10, 1]</code></li> <li>Sort the integers based on digit sum: <code>[100, 37]</code>. Swap <code>37</code> with <code>100</code> to obtain the sorted order.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [22,14,33,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[2 + 2 = 4, 1 + 4 = 5, 3 + 3 = 6, 7 = 7] &rarr; [4, 5, 6, 7]</code></li> <li>Sort the integers based on digit sum: <code>[22, 14, 33, 7]</code>. The array is already sorted.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 0.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [18,43,34,16]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[1 + 8 = 9, 4 + 3 = 7, 3 + 4 = 7, 1 + 6 = 7] &rarr; [9, 7, 7, 7]</code></li> <li>Sort the integers based on digit sum: <code>[16, 34, 43, 18]</code>. Swap <code>18</code> with <code>16</code>, and swap <code>43</code> with <code>34</code> to obtain the sorted order.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> consists of <strong>distinct</strong> positive integers.</li> </ul>
Array; Hash Table; Sorting
Go
func minSwaps(nums []int) int { n := len(nums) arr := make([][2]int, n) for i := 0; i < n; i++ { arr[i][0] = f(nums[i]) arr[i][1] = nums[i] } sort.Slice(arr, func(i, j int) bool { if arr[i][0] != arr[j][0] { return arr[i][0] < arr[j][0] } return arr[i][1] < arr[j][1] }) d := make(map[int]int, n) for i := 0; i < n; i++ { d[arr[i][1]] = i } vis := make([]bool, n) ans := n for i := 0; i < n; i++ { if !vis[i] { ans-- j := i for !vis[j] { vis[j] = true j = d[nums[j]] } } } return ans } func f(x int) int { s := 0 for x != 0 { s += x % 10 x /= 10 } return s }
3,551
Minimum Swaps to Sort by Digit Sum
Medium
<p>You are given an array <code>nums</code> of <strong>distinct</strong> positive integers. You need to sort the array in <strong>increasing</strong> order based on the sum of the digits of each number. If two numbers have the same digit sum, the <strong>smaller</strong> number appears first in the sorted order.</p> <p>Return the <strong>minimum</strong> number of swaps required to rearrange <code>nums</code> into this sorted order.</p> <p>A <strong>swap</strong> is defined as exchanging the values at two distinct positions in the 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">nums = [37,100]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[3 + 7 = 10, 1 + 0 + 0 = 1] &rarr; [10, 1]</code></li> <li>Sort the integers based on digit sum: <code>[100, 37]</code>. Swap <code>37</code> with <code>100</code> to obtain the sorted order.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [22,14,33,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[2 + 2 = 4, 1 + 4 = 5, 3 + 3 = 6, 7 = 7] &rarr; [4, 5, 6, 7]</code></li> <li>Sort the integers based on digit sum: <code>[22, 14, 33, 7]</code>. The array is already sorted.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 0.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [18,43,34,16]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[1 + 8 = 9, 4 + 3 = 7, 3 + 4 = 7, 1 + 6 = 7] &rarr; [9, 7, 7, 7]</code></li> <li>Sort the integers based on digit sum: <code>[16, 34, 43, 18]</code>. Swap <code>18</code> with <code>16</code>, and swap <code>43</code> with <code>34</code> to obtain the sorted order.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> consists of <strong>distinct</strong> positive integers.</li> </ul>
Array; Hash Table; Sorting
Java
class Solution { public int minSwaps(int[] nums) { int n = nums.length; int[][] arr = new int[n][2]; for (int i = 0; i < n; i++) { arr[i][0] = f(nums[i]); arr[i][1] = nums[i]; } Arrays.sort(arr, (a, b) -> { if (a[0] != b[0]) return Integer.compare(a[0], b[0]); return Integer.compare(a[1], b[1]); }); Map<Integer, Integer> d = new HashMap<>(); for (int i = 0; i < n; i++) { d.put(arr[i][1], i); } boolean[] vis = new boolean[n]; int ans = n; for (int i = 0; i < n; i++) { if (!vis[i]) { ans--; int j = i; while (!vis[j]) { vis[j] = true; j = d.get(nums[j]); } } } return ans; } private int f(int x) { int s = 0; while (x != 0) { s += x % 10; x /= 10; } return s; } }
3,551
Minimum Swaps to Sort by Digit Sum
Medium
<p>You are given an array <code>nums</code> of <strong>distinct</strong> positive integers. You need to sort the array in <strong>increasing</strong> order based on the sum of the digits of each number. If two numbers have the same digit sum, the <strong>smaller</strong> number appears first in the sorted order.</p> <p>Return the <strong>minimum</strong> number of swaps required to rearrange <code>nums</code> into this sorted order.</p> <p>A <strong>swap</strong> is defined as exchanging the values at two distinct positions in the 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">nums = [37,100]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[3 + 7 = 10, 1 + 0 + 0 = 1] &rarr; [10, 1]</code></li> <li>Sort the integers based on digit sum: <code>[100, 37]</code>. Swap <code>37</code> with <code>100</code> to obtain the sorted order.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [22,14,33,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[2 + 2 = 4, 1 + 4 = 5, 3 + 3 = 6, 7 = 7] &rarr; [4, 5, 6, 7]</code></li> <li>Sort the integers based on digit sum: <code>[22, 14, 33, 7]</code>. The array is already sorted.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 0.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [18,43,34,16]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[1 + 8 = 9, 4 + 3 = 7, 3 + 4 = 7, 1 + 6 = 7] &rarr; [9, 7, 7, 7]</code></li> <li>Sort the integers based on digit sum: <code>[16, 34, 43, 18]</code>. Swap <code>18</code> with <code>16</code>, and swap <code>43</code> with <code>34</code> to obtain the sorted order.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> consists of <strong>distinct</strong> positive integers.</li> </ul>
Array; Hash Table; Sorting
Python
class Solution: def minSwaps(self, nums: List[int]) -> int: def f(x: int) -> int: s = 0 while x: s += x % 10 x //= 10 return s n = len(nums) arr = sorted((f(x), x) for x in nums) d = {a[1]: i for i, a in enumerate(arr)} ans = n vis = [False] * n for i in range(n): if not vis[i]: ans -= 1 j = i while not vis[j]: vis[j] = True j = d[nums[j]] return ans
3,551
Minimum Swaps to Sort by Digit Sum
Medium
<p>You are given an array <code>nums</code> of <strong>distinct</strong> positive integers. You need to sort the array in <strong>increasing</strong> order based on the sum of the digits of each number. If two numbers have the same digit sum, the <strong>smaller</strong> number appears first in the sorted order.</p> <p>Return the <strong>minimum</strong> number of swaps required to rearrange <code>nums</code> into this sorted order.</p> <p>A <strong>swap</strong> is defined as exchanging the values at two distinct positions in the 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">nums = [37,100]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[3 + 7 = 10, 1 + 0 + 0 = 1] &rarr; [10, 1]</code></li> <li>Sort the integers based on digit sum: <code>[100, 37]</code>. Swap <code>37</code> with <code>100</code> to obtain the sorted order.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [22,14,33,7]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[2 + 2 = 4, 1 + 4 = 5, 3 + 3 = 6, 7 = 7] &rarr; [4, 5, 6, 7]</code></li> <li>Sort the integers based on digit sum: <code>[22, 14, 33, 7]</code>. The array is already sorted.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 0.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [18,43,34,16]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Compute the digit sum for each integer: <code>[1 + 8 = 9, 4 + 3 = 7, 3 + 4 = 7, 1 + 6 = 7] &rarr; [9, 7, 7, 7]</code></li> <li>Sort the integers based on digit sum: <code>[16, 34, 43, 18]</code>. Swap <code>18</code> with <code>16</code>, and swap <code>43</code> with <code>34</code> to obtain the sorted order.</li> <li>Thus, the minimum number of swaps required to rearrange <code>nums</code> is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>nums</code> consists of <strong>distinct</strong> positive integers.</li> </ul>
Array; Hash Table; Sorting
TypeScript
function f(x: number): number { let s = 0; while (x !== 0) { s += x % 10; x = Math.floor(x / 10); } return s; } function minSwaps(nums: number[]): number { const n = nums.length; const arr: [number, number][] = new Array(n); for (let i = 0; i < n; i++) { arr[i] = [f(nums[i]), nums[i]]; } arr.sort((a, b) => (a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1])); const d = new Map<number, number>(); for (let i = 0; i < n; i++) { d.set(arr[i][1], i); } const vis: boolean[] = new Array(n).fill(false); let ans = n; for (let i = 0; i < n; i++) { if (!vis[i]) { ans--; let j = i; while (!vis[j]) { vis[j] = true; j = d.get(nums[j])!; } } } return ans; }
3,552
Grid Teleportation Traversal
Medium
<p>You are given a 2D character grid <code>matrix</code> of size <code>m x n</code>, represented as an array of strings, where <code>matrix[i][j]</code> represents the cell at the intersection of the <code>i<sup>th</sup></code> row and <code>j<sup>th</sup></code> column. Each cell is one of the following:</p> <ul> <li><code>&#39;.&#39;</code> representing an empty cell.</li> <li><code>&#39;#&#39;</code> representing an obstacle.</li> <li>An uppercase letter (<code>&#39;A&#39;</code>-<code>&#39;Z&#39;</code>) representing a teleportation portal.</li> </ul> <p>You start at the top-left cell <code>(0, 0)</code>, and your goal is to reach the bottom-right cell <code>(m - 1, n - 1)</code>. You can move from the current cell to any adjacent cell (up, down, left, right) as long as the destination cell is within the grid bounds and is not an obstacle<strong>.</strong></p> <p>If you step on a cell containing a portal letter and you haven&#39;t used that portal letter before, you may instantly teleport to any other cell in the grid with the same letter. This teleportation does not count as a move, but each portal letter can be used<strong> at most </strong>once during your journey.</p> <p>Return the <strong>minimum</strong> number of moves required to reach the bottom-right cell. If it is not possible to reach the destination, 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">matrix = [&quot;A..&quot;,&quot;.A.&quot;,&quot;...&quot;]</span></p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3552.Grid%20Teleportation%20Traversal/images/example04140.png" style="width: 151px; height: 151px;" /></p> <ul> <li>Before the first move, teleport from <code>(0, 0)</code> to <code>(1, 1)</code>.</li> <li>In the first move, move from <code>(1, 1)</code> to <code>(1, 2)</code>.</li> <li>In the second move, move from <code>(1, 2)</code> to <code>(2, 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">matrix = [&quot;.#...&quot;,&quot;.#.#.&quot;,&quot;.#.#.&quot;,&quot;...#.&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3552.Grid%20Teleportation%20Traversal/images/ezgifcom-animated-gif-maker.gif" style="width: 251px; height: 201px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == matrix.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= n == matrix[i].length &lt;= 10<sup>3</sup></code></li> <li><code>matrix[i][j]</code> is either <code>&#39;#&#39;</code>, <code>&#39;.&#39;</code>, or an uppercase English letter.</li> <li><code>matrix[0][0]</code> is not an obstacle.</li> </ul>
Breadth-First Search; Array; Hash Table; Matrix
C++
class Solution { public: int minMoves(vector<string>& matrix) { int m = matrix.size(), n = matrix[0].size(); unordered_map<char, vector<pair<int, int>>> g; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { char c = matrix[i][j]; if (isalpha(c)) g[c].push_back({i, j}); } int dirs[5] = {-1, 0, 1, 0, -1}; int INF = numeric_limits<int>::max() / 2; vector<vector<int>> dist(m, vector<int>(n, INF)); dist[0][0] = 0; deque<pair<int, int>> q; q.push_back({0, 0}); while (!q.empty()) { auto [i, j] = q.front(); q.pop_front(); int d = dist[i][j]; if (i == m - 1 && j == n - 1) return d; char c = matrix[i][j]; if (g.count(c)) { for (auto [x, y] : g[c]) if (d < dist[x][y]) { dist[x][y] = d; q.push_front({x, y}); } g.erase(c); } for (int idx = 0; idx < 4; ++idx) { int x = i + dirs[idx], y = j + dirs[idx + 1]; if (0 <= x && x < m && 0 <= y && y < n && matrix[x][y] != '#' && d + 1 < dist[x][y]) { dist[x][y] = d + 1; q.push_back({x, y}); } } } return -1; } };
3,552
Grid Teleportation Traversal
Medium
<p>You are given a 2D character grid <code>matrix</code> of size <code>m x n</code>, represented as an array of strings, where <code>matrix[i][j]</code> represents the cell at the intersection of the <code>i<sup>th</sup></code> row and <code>j<sup>th</sup></code> column. Each cell is one of the following:</p> <ul> <li><code>&#39;.&#39;</code> representing an empty cell.</li> <li><code>&#39;#&#39;</code> representing an obstacle.</li> <li>An uppercase letter (<code>&#39;A&#39;</code>-<code>&#39;Z&#39;</code>) representing a teleportation portal.</li> </ul> <p>You start at the top-left cell <code>(0, 0)</code>, and your goal is to reach the bottom-right cell <code>(m - 1, n - 1)</code>. You can move from the current cell to any adjacent cell (up, down, left, right) as long as the destination cell is within the grid bounds and is not an obstacle<strong>.</strong></p> <p>If you step on a cell containing a portal letter and you haven&#39;t used that portal letter before, you may instantly teleport to any other cell in the grid with the same letter. This teleportation does not count as a move, but each portal letter can be used<strong> at most </strong>once during your journey.</p> <p>Return the <strong>minimum</strong> number of moves required to reach the bottom-right cell. If it is not possible to reach the destination, 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">matrix = [&quot;A..&quot;,&quot;.A.&quot;,&quot;...&quot;]</span></p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3552.Grid%20Teleportation%20Traversal/images/example04140.png" style="width: 151px; height: 151px;" /></p> <ul> <li>Before the first move, teleport from <code>(0, 0)</code> to <code>(1, 1)</code>.</li> <li>In the first move, move from <code>(1, 1)</code> to <code>(1, 2)</code>.</li> <li>In the second move, move from <code>(1, 2)</code> to <code>(2, 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">matrix = [&quot;.#...&quot;,&quot;.#.#.&quot;,&quot;.#.#.&quot;,&quot;...#.&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3552.Grid%20Teleportation%20Traversal/images/ezgifcom-animated-gif-maker.gif" style="width: 251px; height: 201px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == matrix.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= n == matrix[i].length &lt;= 10<sup>3</sup></code></li> <li><code>matrix[i][j]</code> is either <code>&#39;#&#39;</code>, <code>&#39;.&#39;</code>, or an uppercase English letter.</li> <li><code>matrix[0][0]</code> is not an obstacle.</li> </ul>
Breadth-First Search; Array; Hash Table; Matrix
Go
type pair struct{ x, y int } func minMoves(matrix []string) int { m, n := len(matrix), len(matrix[0]) g := make(map[rune][]pair) for i := 0; i < m; i++ { for j, c := range matrix[i] { if unicode.IsLetter(c) { g[c] = append(g[c], pair{i, j}) } } } dirs := []int{-1, 0, 1, 0, -1} INF := 1 << 30 dist := make([][]int, m) for i := range dist { dist[i] = make([]int, n) for j := range dist[i] { dist[i][j] = INF } } dist[0][0] = 0 q := list.New() q.PushBack(pair{0, 0}) for q.Len() > 0 { cur := q.Remove(q.Front()).(pair) i, j := cur.x, cur.y d := dist[i][j] if i == m-1 && j == n-1 { return d } c := rune(matrix[i][j]) if v, ok := g[c]; ok { for _, p := range v { x, y := p.x, p.y if d < dist[x][y] { dist[x][y] = d q.PushFront(pair{x, y}) } } delete(g, c) } for idx := 0; idx < 4; idx++ { x, y := i+dirs[idx], j+dirs[idx+1] if 0 <= x && x < m && 0 <= y && y < n && matrix[x][y] != '#' && d+1 < dist[x][y] { dist[x][y] = d + 1 q.PushBack(pair{x, y}) } } } return -1 }
3,552
Grid Teleportation Traversal
Medium
<p>You are given a 2D character grid <code>matrix</code> of size <code>m x n</code>, represented as an array of strings, where <code>matrix[i][j]</code> represents the cell at the intersection of the <code>i<sup>th</sup></code> row and <code>j<sup>th</sup></code> column. Each cell is one of the following:</p> <ul> <li><code>&#39;.&#39;</code> representing an empty cell.</li> <li><code>&#39;#&#39;</code> representing an obstacle.</li> <li>An uppercase letter (<code>&#39;A&#39;</code>-<code>&#39;Z&#39;</code>) representing a teleportation portal.</li> </ul> <p>You start at the top-left cell <code>(0, 0)</code>, and your goal is to reach the bottom-right cell <code>(m - 1, n - 1)</code>. You can move from the current cell to any adjacent cell (up, down, left, right) as long as the destination cell is within the grid bounds and is not an obstacle<strong>.</strong></p> <p>If you step on a cell containing a portal letter and you haven&#39;t used that portal letter before, you may instantly teleport to any other cell in the grid with the same letter. This teleportation does not count as a move, but each portal letter can be used<strong> at most </strong>once during your journey.</p> <p>Return the <strong>minimum</strong> number of moves required to reach the bottom-right cell. If it is not possible to reach the destination, 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">matrix = [&quot;A..&quot;,&quot;.A.&quot;,&quot;...&quot;]</span></p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3552.Grid%20Teleportation%20Traversal/images/example04140.png" style="width: 151px; height: 151px;" /></p> <ul> <li>Before the first move, teleport from <code>(0, 0)</code> to <code>(1, 1)</code>.</li> <li>In the first move, move from <code>(1, 1)</code> to <code>(1, 2)</code>.</li> <li>In the second move, move from <code>(1, 2)</code> to <code>(2, 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">matrix = [&quot;.#...&quot;,&quot;.#.#.&quot;,&quot;.#.#.&quot;,&quot;...#.&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3552.Grid%20Teleportation%20Traversal/images/ezgifcom-animated-gif-maker.gif" style="width: 251px; height: 201px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == matrix.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= n == matrix[i].length &lt;= 10<sup>3</sup></code></li> <li><code>matrix[i][j]</code> is either <code>&#39;#&#39;</code>, <code>&#39;.&#39;</code>, or an uppercase English letter.</li> <li><code>matrix[0][0]</code> is not an obstacle.</li> </ul>
Breadth-First Search; Array; Hash Table; Matrix
Java
class Solution { public int minMoves(String[] matrix) { int m = matrix.length, n = matrix[0].length(); Map<Character, List<int[]>> g = new HashMap<>(); for (int i = 0; i < m; i++) { String row = matrix[i]; for (int j = 0; j < n; j++) { char c = row.charAt(j); if (Character.isAlphabetic(c)) { g.computeIfAbsent(c, k -> new ArrayList<>()).add(new int[] {i, j}); } } } int[] dirs = {-1, 0, 1, 0, -1}; int INF = Integer.MAX_VALUE / 2; int[][] dist = new int[m][n]; for (int[] arr : dist) Arrays.fill(arr, INF); dist[0][0] = 0; Deque<int[]> q = new ArrayDeque<>(); q.add(new int[] {0, 0}); while (!q.isEmpty()) { int[] cur = q.pollFirst(); int i = cur[0], j = cur[1]; int d = dist[i][j]; if (i == m - 1 && j == n - 1) return d; char c = matrix[i].charAt(j); if (g.containsKey(c)) { for (int[] pos : g.get(c)) { int x = pos[0], y = pos[1]; if (d < dist[x][y]) { dist[x][y] = d; q.addFirst(new int[] {x, y}); } } g.remove(c); } for (int idx = 0; idx < 4; idx++) { int a = dirs[idx], b = dirs[idx + 1]; int x = i + a, y = j + b; if (0 <= x && x < m && 0 <= y && y < n && matrix[x].charAt(y) != '#' && d + 1 < dist[x][y]) { dist[x][y] = d + 1; q.addLast(new int[] {x, y}); } } } return -1; } }
3,552
Grid Teleportation Traversal
Medium
<p>You are given a 2D character grid <code>matrix</code> of size <code>m x n</code>, represented as an array of strings, where <code>matrix[i][j]</code> represents the cell at the intersection of the <code>i<sup>th</sup></code> row and <code>j<sup>th</sup></code> column. Each cell is one of the following:</p> <ul> <li><code>&#39;.&#39;</code> representing an empty cell.</li> <li><code>&#39;#&#39;</code> representing an obstacle.</li> <li>An uppercase letter (<code>&#39;A&#39;</code>-<code>&#39;Z&#39;</code>) representing a teleportation portal.</li> </ul> <p>You start at the top-left cell <code>(0, 0)</code>, and your goal is to reach the bottom-right cell <code>(m - 1, n - 1)</code>. You can move from the current cell to any adjacent cell (up, down, left, right) as long as the destination cell is within the grid bounds and is not an obstacle<strong>.</strong></p> <p>If you step on a cell containing a portal letter and you haven&#39;t used that portal letter before, you may instantly teleport to any other cell in the grid with the same letter. This teleportation does not count as a move, but each portal letter can be used<strong> at most </strong>once during your journey.</p> <p>Return the <strong>minimum</strong> number of moves required to reach the bottom-right cell. If it is not possible to reach the destination, 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">matrix = [&quot;A..&quot;,&quot;.A.&quot;,&quot;...&quot;]</span></p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3552.Grid%20Teleportation%20Traversal/images/example04140.png" style="width: 151px; height: 151px;" /></p> <ul> <li>Before the first move, teleport from <code>(0, 0)</code> to <code>(1, 1)</code>.</li> <li>In the first move, move from <code>(1, 1)</code> to <code>(1, 2)</code>.</li> <li>In the second move, move from <code>(1, 2)</code> to <code>(2, 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">matrix = [&quot;.#...&quot;,&quot;.#.#.&quot;,&quot;.#.#.&quot;,&quot;...#.&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3552.Grid%20Teleportation%20Traversal/images/ezgifcom-animated-gif-maker.gif" style="width: 251px; height: 201px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == matrix.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= n == matrix[i].length &lt;= 10<sup>3</sup></code></li> <li><code>matrix[i][j]</code> is either <code>&#39;#&#39;</code>, <code>&#39;.&#39;</code>, or an uppercase English letter.</li> <li><code>matrix[0][0]</code> is not an obstacle.</li> </ul>
Breadth-First Search; Array; Hash Table; Matrix
Python
class Solution: def minMoves(self, matrix: List[str]) -> int: m, n = len(matrix), len(matrix[0]) g = defaultdict(list) for i, row in enumerate(matrix): for j, c in enumerate(row): if c.isalpha(): g[c].append((i, j)) dirs = (-1, 0, 1, 0, -1) dist = [[inf] * n for _ in range(m)] dist[0][0] = 0 q = deque([(0, 0)]) while q: i, j = q.popleft() d = dist[i][j] if i == m - 1 and j == n - 1: return d c = matrix[i][j] if c in g: for x, y in g[c]: if d < dist[x][y]: dist[x][y] = d q.appendleft((x, y)) del g[c] for a, b in pairwise(dirs): x, y = i + a, j + b if ( 0 <= x < m and 0 <= y < n and matrix[x][y] != "#" and d + 1 < dist[x][y] ): dist[x][y] = d + 1 q.append((x, y)) return -1
3,552
Grid Teleportation Traversal
Medium
<p>You are given a 2D character grid <code>matrix</code> of size <code>m x n</code>, represented as an array of strings, where <code>matrix[i][j]</code> represents the cell at the intersection of the <code>i<sup>th</sup></code> row and <code>j<sup>th</sup></code> column. Each cell is one of the following:</p> <ul> <li><code>&#39;.&#39;</code> representing an empty cell.</li> <li><code>&#39;#&#39;</code> representing an obstacle.</li> <li>An uppercase letter (<code>&#39;A&#39;</code>-<code>&#39;Z&#39;</code>) representing a teleportation portal.</li> </ul> <p>You start at the top-left cell <code>(0, 0)</code>, and your goal is to reach the bottom-right cell <code>(m - 1, n - 1)</code>. You can move from the current cell to any adjacent cell (up, down, left, right) as long as the destination cell is within the grid bounds and is not an obstacle<strong>.</strong></p> <p>If you step on a cell containing a portal letter and you haven&#39;t used that portal letter before, you may instantly teleport to any other cell in the grid with the same letter. This teleportation does not count as a move, but each portal letter can be used<strong> at most </strong>once during your journey.</p> <p>Return the <strong>minimum</strong> number of moves required to reach the bottom-right cell. If it is not possible to reach the destination, 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">matrix = [&quot;A..&quot;,&quot;.A.&quot;,&quot;...&quot;]</span></p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3552.Grid%20Teleportation%20Traversal/images/example04140.png" style="width: 151px; height: 151px;" /></p> <ul> <li>Before the first move, teleport from <code>(0, 0)</code> to <code>(1, 1)</code>.</li> <li>In the first move, move from <code>(1, 1)</code> to <code>(1, 2)</code>.</li> <li>In the second move, move from <code>(1, 2)</code> to <code>(2, 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">matrix = [&quot;.#...&quot;,&quot;.#.#.&quot;,&quot;.#.#.&quot;,&quot;...#.&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3552.Grid%20Teleportation%20Traversal/images/ezgifcom-animated-gif-maker.gif" style="width: 251px; height: 201px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m == matrix.length &lt;= 10<sup>3</sup></code></li> <li><code>1 &lt;= n == matrix[i].length &lt;= 10<sup>3</sup></code></li> <li><code>matrix[i][j]</code> is either <code>&#39;#&#39;</code>, <code>&#39;.&#39;</code>, or an uppercase English letter.</li> <li><code>matrix[0][0]</code> is not an obstacle.</li> </ul>
Breadth-First Search; Array; Hash Table; Matrix
TypeScript
function minMoves(matrix: string[]): number { const m = matrix.length, n = matrix[0].length; const g = new Map<string, [number, number][]>(); for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { const c = matrix[i][j]; if (/^[A-Za-z]$/.test(c)) { if (!g.has(c)) g.set(c, []); g.get(c)!.push([i, j]); } } } const dirs = [-1, 0, 1, 0, -1]; const INF = Number.MAX_SAFE_INTEGER; const dist: number[][] = Array.from({ length: m }, () => Array(n).fill(INF)); dist[0][0] = 0; const cap = m * n * 2 + 5; const dq = new Array<[number, number]>(cap); let l = cap >> 1, r = cap >> 1; const pushFront = (v: [number, number]) => { dq[--l] = v; }; const pushBack = (v: [number, number]) => { dq[r++] = v; }; const popFront = (): [number, number] => dq[l++]; const empty = () => l === r; pushBack([0, 0]); while (!empty()) { const [i, j] = popFront(); const d = dist[i][j]; if (i === m - 1 && j === n - 1) return d; const c = matrix[i][j]; if (g.has(c)) { for (const [x, y] of g.get(c)!) { if (d < dist[x][y]) { dist[x][y] = d; pushFront([x, y]); } } g.delete(c); } for (let idx = 0; idx < 4; idx++) { const x = i + dirs[idx], y = j + dirs[idx + 1]; if (0 <= x && x < m && 0 <= y && y < n && matrix[x][y] !== '#' && d + 1 < dist[x][y]) { dist[x][y] = d + 1; pushBack([x, y]); } } } return -1; }
3,554
Find Category Recommendation Pairs
Hard
<p>Table: <code>ProductPurchases</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | user_id | int | | product_id | int | | quantity | int | +-------------+------+ (user_id, product_id) is the unique identifier for this table. Each row represents a purchase of a product by a user in a specific quantity. </pre> <p>Table: <code>ProductInfo</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | product_id | int | | category | varchar | | price | decimal | +-------------+---------+ product_id is the unique identifier for this table. Each row assigns a category and price to a product. </pre> <p>Amazon wants to understand shopping patterns across product categories. Write a solution to:</p> <ol> <li>Find all <strong>category pairs</strong> (where <code>category1</code> &lt; <code>category2</code>)</li> <li>For <strong>each category pair</strong>, determine the number of <strong>unique</strong> <strong>customers</strong> who purchased products from <strong>both</strong> categories</li> </ol> <p>A category pair is considered <strong>reportable</strong> if at least <code>3</code> different customers have purchased products from both categories.</p> <p>Return <em>the result table of reportable category pairs ordered by <strong>customer_count</strong> in <strong>descending</strong> order, and in case of a tie, by <strong>category1</strong> in <strong>ascending</strong> order lexicographically, and then by <strong>category2</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>ProductPurchases table:</p> <pre class="example-io"> +---------+------------+----------+ | user_id | product_id | quantity | +---------+------------+----------+ | 1 | 101 | 2 | | 1 | 102 | 1 | | 1 | 201 | 3 | | 1 | 301 | 1 | | 2 | 101 | 1 | | 2 | 102 | 2 | | 2 | 103 | 1 | | 2 | 201 | 5 | | 3 | 101 | 2 | | 3 | 103 | 1 | | 3 | 301 | 4 | | 3 | 401 | 2 | | 4 | 101 | 1 | | 4 | 201 | 3 | | 4 | 301 | 1 | | 4 | 401 | 2 | | 5 | 102 | 2 | | 5 | 103 | 1 | | 5 | 201 | 2 | | 5 | 202 | 3 | +---------+------------+----------+ </pre> <p>ProductInfo table:</p> <pre class="example-io"> +------------+-------------+-------+ | product_id | category | price | +------------+-------------+-------+ | 101 | Electronics | 100 | | 102 | Books | 20 | | 103 | Books | 35 | | 201 | Clothing | 45 | | 202 | Clothing | 60 | | 301 | Sports | 75 | | 401 | Kitchen | 50 | +------------+-------------+-------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+-------------+----------------+ | category1 | category2 | customer_count | +-------------+-------------+----------------+ | Books | Clothing | 3 | | Books | Electronics | 3 | | Clothing | Electronics | 3 | | Electronics | Sports | 3 | +-------------+-------------+----------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Books-Clothing</strong>: <ul> <li>User 1 purchased products from Books (102) and Clothing (201)</li> <li>User 2 purchased products from Books (102, 103) and Clothing (201)</li> <li>User 5 purchased products from Books (102, 103) and Clothing (201, 202)</li> <li>Total: 3 customers purchased from both categories</li> </ul> </li> <li><strong>Books-Electronics</strong>: <ul> <li>User 1 purchased products from Books (102) and Electronics (101)</li> <li>User 2 purchased products from Books (102, 103) and Electronics (101)</li> <li>User 3 purchased products from Books (103) and Electronics (101)</li> <li>Total: 3 customers purchased from both categories</li> </ul> </li> <li><strong>Clothing-Electronics</strong>: <ul> <li>User 1 purchased products from Clothing (201) and Electronics (101)</li> <li>User 2 purchased products from Clothing (201) and Electronics (101)</li> <li>User 4 purchased products from Clothing (201) and Electronics (101)</li> <li>Total: 3 customers purchased from both categories</li> </ul> </li> <li><strong>Electronics-Sports</strong>: <ul> <li>User 1 purchased products from Electronics (101) and Sports (301)</li> <li>User 3 purchased products from Electronics (101) and Sports (301)</li> <li>User 4 purchased products from Electronics (101) and Sports (301)</li> <li>Total: 3 customers purchased from both categories</li> </ul> </li> <li>Other category pairs like Clothing-Sports (only 2 customers: Users 1 and 4) and Books-Kitchen (only 1 customer: User 3) have fewer than 3 shared customers and are not included in the result.</li> </ul> <p>The result is ordered by customer_count in descending order. Since all pairs have the same customer_count of 3, they are ordered by category1 (then category2) in ascending order.</p> </div>
Database
Python
import pandas as pd def find_category_recommendation_pairs( product_purchases: pd.DataFrame, product_info: pd.DataFrame ) -> pd.DataFrame: df = product_purchases[["user_id", "product_id"]].merge( product_info[["product_id", "category"]], on="product_id", how="inner" ) user_category = df.drop_duplicates(subset=["user_id", "category"]) pair_per_user = ( user_category.merge(user_category, on="user_id") .query("category_x < category_y") .rename(columns={"category_x": "category1", "category_y": "category2"}) ) pair_counts = ( pair_per_user.groupby(["category1", "category2"])["user_id"] .nunique() .reset_index(name="customer_count") ) result = ( pair_counts.query("customer_count >= 3") .sort_values( ["customer_count", "category1", "category2"], ascending=[False, True, True] ) .reset_index(drop=True) ) return result
3,554
Find Category Recommendation Pairs
Hard
<p>Table: <code>ProductPurchases</code></p> <pre> +-------------+------+ | Column Name | Type | +-------------+------+ | user_id | int | | product_id | int | | quantity | int | +-------------+------+ (user_id, product_id) is the unique identifier for this table. Each row represents a purchase of a product by a user in a specific quantity. </pre> <p>Table: <code>ProductInfo</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | product_id | int | | category | varchar | | price | decimal | +-------------+---------+ product_id is the unique identifier for this table. Each row assigns a category and price to a product. </pre> <p>Amazon wants to understand shopping patterns across product categories. Write a solution to:</p> <ol> <li>Find all <strong>category pairs</strong> (where <code>category1</code> &lt; <code>category2</code>)</li> <li>For <strong>each category pair</strong>, determine the number of <strong>unique</strong> <strong>customers</strong> who purchased products from <strong>both</strong> categories</li> </ol> <p>A category pair is considered <strong>reportable</strong> if at least <code>3</code> different customers have purchased products from both categories.</p> <p>Return <em>the result table of reportable category pairs ordered by <strong>customer_count</strong> in <strong>descending</strong> order, and in case of a tie, by <strong>category1</strong> in <strong>ascending</strong> order lexicographically, and then by <strong>category2</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>ProductPurchases table:</p> <pre class="example-io"> +---------+------------+----------+ | user_id | product_id | quantity | +---------+------------+----------+ | 1 | 101 | 2 | | 1 | 102 | 1 | | 1 | 201 | 3 | | 1 | 301 | 1 | | 2 | 101 | 1 | | 2 | 102 | 2 | | 2 | 103 | 1 | | 2 | 201 | 5 | | 3 | 101 | 2 | | 3 | 103 | 1 | | 3 | 301 | 4 | | 3 | 401 | 2 | | 4 | 101 | 1 | | 4 | 201 | 3 | | 4 | 301 | 1 | | 4 | 401 | 2 | | 5 | 102 | 2 | | 5 | 103 | 1 | | 5 | 201 | 2 | | 5 | 202 | 3 | +---------+------------+----------+ </pre> <p>ProductInfo table:</p> <pre class="example-io"> +------------+-------------+-------+ | product_id | category | price | +------------+-------------+-------+ | 101 | Electronics | 100 | | 102 | Books | 20 | | 103 | Books | 35 | | 201 | Clothing | 45 | | 202 | Clothing | 60 | | 301 | Sports | 75 | | 401 | Kitchen | 50 | +------------+-------------+-------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+-------------+----------------+ | category1 | category2 | customer_count | +-------------+-------------+----------------+ | Books | Clothing | 3 | | Books | Electronics | 3 | | Clothing | Electronics | 3 | | Electronics | Sports | 3 | +-------------+-------------+----------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Books-Clothing</strong>: <ul> <li>User 1 purchased products from Books (102) and Clothing (201)</li> <li>User 2 purchased products from Books (102, 103) and Clothing (201)</li> <li>User 5 purchased products from Books (102, 103) and Clothing (201, 202)</li> <li>Total: 3 customers purchased from both categories</li> </ul> </li> <li><strong>Books-Electronics</strong>: <ul> <li>User 1 purchased products from Books (102) and Electronics (101)</li> <li>User 2 purchased products from Books (102, 103) and Electronics (101)</li> <li>User 3 purchased products from Books (103) and Electronics (101)</li> <li>Total: 3 customers purchased from both categories</li> </ul> </li> <li><strong>Clothing-Electronics</strong>: <ul> <li>User 1 purchased products from Clothing (201) and Electronics (101)</li> <li>User 2 purchased products from Clothing (201) and Electronics (101)</li> <li>User 4 purchased products from Clothing (201) and Electronics (101)</li> <li>Total: 3 customers purchased from both categories</li> </ul> </li> <li><strong>Electronics-Sports</strong>: <ul> <li>User 1 purchased products from Electronics (101) and Sports (301)</li> <li>User 3 purchased products from Electronics (101) and Sports (301)</li> <li>User 4 purchased products from Electronics (101) and Sports (301)</li> <li>Total: 3 customers purchased from both categories</li> </ul> </li> <li>Other category pairs like Clothing-Sports (only 2 customers: Users 1 and 4) and Books-Kitchen (only 1 customer: User 3) have fewer than 3 shared customers and are not included in the result.</li> </ul> <p>The result is ordered by customer_count in descending order. Since all pairs have the same customer_count of 3, they are ordered by category1 (then category2) in ascending order.</p> </div>
Database
SQL
# Write your MySQL query statement below WITH user_category AS ( SELECT DISTINCT user_id, category FROM ProductPurchases JOIN ProductInfo USING (product_id) ), pair_per_user AS ( SELECT a.user_id, a.category AS category1, b.category AS category2 FROM user_category AS a JOIN user_category AS b ON a.user_id = b.user_id AND a.category < b.category ) SELECT category1, category2, COUNT(DISTINCT user_id) AS customer_count FROM pair_per_user GROUP BY 1, 2 HAVING customer_count >= 3 ORDER BY 3 DESC, 1, 2;
3,555
Smallest Subarray to Sort in Every Sliding Window
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>For each contiguous <span data-keyword="subarray">subarray</span> of length <code>k</code>, determine the <strong>minimum</strong> length of a continuous segment that must be sorted so that the entire window becomes <strong>non‑decreasing</strong>; if the window is already sorted, its required length is zero.</p> <p>Return an array of length <code>n &minus; k + 1</code> where each element corresponds to the answer for its window.</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,3,2,4,5], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>nums[0...2] = [1, 3, 2]</code>. Sort <code>[3, 2]</code> to get <code>[1, 2, 3]</code>, the answer is 2.</li> <li><code>nums[1...3] = [3, 2, 4]</code>. Sort <code>[3, 2]</code> to get <code>[2, 3, 4]</code>, the answer is 2.</li> <li><code>nums[2...4] = [2, 4, 5]</code> is already sorted, so the answer is 0.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,4,3,2,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[4,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>nums[0...3] = [5, 4, 3, 2]</code>. The whole subarray must be sorted, so the answer is 4.</li> <li><code>nums[1...4] = [4, 3, 2, 1]</code>. The whole subarray must be sorted, so the answer is 4.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Stack; Greedy; Array; Two Pointers; Sorting; Monotonic Stack
C++
class Solution { public: vector<int> minSubarraySort(vector<int>& nums, int k) { const int inf = 1 << 30; int n = nums.size(); auto f = [&](int i, int j) -> int { int mi = inf, mx = -inf; int l = -1, r = -1; for (int k = i; k <= j; ++k) { if (nums[k] < mx) { r = k; } else { mx = nums[k]; } int p = j - k + i; if (nums[p] > mi) { l = p; } else { mi = nums[p]; } } return r == -1 ? 0 : r - l + 1; }; vector<int> ans; for (int i = 0; i < n - k + 1; ++i) { ans.push_back(f(i, i + k - 1)); } return ans; } };
3,555
Smallest Subarray to Sort in Every Sliding Window
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>For each contiguous <span data-keyword="subarray">subarray</span> of length <code>k</code>, determine the <strong>minimum</strong> length of a continuous segment that must be sorted so that the entire window becomes <strong>non‑decreasing</strong>; if the window is already sorted, its required length is zero.</p> <p>Return an array of length <code>n &minus; k + 1</code> where each element corresponds to the answer for its window.</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,3,2,4,5], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>nums[0...2] = [1, 3, 2]</code>. Sort <code>[3, 2]</code> to get <code>[1, 2, 3]</code>, the answer is 2.</li> <li><code>nums[1...3] = [3, 2, 4]</code>. Sort <code>[3, 2]</code> to get <code>[2, 3, 4]</code>, the answer is 2.</li> <li><code>nums[2...4] = [2, 4, 5]</code> is already sorted, so the answer is 0.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,4,3,2,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[4,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>nums[0...3] = [5, 4, 3, 2]</code>. The whole subarray must be sorted, so the answer is 4.</li> <li><code>nums[1...4] = [4, 3, 2, 1]</code>. The whole subarray must be sorted, so the answer is 4.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Stack; Greedy; Array; Two Pointers; Sorting; Monotonic Stack
Go
func minSubarraySort(nums []int, k int) []int { const inf = 1 << 30 n := len(nums) f := func(i, j int) int { mi := inf mx := -inf l, r := -1, -1 for p := i; p <= j; p++ { if nums[p] < mx { r = p } else { mx = nums[p] } q := j - p + i if nums[q] > mi { l = q } else { mi = nums[q] } } if r == -1 { return 0 } return r - l + 1 } ans := make([]int, 0, n-k+1) for i := 0; i <= n-k; i++ { ans = append(ans, f(i, i+k-1)) } return ans }
3,555
Smallest Subarray to Sort in Every Sliding Window
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>For each contiguous <span data-keyword="subarray">subarray</span> of length <code>k</code>, determine the <strong>minimum</strong> length of a continuous segment that must be sorted so that the entire window becomes <strong>non‑decreasing</strong>; if the window is already sorted, its required length is zero.</p> <p>Return an array of length <code>n &minus; k + 1</code> where each element corresponds to the answer for its window.</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,3,2,4,5], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>nums[0...2] = [1, 3, 2]</code>. Sort <code>[3, 2]</code> to get <code>[1, 2, 3]</code>, the answer is 2.</li> <li><code>nums[1...3] = [3, 2, 4]</code>. Sort <code>[3, 2]</code> to get <code>[2, 3, 4]</code>, the answer is 2.</li> <li><code>nums[2...4] = [2, 4, 5]</code> is already sorted, so the answer is 0.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,4,3,2,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[4,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>nums[0...3] = [5, 4, 3, 2]</code>. The whole subarray must be sorted, so the answer is 4.</li> <li><code>nums[1...4] = [4, 3, 2, 1]</code>. The whole subarray must be sorted, so the answer is 4.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Stack; Greedy; Array; Two Pointers; Sorting; Monotonic Stack
Java
class Solution { private int[] nums; private final int inf = 1 << 30; public int[] minSubarraySort(int[] nums, int k) { this.nums = nums; int n = nums.length; int[] ans = new int[n - k + 1]; for (int i = 0; i < n - k + 1; ++i) { ans[i] = f(i, i + k - 1); } return ans; } private int f(int i, int j) { int mi = inf, mx = -inf; int l = -1, r = -1; for (int k = i; k <= j; ++k) { if (nums[k] < mx) { r = k; } else { mx = nums[k]; } int p = j - k + i; if (nums[p] > mi) { l = p; } else { mi = nums[p]; } } return r == -1 ? 0 : r - l + 1; } }
3,555
Smallest Subarray to Sort in Every Sliding Window
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>For each contiguous <span data-keyword="subarray">subarray</span> of length <code>k</code>, determine the <strong>minimum</strong> length of a continuous segment that must be sorted so that the entire window becomes <strong>non‑decreasing</strong>; if the window is already sorted, its required length is zero.</p> <p>Return an array of length <code>n &minus; k + 1</code> where each element corresponds to the answer for its window.</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,3,2,4,5], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>nums[0...2] = [1, 3, 2]</code>. Sort <code>[3, 2]</code> to get <code>[1, 2, 3]</code>, the answer is 2.</li> <li><code>nums[1...3] = [3, 2, 4]</code>. Sort <code>[3, 2]</code> to get <code>[2, 3, 4]</code>, the answer is 2.</li> <li><code>nums[2...4] = [2, 4, 5]</code> is already sorted, so the answer is 0.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,4,3,2,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[4,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>nums[0...3] = [5, 4, 3, 2]</code>. The whole subarray must be sorted, so the answer is 4.</li> <li><code>nums[1...4] = [4, 3, 2, 1]</code>. The whole subarray must be sorted, so the answer is 4.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Stack; Greedy; Array; Two Pointers; Sorting; Monotonic Stack
Python
class Solution: def minSubarraySort(self, nums: List[int], k: int) -> List[int]: def f(i: int, j: int) -> int: mi, mx = inf, -inf l = r = -1 for k in range(i, j + 1): if mx > nums[k]: r = k else: mx = nums[k] p = j - k + i if mi < nums[p]: l = p else: mi = nums[p] return 0 if r == -1 else r - l + 1 n = len(nums) return [f(i, i + k - 1) for i in range(n - k + 1)]
3,555
Smallest Subarray to Sort in Every Sliding Window
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>For each contiguous <span data-keyword="subarray">subarray</span> of length <code>k</code>, determine the <strong>minimum</strong> length of a continuous segment that must be sorted so that the entire window becomes <strong>non‑decreasing</strong>; if the window is already sorted, its required length is zero.</p> <p>Return an array of length <code>n &minus; k + 1</code> where each element corresponds to the answer for its window.</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,3,2,4,5], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[2,2,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>nums[0...2] = [1, 3, 2]</code>. Sort <code>[3, 2]</code> to get <code>[1, 2, 3]</code>, the answer is 2.</li> <li><code>nums[1...3] = [3, 2, 4]</code>. Sort <code>[3, 2]</code> to get <code>[2, 3, 4]</code>, the answer is 2.</li> <li><code>nums[2...4] = [2, 4, 5]</code> is already sorted, so the answer is 0.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,4,3,2,1], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[4,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>nums[0...3] = [5, 4, 3, 2]</code>. The whole subarray must be sorted, so the answer is 4.</li> <li><code>nums[1...4] = [4, 3, 2, 1]</code>. The whole subarray must be sorted, so the answer is 4.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Stack; Greedy; Array; Two Pointers; Sorting; Monotonic Stack
TypeScript
function minSubarraySort(nums: number[], k: number): number[] { const inf = Infinity; const n = nums.length; const f = (i: number, j: number): number => { let mi = inf; let mx = -inf; let l = -1, r = -1; for (let p = i; p <= j; ++p) { if (nums[p] < mx) { r = p; } else { mx = nums[p]; } const q = j - p + i; if (nums[q] > mi) { l = q; } else { mi = nums[q]; } } return r === -1 ? 0 : r - l + 1; }; const ans: number[] = []; for (let i = 0; i <= n - k; ++i) { ans.push(f(i, i + k - 1)); } return ans; }
3,556
Sum of Largest Prime Substrings
Medium
<p data-end="157" data-start="30">Given a string <code>s</code>, find the sum of the <strong>3 largest unique <span data-keyword="prime-number">prime numbers</span></strong> that can be formed using any of its<strong> <span data-keyword="substring">substrings</span></strong>.</p> <p data-end="269" data-start="166">Return the <strong>sum</strong> of the three largest unique prime numbers that can be formed. If fewer than three exist, return the sum of <strong>all</strong> available primes. If no prime numbers can be formed, return 0.</p> <p data-end="370" data-is-last-node="" data-is-only-node="" data-start="271"><strong data-end="280" data-start="271">Note:</strong> Each prime number should be counted only <strong>once</strong>, even if it appears in <strong>multiple</strong> substrings. Additionally, when converting a substring to an integer, any leading zeros are ignored.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;12234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1469</span></p> <p><strong>Explanation:</strong></p> <ul> <li data-end="136" data-start="16">The unique prime numbers formed from the substrings of <code>&quot;12234&quot;</code> are 2, 3, 23, 223, and 1223.</li> <li data-end="226" data-start="137">The 3 largest primes are 1223, 223, and 23. Their sum is 1469.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;111&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">11</span></p> <p><strong>Explanation:</strong></p> <ul> <li data-end="339" data-start="244">The unique prime number formed from the substrings of <code>&quot;111&quot;</code> is 11.</li> <li data-end="412" data-is-last-node="" data-start="340">Since there is only one prime number, the sum is 11.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="39" data-start="18"><code>1 &lt;= s.length &lt;= 10</code></li> <li data-end="68" data-is-last-node="" data-start="40"><code>s</code> consists of only digits.</li> </ul>
Hash Table; Math; String; Number Theory; Sorting
C++
class Solution { public: long long sumOfLargestPrimes(string s) { unordered_set<long long> st; int n = s.size(); for (int i = 0; i < n; ++i) { long long x = 0; for (int j = i; j < n; ++j) { x = x * 10 + (s[j] - '0'); if (is_prime(x)) { st.insert(x); } } } vector<long long> sorted(st.begin(), st.end()); sort(sorted.begin(), sorted.end()); long long ans = 0; int cnt = 0; for (int i = (int) sorted.size() - 1; i >= 0 && cnt < 3; --i, ++cnt) { ans += sorted[i]; } return ans; } private: bool is_prime(long long x) { if (x < 2) return false; for (long long i = 2; i * i <= x; ++i) { if (x % i == 0) return false; } return true; } };
3,556
Sum of Largest Prime Substrings
Medium
<p data-end="157" data-start="30">Given a string <code>s</code>, find the sum of the <strong>3 largest unique <span data-keyword="prime-number">prime numbers</span></strong> that can be formed using any of its<strong> <span data-keyword="substring">substrings</span></strong>.</p> <p data-end="269" data-start="166">Return the <strong>sum</strong> of the three largest unique prime numbers that can be formed. If fewer than three exist, return the sum of <strong>all</strong> available primes. If no prime numbers can be formed, return 0.</p> <p data-end="370" data-is-last-node="" data-is-only-node="" data-start="271"><strong data-end="280" data-start="271">Note:</strong> Each prime number should be counted only <strong>once</strong>, even if it appears in <strong>multiple</strong> substrings. Additionally, when converting a substring to an integer, any leading zeros are ignored.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;12234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1469</span></p> <p><strong>Explanation:</strong></p> <ul> <li data-end="136" data-start="16">The unique prime numbers formed from the substrings of <code>&quot;12234&quot;</code> are 2, 3, 23, 223, and 1223.</li> <li data-end="226" data-start="137">The 3 largest primes are 1223, 223, and 23. Their sum is 1469.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;111&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">11</span></p> <p><strong>Explanation:</strong></p> <ul> <li data-end="339" data-start="244">The unique prime number formed from the substrings of <code>&quot;111&quot;</code> is 11.</li> <li data-end="412" data-is-last-node="" data-start="340">Since there is only one prime number, the sum is 11.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="39" data-start="18"><code>1 &lt;= s.length &lt;= 10</code></li> <li data-end="68" data-is-last-node="" data-start="40"><code>s</code> consists of only digits.</li> </ul>
Hash Table; Math; String; Number Theory; Sorting
Go
func sumOfLargestPrimes(s string) (ans int64) { st := make(map[int64]struct{}) n := len(s) for i := 0; i < n; i++ { var x int64 = 0 for j := i; j < n; j++ { x = x*10 + int64(s[j]-'0') if isPrime(x) { st[x] = struct{}{} } } } nums := make([]int64, 0, len(st)) for num := range st { nums = append(nums, num) } sort.Slice(nums, func(i, j int) bool { return nums[i] < nums[j] }) for i := len(nums) - 1; i >= 0 && len(nums)-i <= 3; i-- { ans += nums[i] } return } func isPrime(x int64) bool { if x < 2 { return false } sqrtX := int64(math.Sqrt(float64(x))) for i := int64(2); i <= sqrtX; i++ { if x%i == 0 { return false } } return true }
3,556
Sum of Largest Prime Substrings
Medium
<p data-end="157" data-start="30">Given a string <code>s</code>, find the sum of the <strong>3 largest unique <span data-keyword="prime-number">prime numbers</span></strong> that can be formed using any of its<strong> <span data-keyword="substring">substrings</span></strong>.</p> <p data-end="269" data-start="166">Return the <strong>sum</strong> of the three largest unique prime numbers that can be formed. If fewer than three exist, return the sum of <strong>all</strong> available primes. If no prime numbers can be formed, return 0.</p> <p data-end="370" data-is-last-node="" data-is-only-node="" data-start="271"><strong data-end="280" data-start="271">Note:</strong> Each prime number should be counted only <strong>once</strong>, even if it appears in <strong>multiple</strong> substrings. Additionally, when converting a substring to an integer, any leading zeros are ignored.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;12234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1469</span></p> <p><strong>Explanation:</strong></p> <ul> <li data-end="136" data-start="16">The unique prime numbers formed from the substrings of <code>&quot;12234&quot;</code> are 2, 3, 23, 223, and 1223.</li> <li data-end="226" data-start="137">The 3 largest primes are 1223, 223, and 23. Their sum is 1469.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;111&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">11</span></p> <p><strong>Explanation:</strong></p> <ul> <li data-end="339" data-start="244">The unique prime number formed from the substrings of <code>&quot;111&quot;</code> is 11.</li> <li data-end="412" data-is-last-node="" data-start="340">Since there is only one prime number, the sum is 11.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="39" data-start="18"><code>1 &lt;= s.length &lt;= 10</code></li> <li data-end="68" data-is-last-node="" data-start="40"><code>s</code> consists of only digits.</li> </ul>
Hash Table; Math; String; Number Theory; Sorting
Java
class Solution { public long sumOfLargestPrimes(String s) { Set<Long> st = new HashSet<>(); int n = s.length(); for (int i = 0; i < n; i++) { long x = 0; for (int j = i; j < n; j++) { x = x * 10 + (s.charAt(j) - '0'); if (is_prime(x)) { st.add(x); } } } List<Long> sorted = new ArrayList<>(st); Collections.sort(sorted); long ans = 0; int start = Math.max(0, sorted.size() - 3); for (int idx = start; idx < sorted.size(); idx++) { ans += sorted.get(idx); } return ans; } private boolean is_prime(long x) { if (x < 2) return false; for (long i = 2; i * i <= x; i++) { if (x % i == 0) return false; } return true; } }
3,556
Sum of Largest Prime Substrings
Medium
<p data-end="157" data-start="30">Given a string <code>s</code>, find the sum of the <strong>3 largest unique <span data-keyword="prime-number">prime numbers</span></strong> that can be formed using any of its<strong> <span data-keyword="substring">substrings</span></strong>.</p> <p data-end="269" data-start="166">Return the <strong>sum</strong> of the three largest unique prime numbers that can be formed. If fewer than three exist, return the sum of <strong>all</strong> available primes. If no prime numbers can be formed, return 0.</p> <p data-end="370" data-is-last-node="" data-is-only-node="" data-start="271"><strong data-end="280" data-start="271">Note:</strong> Each prime number should be counted only <strong>once</strong>, even if it appears in <strong>multiple</strong> substrings. Additionally, when converting a substring to an integer, any leading zeros are ignored.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;12234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1469</span></p> <p><strong>Explanation:</strong></p> <ul> <li data-end="136" data-start="16">The unique prime numbers formed from the substrings of <code>&quot;12234&quot;</code> are 2, 3, 23, 223, and 1223.</li> <li data-end="226" data-start="137">The 3 largest primes are 1223, 223, and 23. Their sum is 1469.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;111&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">11</span></p> <p><strong>Explanation:</strong></p> <ul> <li data-end="339" data-start="244">The unique prime number formed from the substrings of <code>&quot;111&quot;</code> is 11.</li> <li data-end="412" data-is-last-node="" data-start="340">Since there is only one prime number, the sum is 11.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="39" data-start="18"><code>1 &lt;= s.length &lt;= 10</code></li> <li data-end="68" data-is-last-node="" data-start="40"><code>s</code> consists of only digits.</li> </ul>
Hash Table; Math; String; Number Theory; Sorting
Python
class Solution: def sumOfLargestPrimes(self, s: str) -> int: def is_prime(x: int) -> bool: if x < 2: return False return all(x % i for i in range(2, int(sqrt(x)) + 1)) st = set() n = len(s) for i in range(n): x = 0 for j in range(i, n): x = x * 10 + int(s[j]) if is_prime(x): st.add(x) return sum(sorted(st)[-3:])
3,556
Sum of Largest Prime Substrings
Medium
<p data-end="157" data-start="30">Given a string <code>s</code>, find the sum of the <strong>3 largest unique <span data-keyword="prime-number">prime numbers</span></strong> that can be formed using any of its<strong> <span data-keyword="substring">substrings</span></strong>.</p> <p data-end="269" data-start="166">Return the <strong>sum</strong> of the three largest unique prime numbers that can be formed. If fewer than three exist, return the sum of <strong>all</strong> available primes. If no prime numbers can be formed, return 0.</p> <p data-end="370" data-is-last-node="" data-is-only-node="" data-start="271"><strong data-end="280" data-start="271">Note:</strong> Each prime number should be counted only <strong>once</strong>, even if it appears in <strong>multiple</strong> substrings. Additionally, when converting a substring to an integer, any leading zeros are ignored.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;12234&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1469</span></p> <p><strong>Explanation:</strong></p> <ul> <li data-end="136" data-start="16">The unique prime numbers formed from the substrings of <code>&quot;12234&quot;</code> are 2, 3, 23, 223, and 1223.</li> <li data-end="226" data-start="137">The 3 largest primes are 1223, 223, and 23. Their sum is 1469.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;111&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">11</span></p> <p><strong>Explanation:</strong></p> <ul> <li data-end="339" data-start="244">The unique prime number formed from the substrings of <code>&quot;111&quot;</code> is 11.</li> <li data-end="412" data-is-last-node="" data-start="340">Since there is only one prime number, the sum is 11.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="39" data-start="18"><code>1 &lt;= s.length &lt;= 10</code></li> <li data-end="68" data-is-last-node="" data-start="40"><code>s</code> consists of only digits.</li> </ul>
Hash Table; Math; String; Number Theory; Sorting
TypeScript
function sumOfLargestPrimes(s: string): number { const st = new Set<number>(); const n = s.length; for (let i = 0; i < n; i++) { let x = 0; for (let j = i; j < n; j++) { x = x * 10 + Number(s[j]); if (isPrime(x)) { st.add(x); } } } const sorted = Array.from(st).sort((a, b) => a - b); const topThree = sorted.slice(-3); return topThree.reduce((sum, val) => sum + val, 0); } function isPrime(x: number): boolean { if (x < 2) return false; for (let i = 2; i * i <= x; i++) { if (x % i === 0) return false; } return true; }
3,560
Find Minimum Log Transportation Cost
Easy
<p>You are given integers <code>n</code>, <code>m</code>, and <code>k</code>.</p> <p>There are two logs of lengths <code>n</code> and <code>m</code> units, which need to be transported in three trucks where each truck can carry one log with length <strong>at most</strong> <code>k</code> units.</p> <p>You may cut the logs into smaller pieces, where the cost of cutting a log of length <code>x</code> into logs of length <code>len1</code> and <code>len2</code> is <code>cost = len1 * len2</code> such that <code>len1 + len2 = x</code>.</p> <p>Return the <strong>minimum total cost</strong> to distribute the logs onto the trucks. If the logs don&#39;t need to be cut, the total cost is 0.</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 = 6, m = 5, k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>Cut the log with length 6 into logs with length 1 and 5, at a cost equal to <code>1 * 5 == 5</code>. Now the three logs of length 1, 5, and 5 can fit in one truck each.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, m = 4, k = 6</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The two logs can fit in the trucks already, hence we don&#39;t need to cut the logs.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= n, m &lt;= 2 * k</code></li> <li>The input is generated such that it is always possible to transport the logs.</li> </ul>
Math
C++
class Solution { public: long long minCuttingCost(int n, int m, int k) { int x = max(n, m); return x <= k ? 0 : 1LL * k * (x - k); } };
3,560
Find Minimum Log Transportation Cost
Easy
<p>You are given integers <code>n</code>, <code>m</code>, and <code>k</code>.</p> <p>There are two logs of lengths <code>n</code> and <code>m</code> units, which need to be transported in three trucks where each truck can carry one log with length <strong>at most</strong> <code>k</code> units.</p> <p>You may cut the logs into smaller pieces, where the cost of cutting a log of length <code>x</code> into logs of length <code>len1</code> and <code>len2</code> is <code>cost = len1 * len2</code> such that <code>len1 + len2 = x</code>.</p> <p>Return the <strong>minimum total cost</strong> to distribute the logs onto the trucks. If the logs don&#39;t need to be cut, the total cost is 0.</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 = 6, m = 5, k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>Cut the log with length 6 into logs with length 1 and 5, at a cost equal to <code>1 * 5 == 5</code>. Now the three logs of length 1, 5, and 5 can fit in one truck each.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, m = 4, k = 6</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The two logs can fit in the trucks already, hence we don&#39;t need to cut the logs.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= n, m &lt;= 2 * k</code></li> <li>The input is generated such that it is always possible to transport the logs.</li> </ul>
Math
Go
func minCuttingCost(n int, m int, k int) int64 { x := max(n, m) if x <= k { return 0 } return int64(k * (x - k)) }
3,560
Find Minimum Log Transportation Cost
Easy
<p>You are given integers <code>n</code>, <code>m</code>, and <code>k</code>.</p> <p>There are two logs of lengths <code>n</code> and <code>m</code> units, which need to be transported in three trucks where each truck can carry one log with length <strong>at most</strong> <code>k</code> units.</p> <p>You may cut the logs into smaller pieces, where the cost of cutting a log of length <code>x</code> into logs of length <code>len1</code> and <code>len2</code> is <code>cost = len1 * len2</code> such that <code>len1 + len2 = x</code>.</p> <p>Return the <strong>minimum total cost</strong> to distribute the logs onto the trucks. If the logs don&#39;t need to be cut, the total cost is 0.</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 = 6, m = 5, k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>Cut the log with length 6 into logs with length 1 and 5, at a cost equal to <code>1 * 5 == 5</code>. Now the three logs of length 1, 5, and 5 can fit in one truck each.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, m = 4, k = 6</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The two logs can fit in the trucks already, hence we don&#39;t need to cut the logs.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= n, m &lt;= 2 * k</code></li> <li>The input is generated such that it is always possible to transport the logs.</li> </ul>
Math
Java
class Solution { public long minCuttingCost(int n, int m, int k) { int x = Math.max(n, m); return x <= k ? 0 : 1L * k * (x - k); } }
3,560
Find Minimum Log Transportation Cost
Easy
<p>You are given integers <code>n</code>, <code>m</code>, and <code>k</code>.</p> <p>There are two logs of lengths <code>n</code> and <code>m</code> units, which need to be transported in three trucks where each truck can carry one log with length <strong>at most</strong> <code>k</code> units.</p> <p>You may cut the logs into smaller pieces, where the cost of cutting a log of length <code>x</code> into logs of length <code>len1</code> and <code>len2</code> is <code>cost = len1 * len2</code> such that <code>len1 + len2 = x</code>.</p> <p>Return the <strong>minimum total cost</strong> to distribute the logs onto the trucks. If the logs don&#39;t need to be cut, the total cost is 0.</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 = 6, m = 5, k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>Cut the log with length 6 into logs with length 1 and 5, at a cost equal to <code>1 * 5 == 5</code>. Now the three logs of length 1, 5, and 5 can fit in one truck each.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, m = 4, k = 6</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The two logs can fit in the trucks already, hence we don&#39;t need to cut the logs.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= n, m &lt;= 2 * k</code></li> <li>The input is generated such that it is always possible to transport the logs.</li> </ul>
Math
Python
class Solution: def minCuttingCost(self, n: int, m: int, k: int) -> int: x = max(n, m) return 0 if x <= k else k * (x - k)
3,560
Find Minimum Log Transportation Cost
Easy
<p>You are given integers <code>n</code>, <code>m</code>, and <code>k</code>.</p> <p>There are two logs of lengths <code>n</code> and <code>m</code> units, which need to be transported in three trucks where each truck can carry one log with length <strong>at most</strong> <code>k</code> units.</p> <p>You may cut the logs into smaller pieces, where the cost of cutting a log of length <code>x</code> into logs of length <code>len1</code> and <code>len2</code> is <code>cost = len1 * len2</code> such that <code>len1 + len2 = x</code>.</p> <p>Return the <strong>minimum total cost</strong> to distribute the logs onto the trucks. If the logs don&#39;t need to be cut, the total cost is 0.</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 = 6, m = 5, k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>Cut the log with length 6 into logs with length 1 and 5, at a cost equal to <code>1 * 5 == 5</code>. Now the three logs of length 1, 5, and 5 can fit in one truck each.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, m = 4, k = 6</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The two logs can fit in the trucks already, hence we don&#39;t need to cut the logs.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= k &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= n, m &lt;= 2 * k</code></li> <li>The input is generated such that it is always possible to transport the logs.</li> </ul>
Math
TypeScript
function minCuttingCost(n: number, m: number, k: number): number { const x = Math.max(n, m); return x <= k ? 0 : k * (x - k); }
3,561
Resulting String After Adjacent Removals
Medium
<p>You are given a string <code>s</code> consisting of lowercase English letters.</p> <p>You <strong>must</strong> repeatedly perform the following operation while the string <code>s</code> has <strong>at least</strong> two <strong>consecutive </strong>characters:</p> <ul> <li>Remove the <strong>leftmost</strong> pair of <strong>adjacent</strong> characters in the string that are <strong>consecutive</strong> in the alphabet, in either order (e.g., <code>&#39;a&#39;</code> and <code>&#39;b&#39;</code>, or <code>&#39;b&#39;</code> and <code>&#39;a&#39;</code>).</li> <li>Shift the remaining characters to the left to fill the gap.</li> </ul> <p>Return the resulting string after no more operations can be performed.</p> <p><strong>Note:</strong> Consider the alphabet as circular, thus <code>&#39;a&#39;</code> and <code>&#39;z&#39;</code> are consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;c&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;ab&quot;</code> from the string, leaving <code>&quot;c&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;c&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;adcb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;dc&quot;</code> from the string, leaving <code>&quot;ab&quot;</code> as the remaining string.</li> <li>Remove <code>&quot;ab&quot;</code> from the string, leaving <code>&quot;&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zadb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;db&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;za&quot;</code> from the string, leaving <code>&quot;db&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;db&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Stack; String; Simulation
C++
class Solution { public: string resultingString(string s) { string stk; for (char c : s) { if (stk.size() && (abs(stk.back() - c) == 1 || abs(stk.back() - c) == 25)) { stk.pop_back(); } else { stk.push_back(c); } } return stk; } };
3,561
Resulting String After Adjacent Removals
Medium
<p>You are given a string <code>s</code> consisting of lowercase English letters.</p> <p>You <strong>must</strong> repeatedly perform the following operation while the string <code>s</code> has <strong>at least</strong> two <strong>consecutive </strong>characters:</p> <ul> <li>Remove the <strong>leftmost</strong> pair of <strong>adjacent</strong> characters in the string that are <strong>consecutive</strong> in the alphabet, in either order (e.g., <code>&#39;a&#39;</code> and <code>&#39;b&#39;</code>, or <code>&#39;b&#39;</code> and <code>&#39;a&#39;</code>).</li> <li>Shift the remaining characters to the left to fill the gap.</li> </ul> <p>Return the resulting string after no more operations can be performed.</p> <p><strong>Note:</strong> Consider the alphabet as circular, thus <code>&#39;a&#39;</code> and <code>&#39;z&#39;</code> are consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;c&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;ab&quot;</code> from the string, leaving <code>&quot;c&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;c&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;adcb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;dc&quot;</code> from the string, leaving <code>&quot;ab&quot;</code> as the remaining string.</li> <li>Remove <code>&quot;ab&quot;</code> from the string, leaving <code>&quot;&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zadb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;db&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;za&quot;</code> from the string, leaving <code>&quot;db&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;db&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Stack; String; Simulation
Go
func resultingString(s string) string { isContiguous := func(a, b rune) bool { x := abs(int(a - b)) return x == 1 || x == 25 } stk := []rune{} for _, c := range s { if len(stk) > 0 && isContiguous(stk[len(stk)-1], c) { stk = stk[:len(stk)-1] } else { stk = append(stk, c) } } return string(stk) } func abs(x int) int { if x < 0 { return -x } return x }
3,561
Resulting String After Adjacent Removals
Medium
<p>You are given a string <code>s</code> consisting of lowercase English letters.</p> <p>You <strong>must</strong> repeatedly perform the following operation while the string <code>s</code> has <strong>at least</strong> two <strong>consecutive </strong>characters:</p> <ul> <li>Remove the <strong>leftmost</strong> pair of <strong>adjacent</strong> characters in the string that are <strong>consecutive</strong> in the alphabet, in either order (e.g., <code>&#39;a&#39;</code> and <code>&#39;b&#39;</code>, or <code>&#39;b&#39;</code> and <code>&#39;a&#39;</code>).</li> <li>Shift the remaining characters to the left to fill the gap.</li> </ul> <p>Return the resulting string after no more operations can be performed.</p> <p><strong>Note:</strong> Consider the alphabet as circular, thus <code>&#39;a&#39;</code> and <code>&#39;z&#39;</code> are consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;c&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;ab&quot;</code> from the string, leaving <code>&quot;c&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;c&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;adcb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;dc&quot;</code> from the string, leaving <code>&quot;ab&quot;</code> as the remaining string.</li> <li>Remove <code>&quot;ab&quot;</code> from the string, leaving <code>&quot;&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zadb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;db&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;za&quot;</code> from the string, leaving <code>&quot;db&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;db&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Stack; String; Simulation
Java
class Solution { public String resultingString(String s) { StringBuilder stk = new StringBuilder(); for (char c : s.toCharArray()) { if (stk.length() > 0 && isContiguous(stk.charAt(stk.length() - 1), c)) { stk.deleteCharAt(stk.length() - 1); } else { stk.append(c); } } return stk.toString(); } private boolean isContiguous(char a, char b) { int t = Math.abs(a - b); return t == 1 || t == 25; } }
3,561
Resulting String After Adjacent Removals
Medium
<p>You are given a string <code>s</code> consisting of lowercase English letters.</p> <p>You <strong>must</strong> repeatedly perform the following operation while the string <code>s</code> has <strong>at least</strong> two <strong>consecutive </strong>characters:</p> <ul> <li>Remove the <strong>leftmost</strong> pair of <strong>adjacent</strong> characters in the string that are <strong>consecutive</strong> in the alphabet, in either order (e.g., <code>&#39;a&#39;</code> and <code>&#39;b&#39;</code>, or <code>&#39;b&#39;</code> and <code>&#39;a&#39;</code>).</li> <li>Shift the remaining characters to the left to fill the gap.</li> </ul> <p>Return the resulting string after no more operations can be performed.</p> <p><strong>Note:</strong> Consider the alphabet as circular, thus <code>&#39;a&#39;</code> and <code>&#39;z&#39;</code> are consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;c&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;ab&quot;</code> from the string, leaving <code>&quot;c&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;c&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;adcb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;dc&quot;</code> from the string, leaving <code>&quot;ab&quot;</code> as the remaining string.</li> <li>Remove <code>&quot;ab&quot;</code> from the string, leaving <code>&quot;&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zadb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;db&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;za&quot;</code> from the string, leaving <code>&quot;db&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;db&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Stack; String; Simulation
Python
class Solution: def resultingString(self, s: str) -> str: stk = [] for c in s: if stk and abs(ord(c) - ord(stk[-1])) in (1, 25): stk.pop() else: stk.append(c) return "".join(stk)
3,561
Resulting String After Adjacent Removals
Medium
<p>You are given a string <code>s</code> consisting of lowercase English letters.</p> <p>You <strong>must</strong> repeatedly perform the following operation while the string <code>s</code> has <strong>at least</strong> two <strong>consecutive </strong>characters:</p> <ul> <li>Remove the <strong>leftmost</strong> pair of <strong>adjacent</strong> characters in the string that are <strong>consecutive</strong> in the alphabet, in either order (e.g., <code>&#39;a&#39;</code> and <code>&#39;b&#39;</code>, or <code>&#39;b&#39;</code> and <code>&#39;a&#39;</code>).</li> <li>Shift the remaining characters to the left to fill the gap.</li> </ul> <p>Return the resulting string after no more operations can be performed.</p> <p><strong>Note:</strong> Consider the alphabet as circular, thus <code>&#39;a&#39;</code> and <code>&#39;z&#39;</code> are consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;c&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;ab&quot;</code> from the string, leaving <code>&quot;c&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;c&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;adcb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;dc&quot;</code> from the string, leaving <code>&quot;ab&quot;</code> as the remaining string.</li> <li>Remove <code>&quot;ab&quot;</code> from the string, leaving <code>&quot;&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zadb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;db&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>&quot;za&quot;</code> from the string, leaving <code>&quot;db&quot;</code> as the remaining string.</li> <li>No further operations are possible. Thus, the resulting string after all possible removals is <code>&quot;db&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Stack; String; Simulation
TypeScript
function resultingString(s: string): string { const stk: string[] = []; const isContiguous = (a: string, b: string): boolean => { const x = Math.abs(a.charCodeAt(0) - b.charCodeAt(0)); return x === 1 || x === 25; }; for (const c of s) { if (stk.length && isContiguous(stk.at(-1)!, c)) { stk.pop(); } else { stk.push(c); } } return stk.join(''); }
3,564
Seasonal Sales Analysis
Medium
<p>Table: <code>sales</code></p> <pre> +---------------+---------+ | Column Name | Type | +---------------+---------+ | sale_id | int | | product_id | int | | sale_date | date | | quantity | int | | price | decimal | +---------------+---------+ sale_id is the unique identifier for this table. Each row contains information about a product sale including the product_id, date of sale, quantity sold, and price per unit. </pre> <p>Table: <code>products</code></p> <pre> +---------------+---------+ | Column Name | Type | +---------------+---------+ | product_id | int | | product_name | varchar | | category | varchar | +---------------+---------+ product_id is the unique identifier for this table. Each row contains information about a product including its name and category. </pre> <p>Write a solution to find the most popular product category for each season. The seasons are defined as:</p> <ul> <li><strong>Winter</strong>: December, January, February</li> <li><strong>Spring</strong>: March, April, May</li> <li><strong>Summer</strong>: June, July, August</li> <li><strong>Fall</strong>: September, October, November</li> </ul> <p>The <strong>popularity</strong> of a <strong>category</strong> is determined by the <strong>total quantity sold</strong> in that <strong>season</strong>. If there is a <strong>tie</strong>, select the category with the highest <strong>total revenue</strong> (<code>quantity &times; price</code>).</p> <p>Return <em>the result table ordered by season 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>sales table:</p> <pre class="example-io"> +---------+------------+------------+----------+-------+ | sale_id | product_id | sale_date | quantity | price | +---------+------------+------------+----------+-------+ | 1 | 1 | 2023-01-15 | 5 | 10.00 | | 2 | 2 | 2023-01-20 | 4 | 15.00 | | 3 | 3 | 2023-03-10 | 3 | 18.00 | | 4 | 4 | 2023-04-05 | 1 | 20.00 | | 5 | 1 | 2023-05-20 | 2 | 10.00 | | 6 | 2 | 2023-06-12 | 4 | 15.00 | | 7 | 5 | 2023-06-15 | 5 | 12.00 | | 8 | 3 | 2023-07-24 | 2 | 18.00 | | 9 | 4 | 2023-08-01 | 5 | 20.00 | | 10 | 5 | 2023-09-03 | 3 | 12.00 | | 11 | 1 | 2023-09-25 | 6 | 10.00 | | 12 | 2 | 2023-11-10 | 4 | 15.00 | | 13 | 3 | 2023-12-05 | 6 | 18.00 | | 14 | 4 | 2023-12-22 | 3 | 20.00 | | 15 | 5 | 2024-02-14 | 2 | 12.00 | +---------+------------+------------+----------+-------+ </pre> <p>products table:</p> <pre class="example-io"> +------------+-----------------+----------+ | product_id | product_name | category | +------------+-----------------+----------+ | 1 | Warm Jacket | Apparel | | 2 | Designer Jeans | Apparel | | 3 | Cutting Board | Kitchen | | 4 | Smart Speaker | Tech | | 5 | Yoga Mat | Fitness | +------------+-----------------+----------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+----------+----------------+---------------+ | season | category | total_quantity | total_revenue | +---------+----------+----------------+---------------+ | Fall | Apparel | 10 | 120.00 | | Spring | Kitchen | 3 | 54.00 | | Summer | Tech | 5 | 100.00 | | Winter | Apparel | 9 | 110.00 | +---------+----------+----------------+---------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Fall (Sep, Oct, Nov):</strong> <ul> <li>Apparel: 10 items sold (6 Jackets in Sep, 4 Jeans in Nov), revenue $120.00 (6&times;$10.00 + 4&times;$15.00)</li> <li>Fitness: 3 Yoga Mats sold in Sep, revenue $36.00</li> <li>Most popular: Apparel with highest total quantity (10)</li> </ul> </li> <li><strong>Spring (Mar, Apr, May):</strong> <ul> <li>Kitchen: 3 Cutting Boards sold in Mar, revenue $54.00</li> <li>Tech: 1 Smart Speaker sold in Apr, revenue $20.00</li> <li>Apparel: 2 Warm Jackets sold in May, revenue $20.00</li> <li>Most popular: Kitchen with highest total quantity (3) and highest revenue ($54.00)</li> </ul> </li> <li><strong>Summer (Jun, Jul, Aug):</strong> <ul> <li>Apparel: 4 Designer Jeans sold in Jun, revenue $60.00</li> <li>Fitness: 5 Yoga Mats sold in Jun, revenue $60.00</li> <li>Kitchen: 2 Cutting Boards sold in Jul, revenue $36.00</li> <li>Tech: 5 Smart Speakers sold in Aug, revenue $100.00</li> <li>Most popular: Tech and Fitness both have 5 items, but Tech has higher revenue ($100.00 vs $60.00)</li> </ul> </li> <li><strong>Winter (Dec, Jan, Feb):</strong> <ul> <li>Apparel: 9 items sold (5 Jackets in Jan, 4 Jeans in Jan), revenue $110.00</li> <li>Kitchen: 6 Cutting Boards sold in Dec, revenue $108.00</li> <li>Tech: 3 Smart Speakers sold in Dec, revenue $60.00</li> <li>Fitness: 2 Yoga Mats sold in Feb, revenue $24.00</li> <li>Most popular: Apparel with highest total quantity (9) and highest revenue ($110.00)</li> </ul> </li> </ul> <p>The result table is ordered by season in ascending order.</p> </div>
Database
Python
import pandas as pd def seasonal_sales_analysis( products: pd.DataFrame, sales: pd.DataFrame ) -> pd.DataFrame: df = sales.merge(products, on="product_id") month_to_season = { 12: "Winter", 1: "Winter", 2: "Winter", 3: "Spring", 4: "Spring", 5: "Spring", 6: "Summer", 7: "Summer", 8: "Summer", 9: "Fall", 10: "Fall", 11: "Fall", } df["season"] = df["sale_date"].dt.month.map(month_to_season) seasonal_sales = df.groupby(["season", "category"], as_index=False).agg( total_quantity=("quantity", "sum"), total_revenue=("quantity", lambda x: (x * df.loc[x.index, "price"]).sum()), ) seasonal_sales["rk"] = ( seasonal_sales.sort_values( ["season", "total_quantity", "total_revenue"], ascending=[True, False, False], ) .groupby("season") .cumcount() + 1 ) result = seasonal_sales[seasonal_sales["rk"] == 1].copy() return result[ ["season", "category", "total_quantity", "total_revenue"] ].sort_values("season")
3,564
Seasonal Sales Analysis
Medium
<p>Table: <code>sales</code></p> <pre> +---------------+---------+ | Column Name | Type | +---------------+---------+ | sale_id | int | | product_id | int | | sale_date | date | | quantity | int | | price | decimal | +---------------+---------+ sale_id is the unique identifier for this table. Each row contains information about a product sale including the product_id, date of sale, quantity sold, and price per unit. </pre> <p>Table: <code>products</code></p> <pre> +---------------+---------+ | Column Name | Type | +---------------+---------+ | product_id | int | | product_name | varchar | | category | varchar | +---------------+---------+ product_id is the unique identifier for this table. Each row contains information about a product including its name and category. </pre> <p>Write a solution to find the most popular product category for each season. The seasons are defined as:</p> <ul> <li><strong>Winter</strong>: December, January, February</li> <li><strong>Spring</strong>: March, April, May</li> <li><strong>Summer</strong>: June, July, August</li> <li><strong>Fall</strong>: September, October, November</li> </ul> <p>The <strong>popularity</strong> of a <strong>category</strong> is determined by the <strong>total quantity sold</strong> in that <strong>season</strong>. If there is a <strong>tie</strong>, select the category with the highest <strong>total revenue</strong> (<code>quantity &times; price</code>).</p> <p>Return <em>the result table ordered by season 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>sales table:</p> <pre class="example-io"> +---------+------------+------------+----------+-------+ | sale_id | product_id | sale_date | quantity | price | +---------+------------+------------+----------+-------+ | 1 | 1 | 2023-01-15 | 5 | 10.00 | | 2 | 2 | 2023-01-20 | 4 | 15.00 | | 3 | 3 | 2023-03-10 | 3 | 18.00 | | 4 | 4 | 2023-04-05 | 1 | 20.00 | | 5 | 1 | 2023-05-20 | 2 | 10.00 | | 6 | 2 | 2023-06-12 | 4 | 15.00 | | 7 | 5 | 2023-06-15 | 5 | 12.00 | | 8 | 3 | 2023-07-24 | 2 | 18.00 | | 9 | 4 | 2023-08-01 | 5 | 20.00 | | 10 | 5 | 2023-09-03 | 3 | 12.00 | | 11 | 1 | 2023-09-25 | 6 | 10.00 | | 12 | 2 | 2023-11-10 | 4 | 15.00 | | 13 | 3 | 2023-12-05 | 6 | 18.00 | | 14 | 4 | 2023-12-22 | 3 | 20.00 | | 15 | 5 | 2024-02-14 | 2 | 12.00 | +---------+------------+------------+----------+-------+ </pre> <p>products table:</p> <pre class="example-io"> +------------+-----------------+----------+ | product_id | product_name | category | +------------+-----------------+----------+ | 1 | Warm Jacket | Apparel | | 2 | Designer Jeans | Apparel | | 3 | Cutting Board | Kitchen | | 4 | Smart Speaker | Tech | | 5 | Yoga Mat | Fitness | +------------+-----------------+----------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+----------+----------------+---------------+ | season | category | total_quantity | total_revenue | +---------+----------+----------------+---------------+ | Fall | Apparel | 10 | 120.00 | | Spring | Kitchen | 3 | 54.00 | | Summer | Tech | 5 | 100.00 | | Winter | Apparel | 9 | 110.00 | +---------+----------+----------------+---------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Fall (Sep, Oct, Nov):</strong> <ul> <li>Apparel: 10 items sold (6 Jackets in Sep, 4 Jeans in Nov), revenue $120.00 (6&times;$10.00 + 4&times;$15.00)</li> <li>Fitness: 3 Yoga Mats sold in Sep, revenue $36.00</li> <li>Most popular: Apparel with highest total quantity (10)</li> </ul> </li> <li><strong>Spring (Mar, Apr, May):</strong> <ul> <li>Kitchen: 3 Cutting Boards sold in Mar, revenue $54.00</li> <li>Tech: 1 Smart Speaker sold in Apr, revenue $20.00</li> <li>Apparel: 2 Warm Jackets sold in May, revenue $20.00</li> <li>Most popular: Kitchen with highest total quantity (3) and highest revenue ($54.00)</li> </ul> </li> <li><strong>Summer (Jun, Jul, Aug):</strong> <ul> <li>Apparel: 4 Designer Jeans sold in Jun, revenue $60.00</li> <li>Fitness: 5 Yoga Mats sold in Jun, revenue $60.00</li> <li>Kitchen: 2 Cutting Boards sold in Jul, revenue $36.00</li> <li>Tech: 5 Smart Speakers sold in Aug, revenue $100.00</li> <li>Most popular: Tech and Fitness both have 5 items, but Tech has higher revenue ($100.00 vs $60.00)</li> </ul> </li> <li><strong>Winter (Dec, Jan, Feb):</strong> <ul> <li>Apparel: 9 items sold (5 Jackets in Jan, 4 Jeans in Jan), revenue $110.00</li> <li>Kitchen: 6 Cutting Boards sold in Dec, revenue $108.00</li> <li>Tech: 3 Smart Speakers sold in Dec, revenue $60.00</li> <li>Fitness: 2 Yoga Mats sold in Feb, revenue $24.00</li> <li>Most popular: Apparel with highest total quantity (9) and highest revenue ($110.00)</li> </ul> </li> </ul> <p>The result table is ordered by season in ascending order.</p> </div>
Database
SQL
# Write your MySQL query statement below WITH SeasonalSales AS ( SELECT CASE WHEN MONTH(sale_date) IN (12, 1, 2) THEN 'Winter' WHEN MONTH(sale_date) IN (3, 4, 5) THEN 'Spring' WHEN MONTH(sale_date) IN (6, 7, 8) THEN 'Summer' WHEN MONTH(sale_date) IN (9, 10, 11) THEN 'Fall' END AS season, category, SUM(quantity) AS total_quantity, SUM(quantity * price) AS total_revenue FROM sales JOIN products USING (product_id) GROUP BY 1, 2 ), TopCategoryPerSeason AS ( SELECT *, RANK() OVER ( PARTITION BY season ORDER BY total_quantity DESC, total_revenue DESC ) AS rk FROM SeasonalSales ) SELECT season, category, total_quantity, total_revenue FROM TopCategoryPerSeason WHERE rk = 1 ORDER BY 1;
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
C++
class Solution { int m, n; unsigned long long st = 0; vector<vector<int>> path; int dirs[5] = {-1, 0, 1, 0, -1}; int f(int i, int j) { return i * n + j; } bool dfs(int i, int j, int v, vector<vector<int>>& grid) { path.push_back({i, j}); if (path.size() == static_cast<size_t>(m * n)) { return true; } st |= 1ULL << 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 & (1ULL << f(x, y))) == 0 && (grid[x][y] == 0 || grid[x][y] == v)) { if (dfs(x, y, v, grid)) { return true; } } } path.pop_back(); st ^= 1ULL << f(i, j); return false; } public: vector<vector<int>> findPath(vector<vector<int>>& grid, int k) { m = grid.size(); n = grid[0].size(); 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 {}; } };
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
Go
func findPath(grid [][]int, k int) [][]int { _ = k m := len(grid) n := len(grid[0]) var st uint64 path := [][]int{} dirs := []int{-1, 0, 1, 0, -1} f := func(i, j int) int { return i*n + j } var dfs func(int, int, int) bool dfs = func(i, j, v int) bool { path = append(path, []int{i, j}) if len(path) == m*n { return true } idx := f(i, j) st |= 1 << idx if grid[i][j] == v { v++ } for t := 0; t < 4; t++ { a, b := dirs[t], dirs[t+1] x, y := i+a, j+b if 0 <= x && x < m && 0 <= y && y < n { idx2 := f(x, y) if (st>>idx2)&1 == 0 && (grid[x][y] == 0 || grid[x][y] == v) { if dfs(x, y, v) { return true } } } } path = path[:len(path)-1] st ^= 1 << idx return false } for i := 0; i < m; i++ { for j := 0; j < n; j++ { if grid[i][j] == 0 || grid[i][j] == 1 { if dfs(i, j, 1) { return path } path = path[:0] st = 0 } } } return [][]int{} }
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; } };