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,390
Longest Team Pass Streak
Hard
<p>Table: <code>Teams</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | player_id | int | | team_name | varchar | +-------------+---------+ player_id is the unique key for this table. Each row contains the unique identifier for player and the name of one of the teams participating in that match. </pre> <p>Table: <code>Passes</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | pass_from | int | | time_stamp | varchar | | pass_to | int | +-------------+---------+ (pass_from, time_stamp) is the unique key for this table. pass_from is a foreign key to player_id from Teams table. Each row represents a pass made during a match, time_stamp represents the time in minutes (00:00-90:00) when the pass was made, pass_to is the player_id of the player receiving the pass. </pre> <p>Write a solution to find the <strong>longest successful pass streak</strong> for <strong>each team</strong> during the match. The rules are as follows:</p> <ul> <li>A successful pass streak is defined as consecutive passes where: <ul> <li>Both the <code>pass_from</code> and <code>pass_to</code> players belong to the same team</li> </ul> </li> <li>A streak breaks when either: <ul> <li>The pass is intercepted (received by a player from the opposing team)</li> </ul> </li> </ul> <p>Return <em>the result table ordered by</em> <code>team_name</code> <em>in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Teams table:</p> <pre> +-----------+-----------+ | player_id | team_name | +-----------+-----------+ | 1 | Arsenal | | 2 | Arsenal | | 3 | Arsenal | | 4 | Arsenal | | 5 | Chelsea | | 6 | Chelsea | | 7 | Chelsea | | 8 | Chelsea | +-----------+-----------+ </pre> <p>Passes table:</p> <pre> +-----------+------------+---------+ | pass_from | time_stamp | pass_to | +-----------+------------+---------+ | 1 | 00:05 | 2 | | 2 | 00:07 | 3 | | 3 | 00:08 | 4 | | 4 | 00:10 | 5 | | 6 | 00:15 | 7 | | 7 | 00:17 | 8 | | 8 | 00:20 | 6 | | 6 | 00:22 | 5 | | 1 | 00:25 | 2 | | 2 | 00:27 | 3 | +-----------+------------+---------+ </pre> <p><strong>Output:</strong></p> <pre> +-----------+----------------+ | team_name | longest_streak | +-----------+----------------+ | Arsenal | 3 | | Chelsea | 4 | +-----------+----------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Arsenal</strong>&#39;s streaks: <ul> <li>First streak: 3 passes (1&rarr;2&rarr;3&rarr;4) ended when player 4 passed to Chelsea&#39;s player 5</li> <li>Second streak: 2 passes (1&rarr;2&rarr;3)</li> <li>Longest streak = 3</li> </ul> </li> <li><strong>Chelsea</strong>&#39;s streaks: <ul> <li>First streak: 3 passes (6&rarr;7&rarr;8&rarr;6&rarr;5)</li> <li>Longest streak = 4</li> </ul> </li> </ul> </div>
Database
SQL
WITH PassesWithTeams AS ( SELECT p.pass_from, p.pass_to, t1.team_name AS team_from, t2.team_name AS team_to, IF(t1.team_name = t2.team_name, 1, 0) same_team_flag, p.time_stamp FROM Passes p JOIN Teams t1 ON p.pass_from = t1.player_id JOIN Teams t2 ON p.pass_to = t2.player_id ), StreakGroups AS ( SELECT team_from AS team_name, time_stamp, same_team_flag, SUM( CASE WHEN same_team_flag = 0 THEN 1 ELSE 0 END ) OVER ( PARTITION BY team_from ORDER BY time_stamp ) AS group_id FROM PassesWithTeams ), StreakLengths AS ( SELECT team_name, group_id, COUNT(*) AS streak_length FROM StreakGroups WHERE same_team_flag = 1 GROUP BY 1, 2 ), LongestStreaks AS ( SELECT team_name, MAX(streak_length) AS longest_streak FROM StreakLengths GROUP BY 1 ) SELECT team_name, longest_streak FROM LongestStreaks ORDER BY 1;
3,391
Design a 3D Binary Matrix with Efficient Layer Tracking
Medium
<p>You are given a <code>n x n x n</code> <strong>binary</strong> 3D array <code>matrix</code>.</p> <p>Implement the <code>Matrix3D</code> class:</p> <ul> <li><code>Matrix3D(int n)</code> Initializes the object with the 3D binary array <code>matrix</code>, where <strong>all</strong> elements are initially set to 0.</li> <li><code>void setCell(int x, int y, int z)</code> Sets the value at <code>matrix[x][y][z]</code> to 1.</li> <li><code>void unsetCell(int x, int y, int z)</code> Sets the value at <code>matrix[x][y][z]</code> to 0.</li> <li><code>int largestMatrix()</code> Returns the index <code>x</code> where <code>matrix[x]</code> contains the most number of 1&#39;s. If there are multiple such indices, return the <strong>largest</strong> <code>x</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Matrix3D&quot;, &quot;setCell&quot;, &quot;largestMatrix&quot;, &quot;setCell&quot;, &quot;largestMatrix&quot;, &quot;setCell&quot;, &quot;largestMatrix&quot;]<br /> [[3], [0, 0, 0], [], [1, 1, 2], [], [0, 0, 1], []]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, null, 0, null, 1, null, 0] </span></p> <p><strong>Explanation</strong></p> Matrix3D matrix3D = new Matrix3D(3); // Initializes a <code>3 x 3 x 3</code> 3D array <code>matrix</code>, filled with all 0&#39;s.<br /> matrix3D.setCell(0, 0, 0); // Sets <code>matrix[0][0][0]</code> to 1.<br /> matrix3D.largestMatrix(); // Returns 0. <code>matrix[0]</code> has the most number of 1&#39;s.<br /> matrix3D.setCell(1, 1, 2); // Sets <code>matrix[1][1][2]</code> to 1.<br /> matrix3D.largestMatrix(); // Returns 1. <code>matrix[0]</code> and <code>matrix[1]</code> tie with the most number of 1&#39;s, but index 1 is bigger.<br /> matrix3D.setCell(0, 0, 1); // Sets <code>matrix[0][0][1]</code> to 1.<br /> matrix3D.largestMatrix(); // Returns 0. <code>matrix[0]</code> has the most number of 1&#39;s.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Matrix3D&quot;, &quot;setCell&quot;, &quot;largestMatrix&quot;, &quot;unsetCell&quot;, &quot;largestMatrix&quot;]<br /> [[4], [2, 1, 1], [], [2, 1, 1], []]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, null, 2, null, 3] </span></p> <p><strong>Explanation</strong></p> Matrix3D matrix3D = new Matrix3D(4); // Initializes a <code>4 x 4 x 4</code> 3D array <code>matrix</code>, filled with all 0&#39;s.<br /> matrix3D.setCell(2, 1, 1); // Sets <code>matrix[2][1][1]</code> to 1.<br /> matrix3D.largestMatrix(); // Returns 2. <code>matrix[2]</code> has the most number of 1&#39;s.<br /> matrix3D.unsetCell(2, 1, 1); // Sets <code>matrix[2][1][1]</code> to 0.<br /> matrix3D.largestMatrix(); // Returns 3. All indices from 0 to 3 tie with the same number of 1&#39;s, but index 3 is the biggest.</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>0 &lt;= x, y, z &lt; n</code></li> <li>At most <code>10<sup>5</sup></code> calls are made in total to <code>setCell</code> and <code>unsetCell</code>.</li> <li>At most <code>10<sup>4</sup></code> calls are made to <code>largestMatrix</code>.</li> </ul>
Design; Array; Hash Table; Matrix; Ordered Set; Heap (Priority Queue)
C++
class matrix3D { private: vector<vector<vector<int>>> g; vector<int> cnt; set<pair<int, int>> sl; public: matrix3D(int n) { g.resize(n, vector<vector<int>>(n, vector<int>(n, 0))); cnt.resize(n, 0); } void setCell(int x, int y, int z) { if (g[x][y][z] == 1) { return; } g[x][y][z] = 1; sl.erase({-cnt[x], -x}); cnt[x]++; sl.insert({-cnt[x], -x}); } void unsetCell(int x, int y, int z) { if (g[x][y][z] == 0) { return; } g[x][y][z] = 0; sl.erase({-cnt[x], -x}); cnt[x]--; if (cnt[x]) { sl.insert({-cnt[x], -x}); } } int largestMatrix() { return sl.empty() ? g.size() - 1 : -sl.begin()->second; } }; /** * Your matrix3D object will be instantiated and called as such: * matrix3D* obj = new matrix3D(n); * obj->setCell(x,y,z); * obj->unsetCell(x,y,z); * int param_3 = obj->largestMatrix(); */
3,391
Design a 3D Binary Matrix with Efficient Layer Tracking
Medium
<p>You are given a <code>n x n x n</code> <strong>binary</strong> 3D array <code>matrix</code>.</p> <p>Implement the <code>Matrix3D</code> class:</p> <ul> <li><code>Matrix3D(int n)</code> Initializes the object with the 3D binary array <code>matrix</code>, where <strong>all</strong> elements are initially set to 0.</li> <li><code>void setCell(int x, int y, int z)</code> Sets the value at <code>matrix[x][y][z]</code> to 1.</li> <li><code>void unsetCell(int x, int y, int z)</code> Sets the value at <code>matrix[x][y][z]</code> to 0.</li> <li><code>int largestMatrix()</code> Returns the index <code>x</code> where <code>matrix[x]</code> contains the most number of 1&#39;s. If there are multiple such indices, return the <strong>largest</strong> <code>x</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Matrix3D&quot;, &quot;setCell&quot;, &quot;largestMatrix&quot;, &quot;setCell&quot;, &quot;largestMatrix&quot;, &quot;setCell&quot;, &quot;largestMatrix&quot;]<br /> [[3], [0, 0, 0], [], [1, 1, 2], [], [0, 0, 1], []]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, null, 0, null, 1, null, 0] </span></p> <p><strong>Explanation</strong></p> Matrix3D matrix3D = new Matrix3D(3); // Initializes a <code>3 x 3 x 3</code> 3D array <code>matrix</code>, filled with all 0&#39;s.<br /> matrix3D.setCell(0, 0, 0); // Sets <code>matrix[0][0][0]</code> to 1.<br /> matrix3D.largestMatrix(); // Returns 0. <code>matrix[0]</code> has the most number of 1&#39;s.<br /> matrix3D.setCell(1, 1, 2); // Sets <code>matrix[1][1][2]</code> to 1.<br /> matrix3D.largestMatrix(); // Returns 1. <code>matrix[0]</code> and <code>matrix[1]</code> tie with the most number of 1&#39;s, but index 1 is bigger.<br /> matrix3D.setCell(0, 0, 1); // Sets <code>matrix[0][0][1]</code> to 1.<br /> matrix3D.largestMatrix(); // Returns 0. <code>matrix[0]</code> has the most number of 1&#39;s.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Matrix3D&quot;, &quot;setCell&quot;, &quot;largestMatrix&quot;, &quot;unsetCell&quot;, &quot;largestMatrix&quot;]<br /> [[4], [2, 1, 1], [], [2, 1, 1], []]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, null, 2, null, 3] </span></p> <p><strong>Explanation</strong></p> Matrix3D matrix3D = new Matrix3D(4); // Initializes a <code>4 x 4 x 4</code> 3D array <code>matrix</code>, filled with all 0&#39;s.<br /> matrix3D.setCell(2, 1, 1); // Sets <code>matrix[2][1][1]</code> to 1.<br /> matrix3D.largestMatrix(); // Returns 2. <code>matrix[2]</code> has the most number of 1&#39;s.<br /> matrix3D.unsetCell(2, 1, 1); // Sets <code>matrix[2][1][1]</code> to 0.<br /> matrix3D.largestMatrix(); // Returns 3. All indices from 0 to 3 tie with the same number of 1&#39;s, but index 3 is the biggest.</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>0 &lt;= x, y, z &lt; n</code></li> <li>At most <code>10<sup>5</sup></code> calls are made in total to <code>setCell</code> and <code>unsetCell</code>.</li> <li>At most <code>10<sup>4</sup></code> calls are made to <code>largestMatrix</code>.</li> </ul>
Design; Array; Hash Table; Matrix; Ordered Set; Heap (Priority Queue)
Java
class matrix3D { private final int[][][] g; private final int[] cnt; private final TreeSet<int[]> sl = new TreeSet<>((a, b) -> a[0] == b[0] ? b[1] - a[1] : b[0] - a[0]); public matrix3D(int n) { g = new int[n][n][n]; cnt = new int[n]; } public void setCell(int x, int y, int z) { if (g[x][y][z] == 1) { return; } g[x][y][z] = 1; sl.remove(new int[] {cnt[x], x}); cnt[x]++; sl.add(new int[] {cnt[x], x}); } public void unsetCell(int x, int y, int z) { if (g[x][y][z] == 0) { return; } g[x][y][z] = 0; sl.remove(new int[] {cnt[x], x}); cnt[x]--; if (cnt[x] > 0) { sl.add(new int[] {cnt[x], x}); } } public int largestMatrix() { return sl.isEmpty() ? g.length - 1 : sl.first()[1]; } } /** * Your matrix3D object will be instantiated and called as such: * matrix3D obj = new matrix3D(n); * obj.setCell(x,y,z); * obj.unsetCell(x,y,z); * int param_3 = obj.largestMatrix(); */
3,391
Design a 3D Binary Matrix with Efficient Layer Tracking
Medium
<p>You are given a <code>n x n x n</code> <strong>binary</strong> 3D array <code>matrix</code>.</p> <p>Implement the <code>Matrix3D</code> class:</p> <ul> <li><code>Matrix3D(int n)</code> Initializes the object with the 3D binary array <code>matrix</code>, where <strong>all</strong> elements are initially set to 0.</li> <li><code>void setCell(int x, int y, int z)</code> Sets the value at <code>matrix[x][y][z]</code> to 1.</li> <li><code>void unsetCell(int x, int y, int z)</code> Sets the value at <code>matrix[x][y][z]</code> to 0.</li> <li><code>int largestMatrix()</code> Returns the index <code>x</code> where <code>matrix[x]</code> contains the most number of 1&#39;s. If there are multiple such indices, return the <strong>largest</strong> <code>x</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Matrix3D&quot;, &quot;setCell&quot;, &quot;largestMatrix&quot;, &quot;setCell&quot;, &quot;largestMatrix&quot;, &quot;setCell&quot;, &quot;largestMatrix&quot;]<br /> [[3], [0, 0, 0], [], [1, 1, 2], [], [0, 0, 1], []]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, null, 0, null, 1, null, 0] </span></p> <p><strong>Explanation</strong></p> Matrix3D matrix3D = new Matrix3D(3); // Initializes a <code>3 x 3 x 3</code> 3D array <code>matrix</code>, filled with all 0&#39;s.<br /> matrix3D.setCell(0, 0, 0); // Sets <code>matrix[0][0][0]</code> to 1.<br /> matrix3D.largestMatrix(); // Returns 0. <code>matrix[0]</code> has the most number of 1&#39;s.<br /> matrix3D.setCell(1, 1, 2); // Sets <code>matrix[1][1][2]</code> to 1.<br /> matrix3D.largestMatrix(); // Returns 1. <code>matrix[0]</code> and <code>matrix[1]</code> tie with the most number of 1&#39;s, but index 1 is bigger.<br /> matrix3D.setCell(0, 0, 1); // Sets <code>matrix[0][0][1]</code> to 1.<br /> matrix3D.largestMatrix(); // Returns 0. <code>matrix[0]</code> has the most number of 1&#39;s.</div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Matrix3D&quot;, &quot;setCell&quot;, &quot;largestMatrix&quot;, &quot;unsetCell&quot;, &quot;largestMatrix&quot;]<br /> [[4], [2, 1, 1], [], [2, 1, 1], []]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, null, 2, null, 3] </span></p> <p><strong>Explanation</strong></p> Matrix3D matrix3D = new Matrix3D(4); // Initializes a <code>4 x 4 x 4</code> 3D array <code>matrix</code>, filled with all 0&#39;s.<br /> matrix3D.setCell(2, 1, 1); // Sets <code>matrix[2][1][1]</code> to 1.<br /> matrix3D.largestMatrix(); // Returns 2. <code>matrix[2]</code> has the most number of 1&#39;s.<br /> matrix3D.unsetCell(2, 1, 1); // Sets <code>matrix[2][1][1]</code> to 0.<br /> matrix3D.largestMatrix(); // Returns 3. All indices from 0 to 3 tie with the same number of 1&#39;s, but index 3 is the biggest.</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code>0 &lt;= x, y, z &lt; n</code></li> <li>At most <code>10<sup>5</sup></code> calls are made in total to <code>setCell</code> and <code>unsetCell</code>.</li> <li>At most <code>10<sup>4</sup></code> calls are made to <code>largestMatrix</code>.</li> </ul>
Design; Array; Hash Table; Matrix; Ordered Set; Heap (Priority Queue)
Python
class matrix3D: def __init__(self, n: int): self.g = [[[0] * n for _ in range(n)] for _ in range(n)] self.cnt = [0] * n self.sl = SortedList(key=lambda x: (-x[0], -x[1])) def setCell(self, x: int, y: int, z: int) -> None: if self.g[x][y][z]: return self.g[x][y][z] = 1 self.sl.discard((self.cnt[x], x)) self.cnt[x] += 1 self.sl.add((self.cnt[x], x)) def unsetCell(self, x: int, y: int, z: int) -> None: if self.g[x][y][z] == 0: return self.g[x][y][z] = 0 self.sl.discard((self.cnt[x], x)) self.cnt[x] -= 1 if self.cnt[x]: self.sl.add((self.cnt[x], x)) def largestMatrix(self) -> int: return self.sl[0][1] if self.sl else len(self.g) - 1 # Your matrix3D object will be instantiated and called as such: # obj = matrix3D(n) # obj.setCell(x,y,z) # obj.unsetCell(x,y,z) # param_3 = obj.largestMatrix()
3,392
Count Subarrays of Length Three With a Condition
Easy
<p>Given an integer array <code>nums</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of length 3 such that the sum of the first and third numbers equals <em>exactly</em> half of the second number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Only the subarray <code>[1,4,1]</code> contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>[1,1,1]</code> is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 100</code></li> <li><code><font face="monospace">-100 &lt;= nums[i] &lt;= 100</font></code></li> </ul>
Array
C++
class Solution { public: int countSubarrays(vector<int>& nums) { int ans = 0; for (int i = 1; i + 1 < nums.size(); ++i) { if ((nums[i - 1] + nums[i + 1]) * 2 == nums[i]) { ++ans; } } return ans; } };
3,392
Count Subarrays of Length Three With a Condition
Easy
<p>Given an integer array <code>nums</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of length 3 such that the sum of the first and third numbers equals <em>exactly</em> half of the second number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Only the subarray <code>[1,4,1]</code> contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>[1,1,1]</code> is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 100</code></li> <li><code><font face="monospace">-100 &lt;= nums[i] &lt;= 100</font></code></li> </ul>
Array
Go
func countSubarrays(nums []int) (ans int) { for i := 1; i+1 < len(nums); i++ { if (nums[i-1]+nums[i+1])*2 == nums[i] { ans++ } } return }
3,392
Count Subarrays of Length Three With a Condition
Easy
<p>Given an integer array <code>nums</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of length 3 such that the sum of the first and third numbers equals <em>exactly</em> half of the second number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Only the subarray <code>[1,4,1]</code> contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>[1,1,1]</code> is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 100</code></li> <li><code><font face="monospace">-100 &lt;= nums[i] &lt;= 100</font></code></li> </ul>
Array
Java
class Solution { public int countSubarrays(int[] nums) { int ans = 0; for (int i = 1; i + 1 < nums.length; ++i) { if ((nums[i - 1] + nums[i + 1]) * 2 == nums[i]) { ++ans; } } return ans; } }
3,392
Count Subarrays of Length Three With a Condition
Easy
<p>Given an integer array <code>nums</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of length 3 such that the sum of the first and third numbers equals <em>exactly</em> half of the second number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Only the subarray <code>[1,4,1]</code> contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>[1,1,1]</code> is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 100</code></li> <li><code><font face="monospace">-100 &lt;= nums[i] &lt;= 100</font></code></li> </ul>
Array
Python
class Solution: def countSubarrays(self, nums: List[int]) -> int: return sum( (nums[i - 1] + nums[i + 1]) * 2 == nums[i] for i in range(1, len(nums) - 1) )
3,392
Count Subarrays of Length Three With a Condition
Easy
<p>Given an integer array <code>nums</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of length 3 such that the sum of the first and third numbers equals <em>exactly</em> half of the second number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Only the subarray <code>[1,4,1]</code> contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>[1,1,1]</code> is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 100</code></li> <li><code><font face="monospace">-100 &lt;= nums[i] &lt;= 100</font></code></li> </ul>
Array
Rust
impl Solution { pub fn count_subarrays(nums: Vec<i32>) -> i32 { let mut ans = 0; for i in 1..nums.len() - 1 { if (nums[i - 1] + nums[i + 1]) * 2 == nums[i] { ans += 1; } } ans } }
3,392
Count Subarrays of Length Three With a Condition
Easy
<p>Given an integer array <code>nums</code>, return the number of <span data-keyword="subarray-nonempty">subarrays</span> of length 3 such that the sum of the first and third numbers equals <em>exactly</em> half of the second number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Only the subarray <code>[1,4,1]</code> contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p><code>[1,1,1]</code> is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 100</code></li> <li><code><font face="monospace">-100 &lt;= nums[i] &lt;= 100</font></code></li> </ul>
Array
TypeScript
function countSubarrays(nums: number[]): number { let ans: number = 0; for (let i = 1; i + 1 < nums.length; ++i) { if ((nums[i - 1] + nums[i + 1]) * 2 === nums[i]) { ++ans; } } return ans; }
3,394
Check if Grid can be Cut into Sections
Medium
<p>You are given an integer <code>n</code> representing the dimensions of an <code>n x n</code><!-- notionvc: fa9fe4ed-dff8-4410-8196-346f2d430795 --> grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates <code>rectangles</code>, where <code>rectangles[i]</code> is in the form <code>[start<sub>x</sub>, start<sub>y</sub>, end<sub>x</sub>, end<sub>y</sub>]</code>, representing a rectangle on the grid. Each rectangle is defined as follows:</p> <ul> <li><code>(start<sub>x</sub>, start<sub>y</sub>)</code>: The bottom-left corner of the rectangle.</li> <li><code>(end<sub>x</sub>, end<sub>y</sub>)</code>: The top-right corner of the rectangle.</li> </ul> <p><strong>Note </strong>that the rectangles do not overlap. Your task is to determine if it is possible to make <strong>either two horizontal or two vertical cuts</strong> on the grid such that:</p> <ul> <li>Each of the three resulting sections formed by the cuts contains <strong>at least</strong> one rectangle.</li> <li>Every rectangle belongs to <strong>exactly</strong> one section.</li> </ul> <p>Return <code>true</code> if such cuts can be made; 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">n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]</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/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tt1drawio.png" style="width: 285px; height: 280px;" /></p> <p>The grid is shown in the diagram. We can make horizontal cuts at <code>y = 2</code> and <code>y = 4</code>. Hence, 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">n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,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/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tc2drawio.png" style="width: 240px; height: 240px;" /></p> <p>We can make vertical cuts at <code>x = 2</code> and <code>x = 3</code>. Hence, output is true.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>We cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>3 &lt;= rectangles.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= rectangles[i][0] &lt; rectangles[i][2] &lt;= n</code></li> <li><code>0 &lt;= rectangles[i][1] &lt; rectangles[i][3] &lt;= n</code></li> <li>No two rectangles overlap.</li> </ul>
Array; Sorting
C++
class Solution { #define pii pair<int, int> bool countLineIntersections(vector<pii>& coordinates) { int lines = 0; int overlap = 0; for (int i = 0; i < coordinates.size(); ++i) { if (coordinates[i].second == 0) overlap--; else overlap++; if (overlap == 0) lines++; } return lines >= 3; } public: bool checkValidCuts(int n, vector<vector<int>>& rectangles) { vector<pii> y_cordinates, x_cordinates; for (auto& rectangle : rectangles) { y_cordinates.push_back(make_pair(rectangle[1], 1)); y_cordinates.push_back(make_pair(rectangle[3], 0)); x_cordinates.push_back(make_pair(rectangle[0], 1)); x_cordinates.push_back(make_pair(rectangle[2], 0)); } sort(y_cordinates.begin(), y_cordinates.end()); sort(x_cordinates.begin(), x_cordinates.end()); // Line-Sweep on x and y cordinates return (countLineIntersections(y_cordinates) or countLineIntersections(x_cordinates)); } };
3,394
Check if Grid can be Cut into Sections
Medium
<p>You are given an integer <code>n</code> representing the dimensions of an <code>n x n</code><!-- notionvc: fa9fe4ed-dff8-4410-8196-346f2d430795 --> grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates <code>rectangles</code>, where <code>rectangles[i]</code> is in the form <code>[start<sub>x</sub>, start<sub>y</sub>, end<sub>x</sub>, end<sub>y</sub>]</code>, representing a rectangle on the grid. Each rectangle is defined as follows:</p> <ul> <li><code>(start<sub>x</sub>, start<sub>y</sub>)</code>: The bottom-left corner of the rectangle.</li> <li><code>(end<sub>x</sub>, end<sub>y</sub>)</code>: The top-right corner of the rectangle.</li> </ul> <p><strong>Note </strong>that the rectangles do not overlap. Your task is to determine if it is possible to make <strong>either two horizontal or two vertical cuts</strong> on the grid such that:</p> <ul> <li>Each of the three resulting sections formed by the cuts contains <strong>at least</strong> one rectangle.</li> <li>Every rectangle belongs to <strong>exactly</strong> one section.</li> </ul> <p>Return <code>true</code> if such cuts can be made; 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">n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]</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/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tt1drawio.png" style="width: 285px; height: 280px;" /></p> <p>The grid is shown in the diagram. We can make horizontal cuts at <code>y = 2</code> and <code>y = 4</code>. Hence, 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">n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,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/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tc2drawio.png" style="width: 240px; height: 240px;" /></p> <p>We can make vertical cuts at <code>x = 2</code> and <code>x = 3</code>. Hence, output is true.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>We cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>3 &lt;= rectangles.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= rectangles[i][0] &lt; rectangles[i][2] &lt;= n</code></li> <li><code>0 &lt;= rectangles[i][1] &lt; rectangles[i][3] &lt;= n</code></li> <li>No two rectangles overlap.</li> </ul>
Array; Sorting
Go
type Pair struct { val int typ int // 1 = start, 0 = end } func countLineIntersections(coords []Pair) bool { lines := 0 overlap := 0 for _, p := range coords { if p.typ == 0 { overlap-- } else { overlap++ } if overlap == 0 { lines++ } } return lines >= 3 } func checkValidCuts(n int, rectangles [][]int) bool { var xCoords []Pair var yCoords []Pair for _, rect := range rectangles { x1, y1, x2, y2 := rect[0], rect[1], rect[2], rect[3] yCoords = append(yCoords, Pair{y1, 1}) // start yCoords = append(yCoords, Pair{y2, 0}) // end xCoords = append(xCoords, Pair{x1, 1}) xCoords = append(xCoords, Pair{x2, 0}) } sort.Slice(yCoords, func(i, j int) bool { if yCoords[i].val == yCoords[j].val { return yCoords[i].typ < yCoords[j].typ // end before start } return yCoords[i].val < yCoords[j].val }) sort.Slice(xCoords, func(i, j int) bool { if xCoords[i].val == xCoords[j].val { return xCoords[i].typ < xCoords[j].typ } return xCoords[i].val < xCoords[j].val }) return countLineIntersections(yCoords) || countLineIntersections(xCoords) }
3,394
Check if Grid can be Cut into Sections
Medium
<p>You are given an integer <code>n</code> representing the dimensions of an <code>n x n</code><!-- notionvc: fa9fe4ed-dff8-4410-8196-346f2d430795 --> grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates <code>rectangles</code>, where <code>rectangles[i]</code> is in the form <code>[start<sub>x</sub>, start<sub>y</sub>, end<sub>x</sub>, end<sub>y</sub>]</code>, representing a rectangle on the grid. Each rectangle is defined as follows:</p> <ul> <li><code>(start<sub>x</sub>, start<sub>y</sub>)</code>: The bottom-left corner of the rectangle.</li> <li><code>(end<sub>x</sub>, end<sub>y</sub>)</code>: The top-right corner of the rectangle.</li> </ul> <p><strong>Note </strong>that the rectangles do not overlap. Your task is to determine if it is possible to make <strong>either two horizontal or two vertical cuts</strong> on the grid such that:</p> <ul> <li>Each of the three resulting sections formed by the cuts contains <strong>at least</strong> one rectangle.</li> <li>Every rectangle belongs to <strong>exactly</strong> one section.</li> </ul> <p>Return <code>true</code> if such cuts can be made; 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">n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]</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/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tt1drawio.png" style="width: 285px; height: 280px;" /></p> <p>The grid is shown in the diagram. We can make horizontal cuts at <code>y = 2</code> and <code>y = 4</code>. Hence, 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">n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,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/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tc2drawio.png" style="width: 240px; height: 240px;" /></p> <p>We can make vertical cuts at <code>x = 2</code> and <code>x = 3</code>. Hence, output is true.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>We cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>3 &lt;= rectangles.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= rectangles[i][0] &lt; rectangles[i][2] &lt;= n</code></li> <li><code>0 &lt;= rectangles[i][1] &lt; rectangles[i][3] &lt;= n</code></li> <li>No two rectangles overlap.</li> </ul>
Array; Sorting
Java
class Solution { // Helper class to mimic C++ pair<int, int> static class Pair { int value; int type; Pair(int value, int type) { this.value = value; this.type = type; } } private boolean countLineIntersections(List<Pair> coordinates) { int lines = 0; int overlap = 0; for (Pair coord : coordinates) { if (coord.type == 0) { overlap--; } else { overlap++; } if (overlap == 0) { lines++; } } return lines >= 3; } public boolean checkValidCuts(int n, int[][] rectangles) { List<Pair> yCoordinates = new ArrayList<>(); List<Pair> xCoordinates = new ArrayList<>(); for (int[] rectangle : rectangles) { // rectangle = [x1, y1, x2, y2] yCoordinates.add(new Pair(rectangle[1], 1)); // y1, start yCoordinates.add(new Pair(rectangle[3], 0)); // y2, end xCoordinates.add(new Pair(rectangle[0], 1)); // x1, start xCoordinates.add(new Pair(rectangle[2], 0)); // x2, end } Comparator<Pair> comparator = (a, b) -> { if (a.value != b.value) return Integer.compare(a.value, b.value); return Integer.compare(a.type, b.type); // End (0) before Start (1) }; Collections.sort(yCoordinates, comparator); Collections.sort(xCoordinates, comparator); return countLineIntersections(yCoordinates) || countLineIntersections(xCoordinates); } }
3,394
Check if Grid can be Cut into Sections
Medium
<p>You are given an integer <code>n</code> representing the dimensions of an <code>n x n</code><!-- notionvc: fa9fe4ed-dff8-4410-8196-346f2d430795 --> grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates <code>rectangles</code>, where <code>rectangles[i]</code> is in the form <code>[start<sub>x</sub>, start<sub>y</sub>, end<sub>x</sub>, end<sub>y</sub>]</code>, representing a rectangle on the grid. Each rectangle is defined as follows:</p> <ul> <li><code>(start<sub>x</sub>, start<sub>y</sub>)</code>: The bottom-left corner of the rectangle.</li> <li><code>(end<sub>x</sub>, end<sub>y</sub>)</code>: The top-right corner of the rectangle.</li> </ul> <p><strong>Note </strong>that the rectangles do not overlap. Your task is to determine if it is possible to make <strong>either two horizontal or two vertical cuts</strong> on the grid such that:</p> <ul> <li>Each of the three resulting sections formed by the cuts contains <strong>at least</strong> one rectangle.</li> <li>Every rectangle belongs to <strong>exactly</strong> one section.</li> </ul> <p>Return <code>true</code> if such cuts can be made; 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">n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]</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/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tt1drawio.png" style="width: 285px; height: 280px;" /></p> <p>The grid is shown in the diagram. We can make horizontal cuts at <code>y = 2</code> and <code>y = 4</code>. Hence, 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">n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,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/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tc2drawio.png" style="width: 240px; height: 240px;" /></p> <p>We can make vertical cuts at <code>x = 2</code> and <code>x = 3</code>. Hence, output is true.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>We cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>3 &lt;= rectangles.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= rectangles[i][0] &lt; rectangles[i][2] &lt;= n</code></li> <li><code>0 &lt;= rectangles[i][1] &lt; rectangles[i][3] &lt;= n</code></li> <li>No two rectangles overlap.</li> </ul>
Array; Sorting
JavaScript
function checkValidCuts(n, rectangles) { const check = (arr, getVals) => { let [c, longest] = [3, 0]; for (const x of arr) { const [start, end] = getVals(x); if (start < longest) { longest = Math.max(longest, end); } else { longest = end; if (--c === 0) return true; } } return false; }; const sortByX = ([a], [b]) => a - b; const sortByY = ([, a], [, b]) => a - b; const getX = ([x1, , x2]) => [x1, x2]; const getY = ([, y1, , y2]) => [y1, y2]; return check(rectangles.toSorted(sortByX), getX) || check(rectangles.toSorted(sortByY), getY); }
3,394
Check if Grid can be Cut into Sections
Medium
<p>You are given an integer <code>n</code> representing the dimensions of an <code>n x n</code><!-- notionvc: fa9fe4ed-dff8-4410-8196-346f2d430795 --> grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates <code>rectangles</code>, where <code>rectangles[i]</code> is in the form <code>[start<sub>x</sub>, start<sub>y</sub>, end<sub>x</sub>, end<sub>y</sub>]</code>, representing a rectangle on the grid. Each rectangle is defined as follows:</p> <ul> <li><code>(start<sub>x</sub>, start<sub>y</sub>)</code>: The bottom-left corner of the rectangle.</li> <li><code>(end<sub>x</sub>, end<sub>y</sub>)</code>: The top-right corner of the rectangle.</li> </ul> <p><strong>Note </strong>that the rectangles do not overlap. Your task is to determine if it is possible to make <strong>either two horizontal or two vertical cuts</strong> on the grid such that:</p> <ul> <li>Each of the three resulting sections formed by the cuts contains <strong>at least</strong> one rectangle.</li> <li>Every rectangle belongs to <strong>exactly</strong> one section.</li> </ul> <p>Return <code>true</code> if such cuts can be made; 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">n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]</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/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tt1drawio.png" style="width: 285px; height: 280px;" /></p> <p>The grid is shown in the diagram. We can make horizontal cuts at <code>y = 2</code> and <code>y = 4</code>. Hence, 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">n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,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/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tc2drawio.png" style="width: 240px; height: 240px;" /></p> <p>We can make vertical cuts at <code>x = 2</code> and <code>x = 3</code>. Hence, output is true.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>We cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>3 &lt;= rectangles.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= rectangles[i][0] &lt; rectangles[i][2] &lt;= n</code></li> <li><code>0 &lt;= rectangles[i][1] &lt; rectangles[i][3] &lt;= n</code></li> <li>No two rectangles overlap.</li> </ul>
Array; Sorting
Python
class Solution: def countLineIntersections(self, coordinates: List[tuple[int, int]]) -> bool: lines = 0 overlap = 0 for value, marker in coordinates: if marker == 0: overlap -= 1 else: overlap += 1 if overlap == 0: lines += 1 return lines >= 3 def checkValidCuts(self, n: int, rectangles: List[List[int]]) -> bool: y_coordinates = [] x_coordinates = [] for rect in rectangles: x1, y1, x2, y2 = rect y_coordinates.append((y1, 1)) # start y_coordinates.append((y2, 0)) # end x_coordinates.append((x1, 1)) # start x_coordinates.append((x2, 0)) # end # Sort by coordinate value, and for tie, put end (0) before start (1) y_coordinates.sort(key=lambda x: (x[0], x[1])) x_coordinates.sort(key=lambda x: (x[0], x[1])) return self.countLineIntersections( y_coordinates ) or self.countLineIntersections(x_coordinates)
3,394
Check if Grid can be Cut into Sections
Medium
<p>You are given an integer <code>n</code> representing the dimensions of an <code>n x n</code><!-- notionvc: fa9fe4ed-dff8-4410-8196-346f2d430795 --> grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates <code>rectangles</code>, where <code>rectangles[i]</code> is in the form <code>[start<sub>x</sub>, start<sub>y</sub>, end<sub>x</sub>, end<sub>y</sub>]</code>, representing a rectangle on the grid. Each rectangle is defined as follows:</p> <ul> <li><code>(start<sub>x</sub>, start<sub>y</sub>)</code>: The bottom-left corner of the rectangle.</li> <li><code>(end<sub>x</sub>, end<sub>y</sub>)</code>: The top-right corner of the rectangle.</li> </ul> <p><strong>Note </strong>that the rectangles do not overlap. Your task is to determine if it is possible to make <strong>either two horizontal or two vertical cuts</strong> on the grid such that:</p> <ul> <li>Each of the three resulting sections formed by the cuts contains <strong>at least</strong> one rectangle.</li> <li>Every rectangle belongs to <strong>exactly</strong> one section.</li> </ul> <p>Return <code>true</code> if such cuts can be made; 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">n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]</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/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tt1drawio.png" style="width: 285px; height: 280px;" /></p> <p>The grid is shown in the diagram. We can make horizontal cuts at <code>y = 2</code> and <code>y = 4</code>. Hence, 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">n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,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/3300-3399/3394.Check%20if%20Grid%20can%20be%20Cut%20into%20Sections/images/tc2drawio.png" style="width: 240px; height: 240px;" /></p> <p>We can make vertical cuts at <code>x = 2</code> and <code>x = 3</code>. Hence, output is true.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>We cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>3 &lt;= rectangles.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= rectangles[i][0] &lt; rectangles[i][2] &lt;= n</code></li> <li><code>0 &lt;= rectangles[i][1] &lt; rectangles[i][3] &lt;= n</code></li> <li>No two rectangles overlap.</li> </ul>
Array; Sorting
TypeScript
function checkValidCuts(n: number, rectangles: number[][]): boolean { const check = (arr: number[][], getVals: (x: number[]) => number[]) => { let [c, longest] = [3, 0]; for (const x of arr) { const [start, end] = getVals(x); if (start < longest) { longest = Math.max(longest, end); } else { longest = end; if (--c === 0) return true; } } return false; }; const sortByX = ([a]: number[], [b]: number[]) => a - b; const sortByY = ([, a]: number[], [, b]: number[]) => a - b; const getX = ([x1, , x2]: number[]) => [x1, x2]; const getY = ([, y1, , y2]: number[]) => [y1, y2]; return check(rectangles.toSorted(sortByX), getX) || check(rectangles.toSorted(sortByY), getY); }
3,396
Minimum Number of Operations to Make Elements in Array Distinct
Easy
<p>You are given an integer array <code>nums</code>. You need to ensure that the elements in the array are <strong>distinct</strong>. To achieve this, you can perform the following operation any number of times:</p> <ul> <li>Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, remove all remaining elements.</li> </ul> <p><strong>Note</strong> that an empty array is considered to have distinct elements. Return the <strong>minimum</strong> number of operations needed to make the elements in the array distinct.<!-- notionvc: 210ee4f2-90af-4cdf-8dbc-96d1fa8f67c7 --></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,2,3,3,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 2, 3, 3, 5, 7]</code>.</li> <li>In the second operation, the next 3 elements are removed, resulting in the array <code>[3, 5, 7]</code>, which has distinct elements.</li> </ul> <p>Therefore, the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,4,4]</span></p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong></p> <ul> <li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 4]</code>.</li> <li>In the second operation, all remaining elements are removed, resulting in an empty array.</li> </ul> <p>Therefore, the answer is 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [6,7,8,9]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array already contains distinct elements. Therefore, the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Hash Table
C++
class Solution { public: int minimumOperations(vector<int>& nums) { unordered_set<int> s; for (int i = nums.size() - 1; ~i; --i) { if (s.contains(nums[i])) { return i / 3 + 1; } s.insert(nums[i]); } return 0; } };
3,396
Minimum Number of Operations to Make Elements in Array Distinct
Easy
<p>You are given an integer array <code>nums</code>. You need to ensure that the elements in the array are <strong>distinct</strong>. To achieve this, you can perform the following operation any number of times:</p> <ul> <li>Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, remove all remaining elements.</li> </ul> <p><strong>Note</strong> that an empty array is considered to have distinct elements. Return the <strong>minimum</strong> number of operations needed to make the elements in the array distinct.<!-- notionvc: 210ee4f2-90af-4cdf-8dbc-96d1fa8f67c7 --></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,2,3,3,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 2, 3, 3, 5, 7]</code>.</li> <li>In the second operation, the next 3 elements are removed, resulting in the array <code>[3, 5, 7]</code>, which has distinct elements.</li> </ul> <p>Therefore, the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,4,4]</span></p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong></p> <ul> <li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 4]</code>.</li> <li>In the second operation, all remaining elements are removed, resulting in an empty array.</li> </ul> <p>Therefore, the answer is 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [6,7,8,9]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array already contains distinct elements. Therefore, the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Hash Table
Go
func minimumOperations(nums []int) int { s := map[int]bool{} for i := len(nums) - 1; i >= 0; i-- { if s[nums[i]] { return i/3 + 1 } s[nums[i]] = true } return 0 }
3,396
Minimum Number of Operations to Make Elements in Array Distinct
Easy
<p>You are given an integer array <code>nums</code>. You need to ensure that the elements in the array are <strong>distinct</strong>. To achieve this, you can perform the following operation any number of times:</p> <ul> <li>Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, remove all remaining elements.</li> </ul> <p><strong>Note</strong> that an empty array is considered to have distinct elements. Return the <strong>minimum</strong> number of operations needed to make the elements in the array distinct.<!-- notionvc: 210ee4f2-90af-4cdf-8dbc-96d1fa8f67c7 --></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,2,3,3,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 2, 3, 3, 5, 7]</code>.</li> <li>In the second operation, the next 3 elements are removed, resulting in the array <code>[3, 5, 7]</code>, which has distinct elements.</li> </ul> <p>Therefore, the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,4,4]</span></p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong></p> <ul> <li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 4]</code>.</li> <li>In the second operation, all remaining elements are removed, resulting in an empty array.</li> </ul> <p>Therefore, the answer is 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [6,7,8,9]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array already contains distinct elements. Therefore, the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Hash Table
Java
class Solution { public int minimumOperations(int[] nums) { Set<Integer> s = new HashSet<>(); for (int i = nums.length - 1; i >= 0; --i) { if (!s.add(nums[i])) { return i / 3 + 1; } } return 0; } }
3,396
Minimum Number of Operations to Make Elements in Array Distinct
Easy
<p>You are given an integer array <code>nums</code>. You need to ensure that the elements in the array are <strong>distinct</strong>. To achieve this, you can perform the following operation any number of times:</p> <ul> <li>Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, remove all remaining elements.</li> </ul> <p><strong>Note</strong> that an empty array is considered to have distinct elements. Return the <strong>minimum</strong> number of operations needed to make the elements in the array distinct.<!-- notionvc: 210ee4f2-90af-4cdf-8dbc-96d1fa8f67c7 --></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,2,3,3,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 2, 3, 3, 5, 7]</code>.</li> <li>In the second operation, the next 3 elements are removed, resulting in the array <code>[3, 5, 7]</code>, which has distinct elements.</li> </ul> <p>Therefore, the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,4,4]</span></p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong></p> <ul> <li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 4]</code>.</li> <li>In the second operation, all remaining elements are removed, resulting in an empty array.</li> </ul> <p>Therefore, the answer is 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [6,7,8,9]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array already contains distinct elements. Therefore, the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Hash Table
Python
class Solution: def minimumOperations(self, nums: List[int]) -> int: s = set() for i in range(len(nums) - 1, -1, -1): if nums[i] in s: return i // 3 + 1 s.add(nums[i]) return 0
3,396
Minimum Number of Operations to Make Elements in Array Distinct
Easy
<p>You are given an integer array <code>nums</code>. You need to ensure that the elements in the array are <strong>distinct</strong>. To achieve this, you can perform the following operation any number of times:</p> <ul> <li>Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, remove all remaining elements.</li> </ul> <p><strong>Note</strong> that an empty array is considered to have distinct elements. Return the <strong>minimum</strong> number of operations needed to make the elements in the array distinct.<!-- notionvc: 210ee4f2-90af-4cdf-8dbc-96d1fa8f67c7 --></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,2,3,3,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 2, 3, 3, 5, 7]</code>.</li> <li>In the second operation, the next 3 elements are removed, resulting in the array <code>[3, 5, 7]</code>, which has distinct elements.</li> </ul> <p>Therefore, the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,4,4]</span></p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong></p> <ul> <li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 4]</code>.</li> <li>In the second operation, all remaining elements are removed, resulting in an empty array.</li> </ul> <p>Therefore, the answer is 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [6,7,8,9]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array already contains distinct elements. Therefore, the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Hash Table
Rust
use std::collections::HashSet; impl Solution { pub fn minimum_operations(nums: Vec<i32>) -> i32 { let mut s = HashSet::new(); for i in (0..nums.len()).rev() { if !s.insert(nums[i]) { return (i / 3) as i32 + 1; } } 0 } }
3,396
Minimum Number of Operations to Make Elements in Array Distinct
Easy
<p>You are given an integer array <code>nums</code>. You need to ensure that the elements in the array are <strong>distinct</strong>. To achieve this, you can perform the following operation any number of times:</p> <ul> <li>Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, remove all remaining elements.</li> </ul> <p><strong>Note</strong> that an empty array is considered to have distinct elements. Return the <strong>minimum</strong> number of operations needed to make the elements in the array distinct.<!-- notionvc: 210ee4f2-90af-4cdf-8dbc-96d1fa8f67c7 --></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,2,3,3,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 2, 3, 3, 5, 7]</code>.</li> <li>In the second operation, the next 3 elements are removed, resulting in the array <code>[3, 5, 7]</code>, which has distinct elements.</li> </ul> <p>Therefore, the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,5,6,4,4]</span></p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong></p> <ul> <li>In the first operation, the first 3 elements are removed, resulting in the array <code>[4, 4]</code>.</li> <li>In the second operation, all remaining elements are removed, resulting in an empty array.</li> </ul> <p>Therefore, the answer is 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [6,7,8,9]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array already contains distinct elements. Therefore, the answer is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Hash Table
TypeScript
function minimumOperations(nums: number[]): number { const s = new Set<number>(); for (let i = nums.length - 1; ~i; --i) { if (s.has(nums[i])) { return Math.ceil((i + 1) / 3); } s.add(nums[i]); } return 0; }
3,397
Maximum Number of Distinct Elements After Operations
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>You are allowed to perform the following <strong>operation</strong> on each element of the array <strong>at most</strong> <em>once</em>:</p> <ul> <li>Add an integer in the range <code>[-k, k]</code> to the element.</li> </ul> <p>Return the <strong>maximum</strong> possible number of <strong>distinct</strong> elements in <code>nums</code> after performing the <strong>operations</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,3,3,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><code>nums</code> changes to <code>[-1, 0, 1, 2, 3, 4]</code> after performing operations on the first four elements.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,4,4,4], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>By adding -1 to <code>nums[0]</code> and 1 to <code>nums[1]</code>, <code>nums</code> changes to <code>[3, 5, 4, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: int maxDistinctElements(vector<int>& nums, int k) { ranges::sort(nums); int ans = 0, pre = INT_MIN; for (int x : nums) { int cur = min(x + k, max(x - k, pre + 1)); if (cur > pre) { ++ans; pre = cur; } } return ans; } };
3,397
Maximum Number of Distinct Elements After Operations
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>You are allowed to perform the following <strong>operation</strong> on each element of the array <strong>at most</strong> <em>once</em>:</p> <ul> <li>Add an integer in the range <code>[-k, k]</code> to the element.</li> </ul> <p>Return the <strong>maximum</strong> possible number of <strong>distinct</strong> elements in <code>nums</code> after performing the <strong>operations</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,3,3,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><code>nums</code> changes to <code>[-1, 0, 1, 2, 3, 4]</code> after performing operations on the first four elements.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,4,4,4], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>By adding -1 to <code>nums[0]</code> and 1 to <code>nums[1]</code>, <code>nums</code> changes to <code>[3, 5, 4, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
Go
func maxDistinctElements(nums []int, k int) (ans int) { sort.Ints(nums) pre := math.MinInt32 for _, x := range nums { cur := min(x+k, max(x-k, pre+1)) if cur > pre { ans++ pre = cur } } return }
3,397
Maximum Number of Distinct Elements After Operations
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>You are allowed to perform the following <strong>operation</strong> on each element of the array <strong>at most</strong> <em>once</em>:</p> <ul> <li>Add an integer in the range <code>[-k, k]</code> to the element.</li> </ul> <p>Return the <strong>maximum</strong> possible number of <strong>distinct</strong> elements in <code>nums</code> after performing the <strong>operations</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,3,3,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><code>nums</code> changes to <code>[-1, 0, 1, 2, 3, 4]</code> after performing operations on the first four elements.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,4,4,4], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>By adding -1 to <code>nums[0]</code> and 1 to <code>nums[1]</code>, <code>nums</code> changes to <code>[3, 5, 4, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
Java
class Solution { public int maxDistinctElements(int[] nums, int k) { Arrays.sort(nums); int n = nums.length; int ans = 0, pre = Integer.MIN_VALUE; for (int x : nums) { int cur = Math.min(x + k, Math.max(x - k, pre + 1)); if (cur > pre) { ++ans; pre = cur; } } return ans; } }
3,397
Maximum Number of Distinct Elements After Operations
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>You are allowed to perform the following <strong>operation</strong> on each element of the array <strong>at most</strong> <em>once</em>:</p> <ul> <li>Add an integer in the range <code>[-k, k]</code> to the element.</li> </ul> <p>Return the <strong>maximum</strong> possible number of <strong>distinct</strong> elements in <code>nums</code> after performing the <strong>operations</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,3,3,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><code>nums</code> changes to <code>[-1, 0, 1, 2, 3, 4]</code> after performing operations on the first four elements.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,4,4,4], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>By adding -1 to <code>nums[0]</code> and 1 to <code>nums[1]</code>, <code>nums</code> changes to <code>[3, 5, 4, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
Python
class Solution: def maxDistinctElements(self, nums: List[int], k: int) -> int: nums.sort() ans = 0 pre = -inf for x in nums: cur = min(x + k, max(x - k, pre + 1)) if cur > pre: ans += 1 pre = cur return ans
3,397
Maximum Number of Distinct Elements After Operations
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>You are allowed to perform the following <strong>operation</strong> on each element of the array <strong>at most</strong> <em>once</em>:</p> <ul> <li>Add an integer in the range <code>[-k, k]</code> to the element.</li> </ul> <p>Return the <strong>maximum</strong> possible number of <strong>distinct</strong> elements in <code>nums</code> after performing the <strong>operations</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,2,3,3,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p><code>nums</code> changes to <code>[-1, 0, 1, 2, 3, 4]</code> after performing operations on the first four elements.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,4,4,4], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>By adding -1 to <code>nums[0]</code> and 1 to <code>nums[1]</code>, <code>nums</code> changes to <code>[3, 5, 4, 4]</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
TypeScript
function maxDistinctElements(nums: number[], k: number): number { nums.sort((a, b) => a - b); let [ans, pre] = [0, -Infinity]; for (const x of nums) { const cur = Math.min(x + k, Math.max(x - k, pre + 1)); if (cur > pre) { ++ans; pre = cur; } } return ans; }
3,398
Smallest Substring With Identical Characters I
Hard
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p> <p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p> <ul> <li>Select any index <code>i</code> (where <code>0 &lt;= i &lt; n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == &#39;1&#39;</code>, change <code>s[i]</code> to <code>&#39;0&#39;</code> and vice versa.</li> </ul> <p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p> <p>Return the <strong>minimum</strong> length after the operations.</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;000001&quot;, numOps = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;001001&quot;</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0000&quot;, numOps = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;1010&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0101&quot;, numOps = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 1000</code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= numOps &lt;= n</code></li> </ul>
Array; Binary Search; Enumeration
C++
class Solution { public: int minLength(string s, int numOps) { int n = s.size(); auto check = [&](int m) { int cnt = 0; if (m == 1) { string t = "01"; for (int i = 0; i < n; ++i) { if (s[i] == t[i & 1]) { ++cnt; } } cnt = min(cnt, n - cnt); } else { int k = 0; for (int i = 0; i < n; ++i) { ++k; if (i == n - 1 || s[i] != s[i + 1]) { cnt += k / (m + 1); k = 0; } } } return cnt <= numOps; }; int l = 1, r = n; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } };
3,398
Smallest Substring With Identical Characters I
Hard
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p> <p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p> <ul> <li>Select any index <code>i</code> (where <code>0 &lt;= i &lt; n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == &#39;1&#39;</code>, change <code>s[i]</code> to <code>&#39;0&#39;</code> and vice versa.</li> </ul> <p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p> <p>Return the <strong>minimum</strong> length after the operations.</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;000001&quot;, numOps = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;001001&quot;</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0000&quot;, numOps = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;1010&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0101&quot;, numOps = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 1000</code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= numOps &lt;= n</code></li> </ul>
Array; Binary Search; Enumeration
Go
func minLength(s string, numOps int) int { check := func(m int) bool { m++ cnt := 0 if m == 1 { t := "01" for i := range s { if s[i] == t[i&1] { cnt++ } } cnt = min(cnt, len(s)-cnt) } else { k := 0 for i := range s { k++ if i == len(s)-1 || s[i] != s[i+1] { cnt += k / (m + 1) k = 0 } } } return cnt <= numOps } return 1 + sort.Search(len(s), func(m int) bool { return check(m) }) }
3,398
Smallest Substring With Identical Characters I
Hard
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p> <p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p> <ul> <li>Select any index <code>i</code> (where <code>0 &lt;= i &lt; n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == &#39;1&#39;</code>, change <code>s[i]</code> to <code>&#39;0&#39;</code> and vice versa.</li> </ul> <p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p> <p>Return the <strong>minimum</strong> length after the operations.</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;000001&quot;, numOps = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;001001&quot;</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0000&quot;, numOps = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;1010&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0101&quot;, numOps = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 1000</code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= numOps &lt;= n</code></li> </ul>
Array; Binary Search; Enumeration
Java
class Solution { private char[] s; private int numOps; public int minLength(String s, int numOps) { this.numOps = numOps; this.s = s.toCharArray(); int l = 1, r = s.length(); while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } private boolean check(int m) { int cnt = 0; if (m == 1) { char[] t = {'0', '1'}; for (int i = 0; i < s.length; ++i) { if (s[i] == t[i & 1]) { ++cnt; } } cnt = Math.min(cnt, s.length - cnt); } else { int k = 0; for (int i = 0; i < s.length; ++i) { ++k; if (i == s.length - 1 || s[i] != s[i + 1]) { cnt += k / (m + 1); k = 0; } } } return cnt <= numOps; } }
3,398
Smallest Substring With Identical Characters I
Hard
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p> <p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p> <ul> <li>Select any index <code>i</code> (where <code>0 &lt;= i &lt; n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == &#39;1&#39;</code>, change <code>s[i]</code> to <code>&#39;0&#39;</code> and vice versa.</li> </ul> <p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p> <p>Return the <strong>minimum</strong> length after the operations.</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;000001&quot;, numOps = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;001001&quot;</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0000&quot;, numOps = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;1010&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0101&quot;, numOps = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 1000</code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= numOps &lt;= n</code></li> </ul>
Array; Binary Search; Enumeration
Python
class Solution: def minLength(self, s: str, numOps: int) -> int: def check(m: int) -> bool: cnt = 0 if m == 1: t = "01" cnt = sum(c == t[i & 1] for i, c in enumerate(s)) cnt = min(cnt, n - cnt) else: k = 0 for i, c in enumerate(s): k += 1 if i == len(s) - 1 or c != s[i + 1]: cnt += k // (m + 1) k = 0 return cnt <= numOps n = len(s) return bisect_left(range(n), True, lo=1, key=check)
3,398
Smallest Substring With Identical Characters I
Hard
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p> <p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p> <ul> <li>Select any index <code>i</code> (where <code>0 &lt;= i &lt; n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == &#39;1&#39;</code>, change <code>s[i]</code> to <code>&#39;0&#39;</code> and vice versa.</li> </ul> <p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p> <p>Return the <strong>minimum</strong> length after the operations.</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;000001&quot;, numOps = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;001001&quot;</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0000&quot;, numOps = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;1010&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0101&quot;, numOps = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 1000</code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= numOps &lt;= n</code></li> </ul>
Array; Binary Search; Enumeration
TypeScript
function minLength(s: string, numOps: number): number { const n = s.length; const check = (m: number): boolean => { let cnt = 0; if (m === 1) { const t = '01'; for (let i = 0; i < n; ++i) { if (s[i] === t[i & 1]) { ++cnt; } } cnt = Math.min(cnt, n - cnt); } else { let k = 0; for (let i = 0; i < n; ++i) { ++k; if (i === n - 1 || s[i] !== s[i + 1]) { cnt += Math.floor(k / (m + 1)); k = 0; } } } return cnt <= numOps; }; let [l, r] = [1, n]; while (l < r) { const mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; }
3,399
Smallest Substring With Identical Characters II
Hard
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p> <p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p> <ul> <li>Select any index <code>i</code> (where <code>0 &lt;= i &lt; n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == &#39;1&#39;</code>, change <code>s[i]</code> to <code>&#39;0&#39;</code> and vice versa.</li> </ul> <p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p> <p>Return the <strong>minimum</strong> length after the operations.</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;000001&quot;, numOps = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;001001&quot;</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0000&quot;, numOps = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;1010&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0101&quot;, numOps = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= numOps &lt;= n</code></li> </ul>
String; Binary Search
C++
class Solution { public: int minLength(string s, int numOps) { int n = s.size(); auto check = [&](int m) { int cnt = 0; if (m == 1) { string t = "01"; for (int i = 0; i < n; ++i) { if (s[i] == t[i & 1]) { ++cnt; } } cnt = min(cnt, n - cnt); } else { int k = 0; for (int i = 0; i < n; ++i) { ++k; if (i == n - 1 || s[i] != s[i + 1]) { cnt += k / (m + 1); k = 0; } } } return cnt <= numOps; }; int l = 1, r = n; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } };
3,399
Smallest Substring With Identical Characters II
Hard
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p> <p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p> <ul> <li>Select any index <code>i</code> (where <code>0 &lt;= i &lt; n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == &#39;1&#39;</code>, change <code>s[i]</code> to <code>&#39;0&#39;</code> and vice versa.</li> </ul> <p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p> <p>Return the <strong>minimum</strong> length after the operations.</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;000001&quot;, numOps = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;001001&quot;</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0000&quot;, numOps = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;1010&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0101&quot;, numOps = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= numOps &lt;= n</code></li> </ul>
String; Binary Search
Go
func minLength(s string, numOps int) int { check := func(m int) bool { m++ cnt := 0 if m == 1 { t := "01" for i := range s { if s[i] == t[i&1] { cnt++ } } cnt = min(cnt, len(s)-cnt) } else { k := 0 for i := range s { k++ if i == len(s)-1 || s[i] != s[i+1] { cnt += k / (m + 1) k = 0 } } } return cnt <= numOps } return 1 + sort.Search(len(s), func(m int) bool { return check(m) }) }
3,399
Smallest Substring With Identical Characters II
Hard
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p> <p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p> <ul> <li>Select any index <code>i</code> (where <code>0 &lt;= i &lt; n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == &#39;1&#39;</code>, change <code>s[i]</code> to <code>&#39;0&#39;</code> and vice versa.</li> </ul> <p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p> <p>Return the <strong>minimum</strong> length after the operations.</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;000001&quot;, numOps = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;001001&quot;</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0000&quot;, numOps = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;1010&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0101&quot;, numOps = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= numOps &lt;= n</code></li> </ul>
String; Binary Search
Java
class Solution { private char[] s; private int numOps; public int minLength(String s, int numOps) { this.numOps = numOps; this.s = s.toCharArray(); int l = 1, r = s.length(); while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } private boolean check(int m) { int cnt = 0; if (m == 1) { char[] t = {'0', '1'}; for (int i = 0; i < s.length; ++i) { if (s[i] == t[i & 1]) { ++cnt; } } cnt = Math.min(cnt, s.length - cnt); } else { int k = 0; for (int i = 0; i < s.length; ++i) { ++k; if (i == s.length - 1 || s[i] != s[i + 1]) { cnt += k / (m + 1); k = 0; } } } return cnt <= numOps; } }
3,399
Smallest Substring With Identical Characters II
Hard
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p> <p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p> <ul> <li>Select any index <code>i</code> (where <code>0 &lt;= i &lt; n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == &#39;1&#39;</code>, change <code>s[i]</code> to <code>&#39;0&#39;</code> and vice versa.</li> </ul> <p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p> <p>Return the <strong>minimum</strong> length after the operations.</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;000001&quot;, numOps = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;001001&quot;</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0000&quot;, numOps = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;1010&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0101&quot;, numOps = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= numOps &lt;= n</code></li> </ul>
String; Binary Search
Python
class Solution: def minLength(self, s: str, numOps: int) -> int: def check(m: int) -> bool: cnt = 0 if m == 1: t = "01" cnt = sum(c == t[i & 1] for i, c in enumerate(s)) cnt = min(cnt, n - cnt) else: k = 0 for i, c in enumerate(s): k += 1 if i == len(s) - 1 or c != s[i + 1]: cnt += k // (m + 1) k = 0 return cnt <= numOps n = len(s) return bisect_left(range(n), True, lo=1, key=check)
3,399
Smallest Substring With Identical Characters II
Hard
<p>You are given a binary string <code>s</code> of length <code>n</code> and an integer <code>numOps</code>.</p> <p>You are allowed to perform the following operation on <code>s</code> <strong>at most</strong> <code>numOps</code> times:</p> <ul> <li>Select any index <code>i</code> (where <code>0 &lt;= i &lt; n</code>) and <strong>flip</strong> <code>s[i]</code>. If <code>s[i] == &#39;1&#39;</code>, change <code>s[i]</code> to <code>&#39;0&#39;</code> and vice versa.</li> </ul> <p>You need to <strong>minimize</strong> the length of the <strong>longest</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code> such that all the characters in the substring are <strong>identical</strong>.</p> <p>Return the <strong>minimum</strong> length after the operations.</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;000001&quot;, numOps = 1</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;001001&quot;</code>. The longest substrings with identical characters are <code>s[0..1]</code> and <code>s[3..4]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0000&quot;, numOps = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>By changing <code>s[0]</code> and <code>s[2]</code> to <code>&#39;1&#39;</code>, <code>s</code> becomes <code>&quot;1010&quot;</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0101&quot;, numOps = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li> <li><code>0 &lt;= numOps &lt;= n</code></li> </ul>
String; Binary Search
TypeScript
function minLength(s: string, numOps: number): number { const n = s.length; const check = (m: number): boolean => { let cnt = 0; if (m === 1) { const t = '01'; for (let i = 0; i < n; ++i) { if (s[i] === t[i & 1]) { ++cnt; } } cnt = Math.min(cnt, n - cnt); } else { let k = 0; for (let i = 0; i < n; ++i) { ++k; if (i === n - 1 || s[i] !== s[i + 1]) { cnt += Math.floor(k / (m + 1)); k = 0; } } } return cnt <= numOps; }; let [l, r] = [1, n]; while (l < r) { const mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; }
3,400
Maximum Number of Matching Indices After Right Shifts
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, of the same length.</p> <p>An index <code>i</code> is considered <strong>matching</strong> if <code>nums1[i] == nums2[i]</code>.</p> <p>Return the <strong>maximum</strong> number of <strong>matching</strong> indices after performing any number of <strong>right shifts</strong> on <code>nums1</code>.</p> <p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [3,1,2,3,1,2], nums2 = [1,2,3,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>If we right shift <code>nums1</code> 2 times, it becomes <code>[1, 2, 3, 1, 2, 3]</code>. Every index matches, so the output is 6.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [1,4,2,5,3,1], nums2 = [2,3,1,2,4,6]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>If we right shift <code>nums1</code> 3 times, it becomes <code>[5, 3, 1, 1, 4, 2]</code>. Indices 1, 2, and 4 match, so the output is 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == nums2.length</code></li> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 3000</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Simulation
C++
class Solution { public: int maximumMatchingIndices(vector<int>& nums1, vector<int>& nums2) { int n = nums1.size(); int ans = 0; for (int k = 0; k < n; ++k) { int t = 0; for (int i = 0; i < n; ++i) { if (nums1[(i + k) % n] == nums2[i]) { ++t; } } ans = max(ans, t); } return ans; } };
3,400
Maximum Number of Matching Indices After Right Shifts
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, of the same length.</p> <p>An index <code>i</code> is considered <strong>matching</strong> if <code>nums1[i] == nums2[i]</code>.</p> <p>Return the <strong>maximum</strong> number of <strong>matching</strong> indices after performing any number of <strong>right shifts</strong> on <code>nums1</code>.</p> <p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [3,1,2,3,1,2], nums2 = [1,2,3,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>If we right shift <code>nums1</code> 2 times, it becomes <code>[1, 2, 3, 1, 2, 3]</code>. Every index matches, so the output is 6.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [1,4,2,5,3,1], nums2 = [2,3,1,2,4,6]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>If we right shift <code>nums1</code> 3 times, it becomes <code>[5, 3, 1, 1, 4, 2]</code>. Indices 1, 2, and 4 match, so the output is 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == nums2.length</code></li> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 3000</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Simulation
Go
func maximumMatchingIndices(nums1 []int, nums2 []int) (ans int) { n := len(nums1) for k := range nums1 { t := 0 for i, x := range nums2 { if nums1[(i+k)%n] == x { t++ } } ans = max(ans, t) } return }
3,400
Maximum Number of Matching Indices After Right Shifts
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, of the same length.</p> <p>An index <code>i</code> is considered <strong>matching</strong> if <code>nums1[i] == nums2[i]</code>.</p> <p>Return the <strong>maximum</strong> number of <strong>matching</strong> indices after performing any number of <strong>right shifts</strong> on <code>nums1</code>.</p> <p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [3,1,2,3,1,2], nums2 = [1,2,3,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>If we right shift <code>nums1</code> 2 times, it becomes <code>[1, 2, 3, 1, 2, 3]</code>. Every index matches, so the output is 6.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [1,4,2,5,3,1], nums2 = [2,3,1,2,4,6]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>If we right shift <code>nums1</code> 3 times, it becomes <code>[5, 3, 1, 1, 4, 2]</code>. Indices 1, 2, and 4 match, so the output is 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == nums2.length</code></li> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 3000</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Simulation
Java
class Solution { public int maximumMatchingIndices(int[] nums1, int[] nums2) { int n = nums1.length; int ans = 0; for (int k = 0; k < n; ++k) { int t = 0; for (int i = 0; i < n; ++i) { if (nums1[(i + k) % n] == nums2[i]) { ++t; } } ans = Math.max(ans, t); } return ans; } }
3,400
Maximum Number of Matching Indices After Right Shifts
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, of the same length.</p> <p>An index <code>i</code> is considered <strong>matching</strong> if <code>nums1[i] == nums2[i]</code>.</p> <p>Return the <strong>maximum</strong> number of <strong>matching</strong> indices after performing any number of <strong>right shifts</strong> on <code>nums1</code>.</p> <p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [3,1,2,3,1,2], nums2 = [1,2,3,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>If we right shift <code>nums1</code> 2 times, it becomes <code>[1, 2, 3, 1, 2, 3]</code>. Every index matches, so the output is 6.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [1,4,2,5,3,1], nums2 = [2,3,1,2,4,6]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>If we right shift <code>nums1</code> 3 times, it becomes <code>[5, 3, 1, 1, 4, 2]</code>. Indices 1, 2, and 4 match, so the output is 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == nums2.length</code></li> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 3000</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Simulation
Python
class Solution: def maximumMatchingIndices(self, nums1: List[int], nums2: List[int]) -> int: n = len(nums1) ans = 0 for k in range(n): t = sum(nums1[(i + k) % n] == x for i, x in enumerate(nums2)) ans = max(ans, t) return ans
3,400
Maximum Number of Matching Indices After Right Shifts
Medium
<p>You are given two integer arrays, <code>nums1</code> and <code>nums2</code>, of the same length.</p> <p>An index <code>i</code> is considered <strong>matching</strong> if <code>nums1[i] == nums2[i]</code>.</p> <p>Return the <strong>maximum</strong> number of <strong>matching</strong> indices after performing any number of <strong>right shifts</strong> on <code>nums1</code>.</p> <p>A <strong>right shift</strong> is defined as shifting the element at index <code>i</code> to index <code>(i + 1) % n</code>, for all indices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [3,1,2,3,1,2], nums2 = [1,2,3,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>If we right shift <code>nums1</code> 2 times, it becomes <code>[1, 2, 3, 1, 2, 3]</code>. Every index matches, so the output is 6.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [1,4,2,5,3,1], nums2 = [2,3,1,2,4,6]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>If we right shift <code>nums1</code> 3 times, it becomes <code>[5, 3, 1, 1, 4, 2]</code>. Indices 1, 2, and 4 match, so the output is 3.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>nums1.length == nums2.length</code></li> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 3000</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Simulation
TypeScript
function maximumMatchingIndices(nums1: number[], nums2: number[]): number { const n = nums1.length; let ans: number = 0; for (let k = 0; k < n; ++k) { let t: number = 0; for (let i = 0; i < n; ++i) { if (nums1[(i + k) % n] === nums2[i]) { ++t; } } ans = Math.max(ans, t); } return ans; }
3,402
Minimum Operations to Make Columns Strictly Increasing
Easy
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers.</p> <p>In one operation, you can increment the value of any <code>grid[i][j]</code> by 1.</p> <p>Return the <strong>minimum</strong> number of operations needed to make all columns of <code>grid</code> <strong>strictly increasing</strong>.</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 = [[3,2],[1,3],[3,4],[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 3 operations on <code>grid[1][0]</code>, 2 operations on <code>grid[2][0]</code>, and 6 operations on <code>grid[3][0]</code>.</li> <li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 4 operations on <code>grid[3][1]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/firstexample.png" style="width: 200px; height: 347px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,2,1],[2,1,0],[1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][0]</code>, and 4 operations on <code>grid[2][0]</code>.</li> <li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][1]</code>, and 2 operations on <code>grid[2][1]</code>.</li> <li>To make the <code>2<sup>nd</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][2]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/secondexample.png" style="width: 300px; height: 257px;" /></div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 50</code></li> <li><code>0 &lt;= grid[i][j] &lt; 2500</code></li> </ul> <p>&nbsp;</p> <div class="spoiler"> <div> <pre> &nbsp;</pre> </div> </div>
Greedy; Array; Matrix
C++
class Solution { public: int minimumOperations(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); int ans = 0; for (int j = 0; j < n; ++j) { int pre = -1; for (int i = 0; i < m; ++i) { int cur = grid[i][j]; if (pre < cur) { pre = cur; } else { ++pre; ans += pre - cur; } } } return ans; } };
3,402
Minimum Operations to Make Columns Strictly Increasing
Easy
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers.</p> <p>In one operation, you can increment the value of any <code>grid[i][j]</code> by 1.</p> <p>Return the <strong>minimum</strong> number of operations needed to make all columns of <code>grid</code> <strong>strictly increasing</strong>.</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 = [[3,2],[1,3],[3,4],[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 3 operations on <code>grid[1][0]</code>, 2 operations on <code>grid[2][0]</code>, and 6 operations on <code>grid[3][0]</code>.</li> <li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 4 operations on <code>grid[3][1]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/firstexample.png" style="width: 200px; height: 347px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,2,1],[2,1,0],[1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][0]</code>, and 4 operations on <code>grid[2][0]</code>.</li> <li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][1]</code>, and 2 operations on <code>grid[2][1]</code>.</li> <li>To make the <code>2<sup>nd</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][2]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/secondexample.png" style="width: 300px; height: 257px;" /></div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 50</code></li> <li><code>0 &lt;= grid[i][j] &lt; 2500</code></li> </ul> <p>&nbsp;</p> <div class="spoiler"> <div> <pre> &nbsp;</pre> </div> </div>
Greedy; Array; Matrix
Go
func minimumOperations(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) for j := 0; j < n; j++ { pre := -1 for i := 0; i < m; i++ { cur := grid[i][j] if pre < cur { pre = cur } else { pre++ ans += pre - cur } } } return }
3,402
Minimum Operations to Make Columns Strictly Increasing
Easy
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers.</p> <p>In one operation, you can increment the value of any <code>grid[i][j]</code> by 1.</p> <p>Return the <strong>minimum</strong> number of operations needed to make all columns of <code>grid</code> <strong>strictly increasing</strong>.</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 = [[3,2],[1,3],[3,4],[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 3 operations on <code>grid[1][0]</code>, 2 operations on <code>grid[2][0]</code>, and 6 operations on <code>grid[3][0]</code>.</li> <li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 4 operations on <code>grid[3][1]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/firstexample.png" style="width: 200px; height: 347px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,2,1],[2,1,0],[1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][0]</code>, and 4 operations on <code>grid[2][0]</code>.</li> <li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][1]</code>, and 2 operations on <code>grid[2][1]</code>.</li> <li>To make the <code>2<sup>nd</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][2]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/secondexample.png" style="width: 300px; height: 257px;" /></div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 50</code></li> <li><code>0 &lt;= grid[i][j] &lt; 2500</code></li> </ul> <p>&nbsp;</p> <div class="spoiler"> <div> <pre> &nbsp;</pre> </div> </div>
Greedy; Array; Matrix
Java
class Solution { public int minimumOperations(int[][] grid) { int m = grid.length, n = grid[0].length; int ans = 0; for (int j = 0; j < n; ++j) { int pre = -1; for (int i = 0; i < m; ++i) { int cur = grid[i][j]; if (pre < cur) { pre = cur; } else { ++pre; ans += pre - cur; } } } return ans; } }
3,402
Minimum Operations to Make Columns Strictly Increasing
Easy
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers.</p> <p>In one operation, you can increment the value of any <code>grid[i][j]</code> by 1.</p> <p>Return the <strong>minimum</strong> number of operations needed to make all columns of <code>grid</code> <strong>strictly increasing</strong>.</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 = [[3,2],[1,3],[3,4],[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 3 operations on <code>grid[1][0]</code>, 2 operations on <code>grid[2][0]</code>, and 6 operations on <code>grid[3][0]</code>.</li> <li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 4 operations on <code>grid[3][1]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/firstexample.png" style="width: 200px; height: 347px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,2,1],[2,1,0],[1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][0]</code>, and 4 operations on <code>grid[2][0]</code>.</li> <li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][1]</code>, and 2 operations on <code>grid[2][1]</code>.</li> <li>To make the <code>2<sup>nd</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][2]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/secondexample.png" style="width: 300px; height: 257px;" /></div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 50</code></li> <li><code>0 &lt;= grid[i][j] &lt; 2500</code></li> </ul> <p>&nbsp;</p> <div class="spoiler"> <div> <pre> &nbsp;</pre> </div> </div>
Greedy; Array; Matrix
Python
class Solution: def minimumOperations(self, grid: List[List[int]]) -> int: ans = 0 for col in zip(*grid): pre = -1 for cur in col: if pre < cur: pre = cur else: pre += 1 ans += pre - cur return ans
3,402
Minimum Operations to Make Columns Strictly Increasing
Easy
<p>You are given a <code>m x n</code> matrix <code>grid</code> consisting of <b>non-negative</b> integers.</p> <p>In one operation, you can increment the value of any <code>grid[i][j]</code> by 1.</p> <p>Return the <strong>minimum</strong> number of operations needed to make all columns of <code>grid</code> <strong>strictly increasing</strong>.</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 = [[3,2],[1,3],[3,4],[0,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <ul> <li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 3 operations on <code>grid[1][0]</code>, 2 operations on <code>grid[2][0]</code>, and 6 operations on <code>grid[3][0]</code>.</li> <li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 4 operations on <code>grid[3][1]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/firstexample.png" style="width: 200px; height: 347px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[3,2,1],[2,1,0],[1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>To make the <code>0<sup>th</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][0]</code>, and 4 operations on <code>grid[2][0]</code>.</li> <li>To make the <code>1<sup>st</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][1]</code>, and 2 operations on <code>grid[2][1]</code>.</li> <li>To make the <code>2<sup>nd</sup></code> column strictly increasing, we can apply 2 operations on <code>grid[1][2]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3402.Minimum%20Operations%20to%20Make%20Columns%20Strictly%20Increasing/images/secondexample.png" style="width: 300px; height: 257px;" /></div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 50</code></li> <li><code>0 &lt;= grid[i][j] &lt; 2500</code></li> </ul> <p>&nbsp;</p> <div class="spoiler"> <div> <pre> &nbsp;</pre> </div> </div>
Greedy; Array; Matrix
TypeScript
function minimumOperations(grid: number[][]): number { const [m, n] = [grid.length, grid[0].length]; let ans: number = 0; for (let j = 0; j < n; ++j) { let pre: number = -1; for (let i = 0; i < m; ++i) { const cur = grid[i][j]; if (pre < cur) { pre = cur; } else { ++pre; ans += pre - cur; } } } return ans; }
3,403
Find the Lexicographically Largest String From the Box I
Medium
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p> <p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p> <ul> <li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li> <li>All the split words are put into a box.</li> </ul> <p>Find the <span data-keyword="lexicographically-smaller-string">lexicographically largest</span> string from the box after all the rounds are finished.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;dbca&quot;, numFriends = 2</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;dbc&quot;</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>All possible splits are:</p> <ul> <li><code>&quot;d&quot;</code> and <code>&quot;bca&quot;</code>.</li> <li><code>&quot;db&quot;</code> and <code>&quot;ca&quot;</code>.</li> <li><code>&quot;dbc&quot;</code> and <code>&quot;a&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">word = &quot;gggg&quot;, numFriends = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;g&quot;</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>The only possible split is: <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, and <code>&quot;g&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 5&nbsp;* 10<sup>3</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= numFriends &lt;= word.length</code></li> </ul>
Two Pointers; String; Enumeration
C++
class Solution { public: string answerString(string word, int numFriends) { if (numFriends == 1) { return word; } int n = word.length(); string ans = ""; for (int i = 0; i < n; ++i) { string t = word.substr(i, min(n - i, n - (numFriends - 1))); if (ans < t) { ans = t; } } return ans; } };
3,403
Find the Lexicographically Largest String From the Box I
Medium
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p> <p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p> <ul> <li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li> <li>All the split words are put into a box.</li> </ul> <p>Find the <span data-keyword="lexicographically-smaller-string">lexicographically largest</span> string from the box after all the rounds are finished.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;dbca&quot;, numFriends = 2</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;dbc&quot;</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>All possible splits are:</p> <ul> <li><code>&quot;d&quot;</code> and <code>&quot;bca&quot;</code>.</li> <li><code>&quot;db&quot;</code> and <code>&quot;ca&quot;</code>.</li> <li><code>&quot;dbc&quot;</code> and <code>&quot;a&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">word = &quot;gggg&quot;, numFriends = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;g&quot;</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>The only possible split is: <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, and <code>&quot;g&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 5&nbsp;* 10<sup>3</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= numFriends &lt;= word.length</code></li> </ul>
Two Pointers; String; Enumeration
Go
func answerString(word string, numFriends int) (ans string) { if numFriends == 1 { return word } n := len(word) for i := 0; i < n; i++ { t := word[i:min(n, i+n-(numFriends-1))] ans = max(ans, t) } return }
3,403
Find the Lexicographically Largest String From the Box I
Medium
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p> <p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p> <ul> <li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li> <li>All the split words are put into a box.</li> </ul> <p>Find the <span data-keyword="lexicographically-smaller-string">lexicographically largest</span> string from the box after all the rounds are finished.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;dbca&quot;, numFriends = 2</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;dbc&quot;</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>All possible splits are:</p> <ul> <li><code>&quot;d&quot;</code> and <code>&quot;bca&quot;</code>.</li> <li><code>&quot;db&quot;</code> and <code>&quot;ca&quot;</code>.</li> <li><code>&quot;dbc&quot;</code> and <code>&quot;a&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">word = &quot;gggg&quot;, numFriends = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;g&quot;</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>The only possible split is: <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, and <code>&quot;g&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 5&nbsp;* 10<sup>3</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= numFriends &lt;= word.length</code></li> </ul>
Two Pointers; String; Enumeration
Java
class Solution { public String answerString(String word, int numFriends) { if (numFriends == 1) { return word; } int n = word.length(); String ans = ""; for (int i = 0; i < n; ++i) { String t = word.substring(i, Math.min(n, i + n - (numFriends - 1))); if (ans.compareTo(t) < 0) { ans = t; } } return ans; } }
3,403
Find the Lexicographically Largest String From the Box I
Medium
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p> <p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p> <ul> <li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li> <li>All the split words are put into a box.</li> </ul> <p>Find the <span data-keyword="lexicographically-smaller-string">lexicographically largest</span> string from the box after all the rounds are finished.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;dbca&quot;, numFriends = 2</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;dbc&quot;</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>All possible splits are:</p> <ul> <li><code>&quot;d&quot;</code> and <code>&quot;bca&quot;</code>.</li> <li><code>&quot;db&quot;</code> and <code>&quot;ca&quot;</code>.</li> <li><code>&quot;dbc&quot;</code> and <code>&quot;a&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">word = &quot;gggg&quot;, numFriends = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;g&quot;</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>The only possible split is: <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, and <code>&quot;g&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 5&nbsp;* 10<sup>3</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= numFriends &lt;= word.length</code></li> </ul>
Two Pointers; String; Enumeration
Python
class Solution: def answerString(self, word: str, numFriends: int) -> str: if numFriends == 1: return word n = len(word) return max(word[i : i + n - (numFriends - 1)] for i in range(n))
3,403
Find the Lexicographically Largest String From the Box I
Medium
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p> <p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p> <ul> <li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li> <li>All the split words are put into a box.</li> </ul> <p>Find the <span data-keyword="lexicographically-smaller-string">lexicographically largest</span> string from the box after all the rounds are finished.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;dbca&quot;, numFriends = 2</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;dbc&quot;</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>All possible splits are:</p> <ul> <li><code>&quot;d&quot;</code> and <code>&quot;bca&quot;</code>.</li> <li><code>&quot;db&quot;</code> and <code>&quot;ca&quot;</code>.</li> <li><code>&quot;dbc&quot;</code> and <code>&quot;a&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">word = &quot;gggg&quot;, numFriends = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;g&quot;</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>The only possible split is: <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, and <code>&quot;g&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 5&nbsp;* 10<sup>3</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= numFriends &lt;= word.length</code></li> </ul>
Two Pointers; String; Enumeration
TypeScript
function answerString(word: string, numFriends: number): string { if (numFriends === 1) { return word; } const n = word.length; let ans = ''; for (let i = 0; i < n; i++) { const t = word.slice(i, Math.min(n, i + n - (numFriends - 1))); ans = t > ans ? t : ans; } return ans; }
3,404
Count Special Subsequences
Medium
<p>You are given an array <code>nums</code> consisting of positive integers.</p> <p>A <strong>special subsequence</strong> is defined as a <span data-keyword="subsequence-array">subsequence</span> of length 4, represented by indices <code>(p, q, r, s)</code>, where <code>p &lt; q &lt; r &lt; s</code>. This subsequence <strong>must</strong> satisfy the following conditions:</p> <ul> <li><code>nums[p] * nums[r] == nums[q] * nums[s]</code></li> <li>There must be <em>at least</em> <strong>one</strong> element between each pair of indices. In other words, <code>q - p &gt; 1</code>, <code>r - q &gt; 1</code> and <code>s - r &gt; 1</code>.</li> </ul> <p>Return the <em>number</em> of different <strong>special</strong> <strong>subsequences</strong> in <code>nums</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,2,3,4,3,6,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>There is one special subsequence in <code>nums</code>.</p> <ul> <li><code>(p, q, r, s) = (0, 2, 4, 6)</code>: <ul> <li>This corresponds to elements <code>(1, 3, 3, 1)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[4] = 1 * 3 = 3</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 1 = 3</code></li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,3,4,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>There are three special subsequences in <code>nums</code>.</p> <ul> <li><code>(p, q, r, s) = (0, 2, 4, 6)</code>: <ul> <li>This corresponds to elements <code>(3, 3, 3, 3)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[4] = 3 * 3 = 9</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 3 = 9</code></li> </ul> </li> <li><code>(p, q, r, s) = (1, 3, 5, 7)</code>: <ul> <li>This corresponds to elements <code>(4, 4, 4, 4)</code>.</li> <li><code>nums[p] * nums[r] = nums[1] * nums[5] = 4 * 4 = 16</code></li> <li><code>nums[q] * nums[s] = nums[3] * nums[7] = 4 * 4 = 16</code></li> </ul> </li> <li><code>(p, q, r, s) = (0, 2, 5, 7)</code>: <ul> <li>This corresponds to elements <code>(3, 3, 4, 4)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[5] = 3 * 4 = 12</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[7] = 3 * 4 = 12</code></li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>7 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; Math; Enumeration
C++
class Solution { public: long long numberOfSubsequences(vector<int>& nums) { int n = nums.size(); unordered_map<int, int> cnt; for (int r = 4; r < n - 2; ++r) { int c = nums[r]; for (int s = r + 2; s < n; ++s) { int d = nums[s]; int g = gcd(c, d); cnt[((d / g) << 12) | (c / g)]++; } } long long ans = 0; for (int q = 2; q < n - 4; ++q) { int b = nums[q]; for (int p = 0; p < q - 1; ++p) { int a = nums[p]; int g = gcd(a, b); ans += cnt[((a / g) << 12) | (b / g)]; } int c = nums[q + 2]; for (int s = q + 4; s < n; ++s) { int d = nums[s]; int g = gcd(c, d); cnt[((d / g) << 12) | (c / g)]--; } } return ans; } };
3,404
Count Special Subsequences
Medium
<p>You are given an array <code>nums</code> consisting of positive integers.</p> <p>A <strong>special subsequence</strong> is defined as a <span data-keyword="subsequence-array">subsequence</span> of length 4, represented by indices <code>(p, q, r, s)</code>, where <code>p &lt; q &lt; r &lt; s</code>. This subsequence <strong>must</strong> satisfy the following conditions:</p> <ul> <li><code>nums[p] * nums[r] == nums[q] * nums[s]</code></li> <li>There must be <em>at least</em> <strong>one</strong> element between each pair of indices. In other words, <code>q - p &gt; 1</code>, <code>r - q &gt; 1</code> and <code>s - r &gt; 1</code>.</li> </ul> <p>Return the <em>number</em> of different <strong>special</strong> <strong>subsequences</strong> in <code>nums</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,2,3,4,3,6,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>There is one special subsequence in <code>nums</code>.</p> <ul> <li><code>(p, q, r, s) = (0, 2, 4, 6)</code>: <ul> <li>This corresponds to elements <code>(1, 3, 3, 1)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[4] = 1 * 3 = 3</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 1 = 3</code></li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,3,4,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>There are three special subsequences in <code>nums</code>.</p> <ul> <li><code>(p, q, r, s) = (0, 2, 4, 6)</code>: <ul> <li>This corresponds to elements <code>(3, 3, 3, 3)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[4] = 3 * 3 = 9</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 3 = 9</code></li> </ul> </li> <li><code>(p, q, r, s) = (1, 3, 5, 7)</code>: <ul> <li>This corresponds to elements <code>(4, 4, 4, 4)</code>.</li> <li><code>nums[p] * nums[r] = nums[1] * nums[5] = 4 * 4 = 16</code></li> <li><code>nums[q] * nums[s] = nums[3] * nums[7] = 4 * 4 = 16</code></li> </ul> </li> <li><code>(p, q, r, s) = (0, 2, 5, 7)</code>: <ul> <li>This corresponds to elements <code>(3, 3, 4, 4)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[5] = 3 * 4 = 12</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[7] = 3 * 4 = 12</code></li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>7 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; Math; Enumeration
Go
func numberOfSubsequences(nums []int) (ans int64) { n := len(nums) cnt := make(map[int]int) gcd := func(a, b int) int { for b != 0 { a, b = b, a%b } return a } for r := 4; r < n-2; r++ { c := nums[r] for s := r + 2; s < n; s++ { d := nums[s] g := gcd(c, d) key := ((d / g) << 12) | (c / g) cnt[key]++ } } for q := 2; q < n-4; q++ { b := nums[q] for p := 0; p < q-1; p++ { a := nums[p] g := gcd(a, b) key := ((a / g) << 12) | (b / g) ans += int64(cnt[key]) } c := nums[q+2] for s := q + 4; s < n; s++ { d := nums[s] g := gcd(c, d) key := ((d / g) << 12) | (c / g) cnt[key]-- } } return }
3,404
Count Special Subsequences
Medium
<p>You are given an array <code>nums</code> consisting of positive integers.</p> <p>A <strong>special subsequence</strong> is defined as a <span data-keyword="subsequence-array">subsequence</span> of length 4, represented by indices <code>(p, q, r, s)</code>, where <code>p &lt; q &lt; r &lt; s</code>. This subsequence <strong>must</strong> satisfy the following conditions:</p> <ul> <li><code>nums[p] * nums[r] == nums[q] * nums[s]</code></li> <li>There must be <em>at least</em> <strong>one</strong> element between each pair of indices. In other words, <code>q - p &gt; 1</code>, <code>r - q &gt; 1</code> and <code>s - r &gt; 1</code>.</li> </ul> <p>Return the <em>number</em> of different <strong>special</strong> <strong>subsequences</strong> in <code>nums</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,2,3,4,3,6,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>There is one special subsequence in <code>nums</code>.</p> <ul> <li><code>(p, q, r, s) = (0, 2, 4, 6)</code>: <ul> <li>This corresponds to elements <code>(1, 3, 3, 1)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[4] = 1 * 3 = 3</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 1 = 3</code></li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,3,4,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>There are three special subsequences in <code>nums</code>.</p> <ul> <li><code>(p, q, r, s) = (0, 2, 4, 6)</code>: <ul> <li>This corresponds to elements <code>(3, 3, 3, 3)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[4] = 3 * 3 = 9</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 3 = 9</code></li> </ul> </li> <li><code>(p, q, r, s) = (1, 3, 5, 7)</code>: <ul> <li>This corresponds to elements <code>(4, 4, 4, 4)</code>.</li> <li><code>nums[p] * nums[r] = nums[1] * nums[5] = 4 * 4 = 16</code></li> <li><code>nums[q] * nums[s] = nums[3] * nums[7] = 4 * 4 = 16</code></li> </ul> </li> <li><code>(p, q, r, s) = (0, 2, 5, 7)</code>: <ul> <li>This corresponds to elements <code>(3, 3, 4, 4)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[5] = 3 * 4 = 12</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[7] = 3 * 4 = 12</code></li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>7 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; Math; Enumeration
Java
class Solution { public long numberOfSubsequences(int[] nums) { int n = nums.length; Map<Integer, Integer> cnt = new HashMap<>(); for (int r = 4; r < n - 2; ++r) { int c = nums[r]; for (int s = r + 2; s < n; ++s) { int d = nums[s]; int g = gcd(c, d); cnt.merge(((d / g) << 12) | (c / g), 1, Integer::sum); } } long ans = 0; for (int q = 2; q < n - 4; ++q) { int b = nums[q]; for (int p = 0; p < q - 1; ++p) { int a = nums[p]; int g = gcd(a, b); ans += cnt.getOrDefault(((a / g) << 12) | (b / g), 0); } int c = nums[q + 2]; for (int s = q + 4; s < n; ++s) { int d = nums[s]; int g = gcd(c, d); cnt.merge(((d / g) << 12) | (c / g), -1, Integer::sum); } } return ans; } private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } }
3,404
Count Special Subsequences
Medium
<p>You are given an array <code>nums</code> consisting of positive integers.</p> <p>A <strong>special subsequence</strong> is defined as a <span data-keyword="subsequence-array">subsequence</span> of length 4, represented by indices <code>(p, q, r, s)</code>, where <code>p &lt; q &lt; r &lt; s</code>. This subsequence <strong>must</strong> satisfy the following conditions:</p> <ul> <li><code>nums[p] * nums[r] == nums[q] * nums[s]</code></li> <li>There must be <em>at least</em> <strong>one</strong> element between each pair of indices. In other words, <code>q - p &gt; 1</code>, <code>r - q &gt; 1</code> and <code>s - r &gt; 1</code>.</li> </ul> <p>Return the <em>number</em> of different <strong>special</strong> <strong>subsequences</strong> in <code>nums</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,2,3,4,3,6,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>There is one special subsequence in <code>nums</code>.</p> <ul> <li><code>(p, q, r, s) = (0, 2, 4, 6)</code>: <ul> <li>This corresponds to elements <code>(1, 3, 3, 1)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[4] = 1 * 3 = 3</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 1 = 3</code></li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,3,4,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>There are three special subsequences in <code>nums</code>.</p> <ul> <li><code>(p, q, r, s) = (0, 2, 4, 6)</code>: <ul> <li>This corresponds to elements <code>(3, 3, 3, 3)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[4] = 3 * 3 = 9</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 3 = 9</code></li> </ul> </li> <li><code>(p, q, r, s) = (1, 3, 5, 7)</code>: <ul> <li>This corresponds to elements <code>(4, 4, 4, 4)</code>.</li> <li><code>nums[p] * nums[r] = nums[1] * nums[5] = 4 * 4 = 16</code></li> <li><code>nums[q] * nums[s] = nums[3] * nums[7] = 4 * 4 = 16</code></li> </ul> </li> <li><code>(p, q, r, s) = (0, 2, 5, 7)</code>: <ul> <li>This corresponds to elements <code>(3, 3, 4, 4)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[5] = 3 * 4 = 12</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[7] = 3 * 4 = 12</code></li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>7 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; Math; Enumeration
Python
class Solution: def numberOfSubsequences(self, nums: List[int]) -> int: n = len(nums) cnt = defaultdict(int) for r in range(4, n - 2): c = nums[r] for s in range(r + 2, n): d = nums[s] g = gcd(c, d) cnt[(d // g, c // g)] += 1 ans = 0 for q in range(2, n - 4): b = nums[q] for p in range(q - 1): a = nums[p] g = gcd(a, b) ans += cnt[(a // g, b // g)] c = nums[q + 2] for s in range(q + 4, n): d = nums[s] g = gcd(c, d) cnt[(d // g, c // g)] -= 1 return ans
3,404
Count Special Subsequences
Medium
<p>You are given an array <code>nums</code> consisting of positive integers.</p> <p>A <strong>special subsequence</strong> is defined as a <span data-keyword="subsequence-array">subsequence</span> of length 4, represented by indices <code>(p, q, r, s)</code>, where <code>p &lt; q &lt; r &lt; s</code>. This subsequence <strong>must</strong> satisfy the following conditions:</p> <ul> <li><code>nums[p] * nums[r] == nums[q] * nums[s]</code></li> <li>There must be <em>at least</em> <strong>one</strong> element between each pair of indices. In other words, <code>q - p &gt; 1</code>, <code>r - q &gt; 1</code> and <code>s - r &gt; 1</code>.</li> </ul> <p>Return the <em>number</em> of different <strong>special</strong> <strong>subsequences</strong> in <code>nums</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,2,3,4,3,6,1]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>There is one special subsequence in <code>nums</code>.</p> <ul> <li><code>(p, q, r, s) = (0, 2, 4, 6)</code>: <ul> <li>This corresponds to elements <code>(1, 3, 3, 1)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[4] = 1 * 3 = 3</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 1 = 3</code></li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,4,3,4,3,4,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>There are three special subsequences in <code>nums</code>.</p> <ul> <li><code>(p, q, r, s) = (0, 2, 4, 6)</code>: <ul> <li>This corresponds to elements <code>(3, 3, 3, 3)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[4] = 3 * 3 = 9</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[6] = 3 * 3 = 9</code></li> </ul> </li> <li><code>(p, q, r, s) = (1, 3, 5, 7)</code>: <ul> <li>This corresponds to elements <code>(4, 4, 4, 4)</code>.</li> <li><code>nums[p] * nums[r] = nums[1] * nums[5] = 4 * 4 = 16</code></li> <li><code>nums[q] * nums[s] = nums[3] * nums[7] = 4 * 4 = 16</code></li> </ul> </li> <li><code>(p, q, r, s) = (0, 2, 5, 7)</code>: <ul> <li>This corresponds to elements <code>(3, 3, 4, 4)</code>.</li> <li><code>nums[p] * nums[r] = nums[0] * nums[5] = 3 * 4 = 12</code></li> <li><code>nums[q] * nums[s] = nums[2] * nums[7] = 3 * 4 = 12</code></li> </ul> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>7 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; Math; Enumeration
TypeScript
function numberOfSubsequences(nums: number[]): number { const n = nums.length; const cnt = new Map<number, number>(); function gcd(a: number, b: number): number { while (b !== 0) { [a, b] = [b, a % b]; } return a; } for (let r = 4; r < n - 2; r++) { const c = nums[r]; for (let s = r + 2; s < n; s++) { const d = nums[s]; const g = gcd(c, d); const key = ((d / g) << 12) | (c / g); cnt.set(key, (cnt.get(key) || 0) + 1); } } let ans = 0; for (let q = 2; q < n - 4; q++) { const b = nums[q]; for (let p = 0; p < q - 1; p++) { const a = nums[p]; const g = gcd(a, b); const key = ((a / g) << 12) | (b / g); ans += cnt.get(key) || 0; } const c = nums[q + 2]; for (let s = q + 4; s < n; s++) { const d = nums[s]; const g = gcd(c, d); const key = ((d / g) << 12) | (c / g); cnt.set(key, (cnt.get(key) || 0) - 1); } } return ans; }
3,405
Count the Number of Arrays with K Matching Adjacent Elements
Hard
<p>You are given three integers <code>n</code>, <code>m</code>, <code>k</code>. A <strong>good array</strong> <code>arr</code> of size <code>n</code> is defined as follows:</p> <ul> <li>Each element in <code>arr</code> is in the <strong>inclusive</strong> range <code>[1, m]</code>.</li> <li><em>Exactly</em> <code>k</code> indices <code>i</code> (where <code>1 &lt;= i &lt; n</code>) satisfy the condition <code>arr[i - 1] == arr[i]</code>.</li> </ul> <p>Return the number of <strong>good arrays</strong> that can be formed.</p> <p>Since the answer may be very large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, m = 2, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are 4 good arrays. They are <code>[1, 1, 2]</code>, <code>[1, 2, 2]</code>, <code>[2, 1, 1]</code> and <code>[2, 2, 1]</code>.</li> <li>Hence, the answer is 4.</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, m = 2, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The good arrays are <code>[1, 1, 1, 2]</code>, <code>[1, 1, 2, 2]</code>, <code>[1, 2, 2, 2]</code>, <code>[2, 1, 1, 1]</code>, <code>[2, 2, 1, 1]</code> and <code>[2, 2, 2, 1]</code>.</li> <li>Hence, the answer is 6.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, m = 2, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The good arrays are <code>[1, 2, 1, 2, 1]</code> and <code>[2, 1, 2, 1, 2]</code>. Hence, the answer is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= n - 1</code></li> </ul>
Math; Combinatorics
C++
const int MX = 1e5 + 10; const int MOD = 1e9 + 7; long long f[MX]; long long g[MX]; long long qpow(long a, int k) { long res = 1; while (k != 0) { if ((k & 1) == 1) { res = res * a % MOD; } k >>= 1; a = a * a % MOD; } return res; } int init = []() { f[0] = g[0] = 1; for (int i = 1; i < MX; ++i) { f[i] = f[i - 1] * i % MOD; g[i] = qpow(f[i], MOD - 2); } return 0; }(); long long comb(int m, int n) { return f[m] * g[n] % MOD * g[m - n] % MOD; } class Solution { public: int countGoodArrays(int n, int m, int k) { return comb(n - 1, k) * m % MOD * qpow(m - 1, n - k - 1) % MOD; } };
3,405
Count the Number of Arrays with K Matching Adjacent Elements
Hard
<p>You are given three integers <code>n</code>, <code>m</code>, <code>k</code>. A <strong>good array</strong> <code>arr</code> of size <code>n</code> is defined as follows:</p> <ul> <li>Each element in <code>arr</code> is in the <strong>inclusive</strong> range <code>[1, m]</code>.</li> <li><em>Exactly</em> <code>k</code> indices <code>i</code> (where <code>1 &lt;= i &lt; n</code>) satisfy the condition <code>arr[i - 1] == arr[i]</code>.</li> </ul> <p>Return the number of <strong>good arrays</strong> that can be formed.</p> <p>Since the answer may be very large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, m = 2, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are 4 good arrays. They are <code>[1, 1, 2]</code>, <code>[1, 2, 2]</code>, <code>[2, 1, 1]</code> and <code>[2, 2, 1]</code>.</li> <li>Hence, the answer is 4.</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, m = 2, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The good arrays are <code>[1, 1, 1, 2]</code>, <code>[1, 1, 2, 2]</code>, <code>[1, 2, 2, 2]</code>, <code>[2, 1, 1, 1]</code>, <code>[2, 2, 1, 1]</code> and <code>[2, 2, 2, 1]</code>.</li> <li>Hence, the answer is 6.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, m = 2, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The good arrays are <code>[1, 2, 1, 2, 1]</code> and <code>[2, 1, 2, 1, 2]</code>. Hence, the answer is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= n - 1</code></li> </ul>
Math; Combinatorics
Go
const MX = 1e5 + 10 const MOD = 1e9 + 7 var f [MX]int64 var g [MX]int64 func qpow(a int64, k int) int64 { res := int64(1) for k != 0 { if k&1 == 1 { res = res * a % MOD } a = a * a % MOD k >>= 1 } return res } func init() { f[0], g[0] = 1, 1 for i := 1; i < MX; i++ { f[i] = f[i-1] * int64(i) % MOD g[i] = qpow(f[i], MOD-2) } } func comb(m, n int) int64 { return f[m] * g[n] % MOD * g[m-n] % MOD } func countGoodArrays(n int, m int, k int) int { ans := comb(n-1, k) * int64(m) % MOD * qpow(int64(m-1), n-k-1) % MOD return int(ans) }
3,405
Count the Number of Arrays with K Matching Adjacent Elements
Hard
<p>You are given three integers <code>n</code>, <code>m</code>, <code>k</code>. A <strong>good array</strong> <code>arr</code> of size <code>n</code> is defined as follows:</p> <ul> <li>Each element in <code>arr</code> is in the <strong>inclusive</strong> range <code>[1, m]</code>.</li> <li><em>Exactly</em> <code>k</code> indices <code>i</code> (where <code>1 &lt;= i &lt; n</code>) satisfy the condition <code>arr[i - 1] == arr[i]</code>.</li> </ul> <p>Return the number of <strong>good arrays</strong> that can be formed.</p> <p>Since the answer may be very large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, m = 2, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are 4 good arrays. They are <code>[1, 1, 2]</code>, <code>[1, 2, 2]</code>, <code>[2, 1, 1]</code> and <code>[2, 2, 1]</code>.</li> <li>Hence, the answer is 4.</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, m = 2, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The good arrays are <code>[1, 1, 1, 2]</code>, <code>[1, 1, 2, 2]</code>, <code>[1, 2, 2, 2]</code>, <code>[2, 1, 1, 1]</code>, <code>[2, 2, 1, 1]</code> and <code>[2, 2, 2, 1]</code>.</li> <li>Hence, the answer is 6.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, m = 2, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The good arrays are <code>[1, 2, 1, 2, 1]</code> and <code>[2, 1, 2, 1, 2]</code>. Hence, the answer is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= n - 1</code></li> </ul>
Math; Combinatorics
Java
class Solution { private static final int N = (int) 1e5 + 10; private static final int MOD = (int) 1e9 + 7; private static final long[] f = new long[N]; private static final long[] g = new long[N]; static { f[0] = 1; g[0] = 1; for (int i = 1; i < N; ++i) { f[i] = f[i - 1] * i % MOD; g[i] = qpow(f[i], MOD - 2); } } public static long qpow(long a, int k) { long res = 1; while (k != 0) { if ((k & 1) == 1) { res = res * a % MOD; } k >>= 1; a = a * a % MOD; } return res; } public static long comb(int m, int n) { return (int) f[m] * g[n] % MOD * g[m - n] % MOD; } public int countGoodArrays(int n, int m, int k) { return (int) (comb(n - 1, k) * m % MOD * qpow(m - 1, n - k - 1) % MOD); } }
3,405
Count the Number of Arrays with K Matching Adjacent Elements
Hard
<p>You are given three integers <code>n</code>, <code>m</code>, <code>k</code>. A <strong>good array</strong> <code>arr</code> of size <code>n</code> is defined as follows:</p> <ul> <li>Each element in <code>arr</code> is in the <strong>inclusive</strong> range <code>[1, m]</code>.</li> <li><em>Exactly</em> <code>k</code> indices <code>i</code> (where <code>1 &lt;= i &lt; n</code>) satisfy the condition <code>arr[i - 1] == arr[i]</code>.</li> </ul> <p>Return the number of <strong>good arrays</strong> that can be formed.</p> <p>Since the answer may be very large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, m = 2, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are 4 good arrays. They are <code>[1, 1, 2]</code>, <code>[1, 2, 2]</code>, <code>[2, 1, 1]</code> and <code>[2, 2, 1]</code>.</li> <li>Hence, the answer is 4.</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, m = 2, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The good arrays are <code>[1, 1, 1, 2]</code>, <code>[1, 1, 2, 2]</code>, <code>[1, 2, 2, 2]</code>, <code>[2, 1, 1, 1]</code>, <code>[2, 2, 1, 1]</code> and <code>[2, 2, 2, 1]</code>.</li> <li>Hence, the answer is 6.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, m = 2, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The good arrays are <code>[1, 2, 1, 2, 1]</code> and <code>[2, 1, 2, 1, 2]</code>. Hence, the answer is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= n - 1</code></li> </ul>
Math; Combinatorics
Python
mx = 10**5 + 10 mod = 10**9 + 7 f = [1] + [0] * mx g = [1] + [0] * mx for i in range(1, mx): f[i] = f[i - 1] * i % mod g[i] = pow(f[i], mod - 2, mod) def comb(m: int, n: int) -> int: return f[m] * g[n] * g[m - n] % mod class Solution: def countGoodArrays(self, n: int, m: int, k: int) -> int: return comb(n - 1, k) * m * pow(m - 1, n - k - 1, mod) % mod
3,405
Count the Number of Arrays with K Matching Adjacent Elements
Hard
<p>You are given three integers <code>n</code>, <code>m</code>, <code>k</code>. A <strong>good array</strong> <code>arr</code> of size <code>n</code> is defined as follows:</p> <ul> <li>Each element in <code>arr</code> is in the <strong>inclusive</strong> range <code>[1, m]</code>.</li> <li><em>Exactly</em> <code>k</code> indices <code>i</code> (where <code>1 &lt;= i &lt; n</code>) satisfy the condition <code>arr[i - 1] == arr[i]</code>.</li> </ul> <p>Return the number of <strong>good arrays</strong> that can be formed.</p> <p>Since the answer may be very large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, m = 2, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are 4 good arrays. They are <code>[1, 1, 2]</code>, <code>[1, 2, 2]</code>, <code>[2, 1, 1]</code> and <code>[2, 2, 1]</code>.</li> <li>Hence, the answer is 4.</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, m = 2, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The good arrays are <code>[1, 1, 1, 2]</code>, <code>[1, 1, 2, 2]</code>, <code>[1, 2, 2, 2]</code>, <code>[2, 1, 1, 1]</code>, <code>[2, 2, 1, 1]</code> and <code>[2, 2, 2, 1]</code>.</li> <li>Hence, the answer is 6.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, m = 2, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The good arrays are <code>[1, 2, 1, 2, 1]</code> and <code>[2, 1, 2, 1, 2]</code>. Hence, the answer is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= n - 1</code></li> </ul>
Math; Combinatorics
Rust
impl Solution { pub fn count_good_arrays(n: i32, m: i32, k: i32) -> i32 { const N: usize = 1e5 as usize + 10; const MOD: i64 = 1_000_000_007; use std::sync::OnceLock; static F: OnceLock<Vec<i64>> = OnceLock::new(); static G: OnceLock<Vec<i64>> = OnceLock::new(); fn qpow(mut a: i64, mut k: i64, m: i64) -> i64 { let mut res = 1; while k != 0 { if k & 1 == 1 { res = res * a % m; } a = a * a % m; k >>= 1; } res } fn init() -> (&'static Vec<i64>, &'static Vec<i64>) { F.get_or_init(|| { let mut f = vec![1i64; N]; for i in 1..N { f[i] = f[i - 1] * i as i64 % MOD; } f }); G.get_or_init(|| { let f = F.get().unwrap(); let mut g = vec![1i64; N]; for i in 1..N { g[i] = qpow(f[i], MOD - 2, MOD); } g }); (F.get().unwrap(), G.get().unwrap()) } fn comb(f: &[i64], g: &[i64], m: usize, n: usize) -> i64 { f[m] * g[n] % MOD * g[m - n] % MOD } let (f, g) = init(); let n = n as usize; let m = m as i64; let k = k as usize; let c = comb(f, g, n - 1, k); let pow = qpow(m - 1, (n - 1 - k) as i64, MOD); (c * m % MOD * pow % MOD) as i32 } }
3,405
Count the Number of Arrays with K Matching Adjacent Elements
Hard
<p>You are given three integers <code>n</code>, <code>m</code>, <code>k</code>. A <strong>good array</strong> <code>arr</code> of size <code>n</code> is defined as follows:</p> <ul> <li>Each element in <code>arr</code> is in the <strong>inclusive</strong> range <code>[1, m]</code>.</li> <li><em>Exactly</em> <code>k</code> indices <code>i</code> (where <code>1 &lt;= i &lt; n</code>) satisfy the condition <code>arr[i - 1] == arr[i]</code>.</li> </ul> <p>Return the number of <strong>good arrays</strong> that can be formed.</p> <p>Since the answer may be very large, return it <strong>modulo </strong><code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, m = 2, k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>There are 4 good arrays. They are <code>[1, 1, 2]</code>, <code>[1, 2, 2]</code>, <code>[2, 1, 1]</code> and <code>[2, 2, 1]</code>.</li> <li>Hence, the answer is 4.</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, m = 2, k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The good arrays are <code>[1, 1, 1, 2]</code>, <code>[1, 1, 2, 2]</code>, <code>[1, 2, 2, 2]</code>, <code>[2, 1, 1, 1]</code>, <code>[2, 2, 1, 1]</code> and <code>[2, 2, 2, 1]</code>.</li> <li>Hence, the answer is 6.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, m = 2, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The good arrays are <code>[1, 2, 1, 2, 1]</code> and <code>[2, 1, 2, 1, 2]</code>. Hence, the answer is 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= k &lt;= n - 1</code></li> </ul>
Math; Combinatorics
TypeScript
const MX = 1e5 + 10; const MOD = BigInt(1e9 + 7); const f: bigint[] = Array(MX).fill(1n); const g: bigint[] = Array(MX).fill(1n); function qpow(a: bigint, k: number): bigint { let res = 1n; while (k !== 0) { if ((k & 1) === 1) { res = (res * a) % MOD; } a = (a * a) % MOD; k >>= 1; } return res; } (function init() { for (let i = 1; i < MX; ++i) { f[i] = (f[i - 1] * BigInt(i)) % MOD; g[i] = qpow(f[i], Number(MOD - 2n)); } })(); function comb(m: number, n: number): bigint { return (((f[m] * g[n]) % MOD) * g[m - n]) % MOD; } export function countGoodArrays(n: number, m: number, k: number): number { const ans = (((comb(n - 1, k) * BigInt(m)) % MOD) * qpow(BigInt(m - 1), n - k - 1)) % MOD; return Number(ans); }
3,406
Find the Lexicographically Largest String From the Box II
Hard
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p> <p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p> <ul> <li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li> <li>All the split words are put into a box.</li> </ul> <p>Find the <strong>lexicographically largest</strong> string from the box after all the rounds are finished.</p> <p>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.<br /> If the first <code>min(a.length, b.length)</code> characters do not differ, then the shorter string is the lexicographically smaller one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;dbca&quot;, numFriends = 2</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;dbc&quot;</span></p> <p><strong>Explanation:</strong></p> <p>All possible splits are:</p> <ul> <li><code>&quot;d&quot;</code> and <code>&quot;bca&quot;</code>.</li> <li><code>&quot;db&quot;</code> and <code>&quot;ca&quot;</code>.</li> <li><code>&quot;dbc&quot;</code> and <code>&quot;a&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">word = &quot;gggg&quot;, numFriends = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;g&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The only possible split is: <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, and <code>&quot;g&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= numFriends &lt;= word.length</code></li> </ul>
Two Pointers; String
C++
class Solution { public: string answerString(string word, int numFriends) { if (numFriends == 1) { return word; } string s = lastSubstring(word); return s.substr(0, min(s.length(), word.length() - numFriends + 1)); } string lastSubstring(string& s) { int n = s.size(); int i = 0, j = 1, k = 0; while (j + k < n) { if (s[i + k] == s[j + k]) { ++k; } else if (s[i + k] < s[j + k]) { i += k + 1; k = 0; if (i >= j) { j = i + 1; } } else { j += k + 1; k = 0; } } return s.substr(i); } };
3,406
Find the Lexicographically Largest String From the Box II
Hard
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p> <p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p> <ul> <li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li> <li>All the split words are put into a box.</li> </ul> <p>Find the <strong>lexicographically largest</strong> string from the box after all the rounds are finished.</p> <p>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.<br /> If the first <code>min(a.length, b.length)</code> characters do not differ, then the shorter string is the lexicographically smaller one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;dbca&quot;, numFriends = 2</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;dbc&quot;</span></p> <p><strong>Explanation:</strong></p> <p>All possible splits are:</p> <ul> <li><code>&quot;d&quot;</code> and <code>&quot;bca&quot;</code>.</li> <li><code>&quot;db&quot;</code> and <code>&quot;ca&quot;</code>.</li> <li><code>&quot;dbc&quot;</code> and <code>&quot;a&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">word = &quot;gggg&quot;, numFriends = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;g&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The only possible split is: <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, and <code>&quot;g&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= numFriends &lt;= word.length</code></li> </ul>
Two Pointers; String
Go
func answerString(word string, numFriends int) string { if numFriends == 1 { return word } s := lastSubstring(word) return s[:min(len(s), len(word)-numFriends+1)] } func lastSubstring(s string) string { n := len(s) i, j, k := 0, 1, 0 for j+k < n { if s[i+k] == s[j+k] { k++ } else if s[i+k] < s[j+k] { i += k + 1 k = 0 if i >= j { j = i + 1 } } else { j += k + 1 k = 0 } } return s[i:] }
3,406
Find the Lexicographically Largest String From the Box II
Hard
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p> <p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p> <ul> <li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li> <li>All the split words are put into a box.</li> </ul> <p>Find the <strong>lexicographically largest</strong> string from the box after all the rounds are finished.</p> <p>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.<br /> If the first <code>min(a.length, b.length)</code> characters do not differ, then the shorter string is the lexicographically smaller one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;dbca&quot;, numFriends = 2</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;dbc&quot;</span></p> <p><strong>Explanation:</strong></p> <p>All possible splits are:</p> <ul> <li><code>&quot;d&quot;</code> and <code>&quot;bca&quot;</code>.</li> <li><code>&quot;db&quot;</code> and <code>&quot;ca&quot;</code>.</li> <li><code>&quot;dbc&quot;</code> and <code>&quot;a&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">word = &quot;gggg&quot;, numFriends = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;g&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The only possible split is: <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, and <code>&quot;g&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= numFriends &lt;= word.length</code></li> </ul>
Two Pointers; String
Java
class Solution { public String answerString(String word, int numFriends) { if (numFriends == 1) { return word; } String s = lastSubstring(word); return s.substring(0, Math.min(s.length(), word.length() - numFriends + 1)); } public String lastSubstring(String s) { int n = s.length(); int i = 0, j = 1, k = 0; while (j + k < n) { int d = s.charAt(i + k) - s.charAt(j + k); if (d == 0) { ++k; } else if (d < 0) { i += k + 1; k = 0; if (i >= j) { j = i + 1; } } else { j += k + 1; k = 0; } } return s.substring(i); } }
3,406
Find the Lexicographically Largest String From the Box II
Hard
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p> <p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p> <ul> <li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li> <li>All the split words are put into a box.</li> </ul> <p>Find the <strong>lexicographically largest</strong> string from the box after all the rounds are finished.</p> <p>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.<br /> If the first <code>min(a.length, b.length)</code> characters do not differ, then the shorter string is the lexicographically smaller one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;dbca&quot;, numFriends = 2</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;dbc&quot;</span></p> <p><strong>Explanation:</strong></p> <p>All possible splits are:</p> <ul> <li><code>&quot;d&quot;</code> and <code>&quot;bca&quot;</code>.</li> <li><code>&quot;db&quot;</code> and <code>&quot;ca&quot;</code>.</li> <li><code>&quot;dbc&quot;</code> and <code>&quot;a&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">word = &quot;gggg&quot;, numFriends = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;g&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The only possible split is: <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, and <code>&quot;g&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= numFriends &lt;= word.length</code></li> </ul>
Two Pointers; String
Python
class Solution: def answerString(self, word: str, numFriends: int) -> str: if numFriends == 1: return word s = self.lastSubstring(word) return s[: len(word) - numFriends + 1] def lastSubstring(self, s: str) -> str: i, j, k = 0, 1, 0 while j + k < len(s): if s[i + k] == s[j + k]: k += 1 elif s[i + k] < s[j + k]: i += k + 1 k = 0 if i >= j: j = i + 1 else: j += k + 1 k = 0 return s[i:]
3,406
Find the Lexicographically Largest String From the Box II
Hard
<p>You are given a string <code>word</code>, and an integer <code>numFriends</code>.</p> <p>Alice is organizing a game for her <code>numFriends</code> friends. There are multiple rounds in the game, where in each round:</p> <ul> <li><code>word</code> is split into <code>numFriends</code> <strong>non-empty</strong> strings, such that no previous round has had the <strong>exact</strong> same split.</li> <li>All the split words are put into a box.</li> </ul> <p>Find the <strong>lexicographically largest</strong> string from the box after all the rounds are finished.</p> <p>A string <code>a</code> is <strong>lexicographically smaller</strong> than a string <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.<br /> If the first <code>min(a.length, b.length)</code> characters do not differ, then the shorter string is the lexicographically smaller one.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word = &quot;dbca&quot;, numFriends = 2</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;dbc&quot;</span></p> <p><strong>Explanation:</strong></p> <p>All possible splits are:</p> <ul> <li><code>&quot;d&quot;</code> and <code>&quot;bca&quot;</code>.</li> <li><code>&quot;db&quot;</code> and <code>&quot;ca&quot;</code>.</li> <li><code>&quot;dbc&quot;</code> and <code>&quot;a&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">word = &quot;gggg&quot;, numFriends = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;g&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The only possible split is: <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, <code>&quot;g&quot;</code>, and <code>&quot;g&quot;</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= numFriends &lt;= word.length</code></li> </ul>
Two Pointers; String
TypeScript
function answerString(word: string, numFriends: number): string { if (numFriends === 1) { return word; } const s = lastSubstring(word); return s.slice(0, word.length - numFriends + 1); } function lastSubstring(s: string): string { const n = s.length; let i = 0; for (let j = 1, k = 0; j + k < n; ) { if (s[i + k] === s[j + k]) { ++k; } else if (s[i + k] < s[j + k]) { i += k + 1; k = 0; if (i >= j) { j = i + 1; } } else { j += k + 1; k = 0; } } return s.slice(i); }
3,407
Substring Matching Pattern
Easy
<p>You are given a string <code>s</code> and a pattern string <code>p</code>, where <code>p</code> contains <strong>exactly one</strong> <code>&#39;*&#39;</code> character.</p> <p>The <code>&#39;*&#39;</code> in <code>p</code> can be replaced with any sequence of zero or more characters.</p> <p>Return <code>true</code> if <code>p</code> can be made a <span data-keyword="substring-nonempty">substring</span> of <code>s</code>, 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">s = &quot;leetcode&quot;, p = &quot;ee*e&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>By replacing the <code>&#39;*&#39;</code> with <code>&quot;tcod&quot;</code>, the substring <code>&quot;eetcode&quot;</code> matches the pattern.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;car&quot;, p = &quot;c*v&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no substring matching the pattern.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;luck&quot;, p = &quot;u*&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The substrings <code>&quot;u&quot;</code>, <code>&quot;uc&quot;</code>, and <code>&quot;uck&quot;</code> match the pattern.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>1 &lt;= p.length &lt;= 50 </code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters and exactly one <code>&#39;*&#39;</code></li> </ul>
String; String Matching
C++
class Solution { public: bool hasMatch(string s, string p) { int i = 0; int pos = 0; int start = 0, end; while ((end = p.find("*", start)) != string::npos) { string t = p.substr(start, end - start); pos = s.find(t, i); if (pos == string::npos) { return false; } i = pos + t.length(); start = end + 1; } string t = p.substr(start); pos = s.find(t, i); if (pos == string::npos) { return false; } return true; } };
3,407
Substring Matching Pattern
Easy
<p>You are given a string <code>s</code> and a pattern string <code>p</code>, where <code>p</code> contains <strong>exactly one</strong> <code>&#39;*&#39;</code> character.</p> <p>The <code>&#39;*&#39;</code> in <code>p</code> can be replaced with any sequence of zero or more characters.</p> <p>Return <code>true</code> if <code>p</code> can be made a <span data-keyword="substring-nonempty">substring</span> of <code>s</code>, 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">s = &quot;leetcode&quot;, p = &quot;ee*e&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>By replacing the <code>&#39;*&#39;</code> with <code>&quot;tcod&quot;</code>, the substring <code>&quot;eetcode&quot;</code> matches the pattern.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;car&quot;, p = &quot;c*v&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no substring matching the pattern.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;luck&quot;, p = &quot;u*&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The substrings <code>&quot;u&quot;</code>, <code>&quot;uc&quot;</code>, and <code>&quot;uck&quot;</code> match the pattern.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>1 &lt;= p.length &lt;= 50 </code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters and exactly one <code>&#39;*&#39;</code></li> </ul>
String; String Matching
Go
func hasMatch(s string, p string) bool { i := 0 for _, t := range strings.Split(p, "*") { j := strings.Index(s[i:], t) if j == -1 { return false } i += j + len(t) } return true }
3,407
Substring Matching Pattern
Easy
<p>You are given a string <code>s</code> and a pattern string <code>p</code>, where <code>p</code> contains <strong>exactly one</strong> <code>&#39;*&#39;</code> character.</p> <p>The <code>&#39;*&#39;</code> in <code>p</code> can be replaced with any sequence of zero or more characters.</p> <p>Return <code>true</code> if <code>p</code> can be made a <span data-keyword="substring-nonempty">substring</span> of <code>s</code>, 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">s = &quot;leetcode&quot;, p = &quot;ee*e&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>By replacing the <code>&#39;*&#39;</code> with <code>&quot;tcod&quot;</code>, the substring <code>&quot;eetcode&quot;</code> matches the pattern.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;car&quot;, p = &quot;c*v&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no substring matching the pattern.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;luck&quot;, p = &quot;u*&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The substrings <code>&quot;u&quot;</code>, <code>&quot;uc&quot;</code>, and <code>&quot;uck&quot;</code> match the pattern.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>1 &lt;= p.length &lt;= 50 </code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters and exactly one <code>&#39;*&#39;</code></li> </ul>
String; String Matching
Java
class Solution { public boolean hasMatch(String s, String p) { int i = 0; for (String t : p.split("\\*")) { int j = s.indexOf(t, i); if (j == -1) { return false; } i = j + t.length(); } return true; } }
3,407
Substring Matching Pattern
Easy
<p>You are given a string <code>s</code> and a pattern string <code>p</code>, where <code>p</code> contains <strong>exactly one</strong> <code>&#39;*&#39;</code> character.</p> <p>The <code>&#39;*&#39;</code> in <code>p</code> can be replaced with any sequence of zero or more characters.</p> <p>Return <code>true</code> if <code>p</code> can be made a <span data-keyword="substring-nonempty">substring</span> of <code>s</code>, 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">s = &quot;leetcode&quot;, p = &quot;ee*e&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>By replacing the <code>&#39;*&#39;</code> with <code>&quot;tcod&quot;</code>, the substring <code>&quot;eetcode&quot;</code> matches the pattern.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;car&quot;, p = &quot;c*v&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no substring matching the pattern.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;luck&quot;, p = &quot;u*&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The substrings <code>&quot;u&quot;</code>, <code>&quot;uc&quot;</code>, and <code>&quot;uck&quot;</code> match the pattern.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>1 &lt;= p.length &lt;= 50 </code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters and exactly one <code>&#39;*&#39;</code></li> </ul>
String; String Matching
Python
class Solution: def hasMatch(self, s: str, p: str) -> bool: i = 0 for t in p.split("*"): j = s.find(t, i) if j == -1: return False i = j + len(t) return True
3,407
Substring Matching Pattern
Easy
<p>You are given a string <code>s</code> and a pattern string <code>p</code>, where <code>p</code> contains <strong>exactly one</strong> <code>&#39;*&#39;</code> character.</p> <p>The <code>&#39;*&#39;</code> in <code>p</code> can be replaced with any sequence of zero or more characters.</p> <p>Return <code>true</code> if <code>p</code> can be made a <span data-keyword="substring-nonempty">substring</span> of <code>s</code>, 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">s = &quot;leetcode&quot;, p = &quot;ee*e&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>By replacing the <code>&#39;*&#39;</code> with <code>&quot;tcod&quot;</code>, the substring <code>&quot;eetcode&quot;</code> matches the pattern.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;car&quot;, p = &quot;c*v&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>There is no substring matching the pattern.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;luck&quot;, p = &quot;u*&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The substrings <code>&quot;u&quot;</code>, <code>&quot;uc&quot;</code>, and <code>&quot;uck&quot;</code> match the pattern.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>1 &lt;= p.length &lt;= 50 </code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters and exactly one <code>&#39;*&#39;</code></li> </ul>
String; String Matching
TypeScript
function hasMatch(s: string, p: string): boolean { let i = 0; for (const t of p.split('*')) { const j = s.indexOf(t, i); if (j === -1) { return false; } i = j + t.length; } return true; }
3,408
Design Task Manager
Medium
<p>There is a task management system that allows users to manage their tasks, each associated with a priority. The system should efficiently handle adding, modifying, executing, and removing tasks.</p> <p>Implement the <code>TaskManager</code> class:</p> <ul> <li> <p><code>TaskManager(vector&lt;vector&lt;int&gt;&gt;&amp; tasks)</code> initializes the task manager with a list of user-task-priority triples. Each element in the input list is of the form <code>[userId, taskId, priority]</code>, which adds a task to the specified user with the given priority.</p> </li> <li> <p><code>void add(int userId, int taskId, int priority)</code> adds a task with the specified <code>taskId</code> and <code>priority</code> to the user with <code>userId</code>. It is <strong>guaranteed</strong> that <code>taskId</code> does not <em>exist</em> in the system.</p> </li> <li> <p><code>void edit(int taskId, int newPriority)</code> updates the priority of the existing <code>taskId</code> to <code>newPriority</code>. It is <strong>guaranteed</strong> that <code>taskId</code> <em>exists</em> in the system.</p> </li> <li> <p><code>void rmv(int taskId)</code> removes the task identified by <code>taskId</code> from the system. It is <strong>guaranteed</strong> that <code>taskId</code> <em>exists</em> in the system.</p> </li> <li> <p><code>int execTop()</code> executes the task with the <strong>highest</strong> priority across all users. If there are multiple tasks with the same <strong>highest</strong> priority, execute the one with the highest <code>taskId</code>. After executing, the<strong> </strong><code>taskId</code><strong> </strong>is <strong>removed</strong> from the system. Return the <code>userId</code> associated with the executed task. If no tasks are available, return -1.</p> </li> </ul> <p><strong>Note</strong> that a user may be assigned multiple tasks.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;TaskManager&quot;, &quot;add&quot;, &quot;edit&quot;, &quot;execTop&quot;, &quot;rmv&quot;, &quot;add&quot;, &quot;execTop&quot;]<br /> [[[[1, 101, 10], [2, 102, 20], [3, 103, 15]]], [4, 104, 5], [102, 8], [], [101], [5, 105, 15], []]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, null, null, 3, null, null, 5] </span></p> <p><strong>Explanation</strong></p> TaskManager taskManager = new TaskManager([[1, 101, 10], [2, 102, 20], [3, 103, 15]]); // Initializes with three tasks for Users 1, 2, and 3.<br /> taskManager.add(4, 104, 5); // Adds task 104 with priority 5 for User 4.<br /> taskManager.edit(102, 8); // Updates priority of task 102 to 8.<br /> taskManager.execTop(); // return 3. Executes task 103 for User 3.<br /> taskManager.rmv(101); // Removes task 101 from the system.<br /> taskManager.add(5, 105, 15); // Adds task 105 with priority 15 for User 5.<br /> taskManager.execTop(); // return 5. Executes task 105 for User 5.</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= userId &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= taskId &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= priority &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= newPriority &lt;= 10<sup>9</sup></code></li> <li>At most <code>2 * 10<sup>5</sup></code> calls will be made in <strong>total</strong> to <code>add</code>, <code>edit</code>, <code>rmv</code>, and <code>execTop</code> methods.</li> <li>The input is generated such that <code>taskId</code> will be valid.</li> </ul>
Design; Hash Table; Ordered Set; Heap (Priority Queue)
C++
class TaskManager { private: unordered_map<int, pair<int, int>> d; set<pair<int, int>> st; public: TaskManager(vector<vector<int>>& tasks) { for (const auto& task : tasks) { add(task[0], task[1], task[2]); } } void add(int userId, int taskId, int priority) { d[taskId] = {userId, priority}; st.insert({-priority, -taskId}); } void edit(int taskId, int newPriority) { auto [userId, priority] = d[taskId]; st.erase({-priority, -taskId}); st.insert({-newPriority, -taskId}); d[taskId] = {userId, newPriority}; } void rmv(int taskId) { auto [userId, priority] = d[taskId]; st.erase({-priority, -taskId}); d.erase(taskId); } int execTop() { if (st.empty()) { return -1; } auto e = *st.begin(); st.erase(st.begin()); int taskId = -e.second; int userId = d[taskId].first; d.erase(taskId); return userId; } }; /** * Your TaskManager object will be instantiated and called as such: * TaskManager* obj = new TaskManager(tasks); * obj->add(userId,taskId,priority); * obj->edit(taskId,newPriority); * obj->rmv(taskId); * int param_4 = obj->execTop(); */
3,408
Design Task Manager
Medium
<p>There is a task management system that allows users to manage their tasks, each associated with a priority. The system should efficiently handle adding, modifying, executing, and removing tasks.</p> <p>Implement the <code>TaskManager</code> class:</p> <ul> <li> <p><code>TaskManager(vector&lt;vector&lt;int&gt;&gt;&amp; tasks)</code> initializes the task manager with a list of user-task-priority triples. Each element in the input list is of the form <code>[userId, taskId, priority]</code>, which adds a task to the specified user with the given priority.</p> </li> <li> <p><code>void add(int userId, int taskId, int priority)</code> adds a task with the specified <code>taskId</code> and <code>priority</code> to the user with <code>userId</code>. It is <strong>guaranteed</strong> that <code>taskId</code> does not <em>exist</em> in the system.</p> </li> <li> <p><code>void edit(int taskId, int newPriority)</code> updates the priority of the existing <code>taskId</code> to <code>newPriority</code>. It is <strong>guaranteed</strong> that <code>taskId</code> <em>exists</em> in the system.</p> </li> <li> <p><code>void rmv(int taskId)</code> removes the task identified by <code>taskId</code> from the system. It is <strong>guaranteed</strong> that <code>taskId</code> <em>exists</em> in the system.</p> </li> <li> <p><code>int execTop()</code> executes the task with the <strong>highest</strong> priority across all users. If there are multiple tasks with the same <strong>highest</strong> priority, execute the one with the highest <code>taskId</code>. After executing, the<strong> </strong><code>taskId</code><strong> </strong>is <strong>removed</strong> from the system. Return the <code>userId</code> associated with the executed task. If no tasks are available, return -1.</p> </li> </ul> <p><strong>Note</strong> that a user may be assigned multiple tasks.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;TaskManager&quot;, &quot;add&quot;, &quot;edit&quot;, &quot;execTop&quot;, &quot;rmv&quot;, &quot;add&quot;, &quot;execTop&quot;]<br /> [[[[1, 101, 10], [2, 102, 20], [3, 103, 15]]], [4, 104, 5], [102, 8], [], [101], [5, 105, 15], []]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, null, null, 3, null, null, 5] </span></p> <p><strong>Explanation</strong></p> TaskManager taskManager = new TaskManager([[1, 101, 10], [2, 102, 20], [3, 103, 15]]); // Initializes with three tasks for Users 1, 2, and 3.<br /> taskManager.add(4, 104, 5); // Adds task 104 with priority 5 for User 4.<br /> taskManager.edit(102, 8); // Updates priority of task 102 to 8.<br /> taskManager.execTop(); // return 3. Executes task 103 for User 3.<br /> taskManager.rmv(101); // Removes task 101 from the system.<br /> taskManager.add(5, 105, 15); // Adds task 105 with priority 15 for User 5.<br /> taskManager.execTop(); // return 5. Executes task 105 for User 5.</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= userId &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= taskId &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= priority &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= newPriority &lt;= 10<sup>9</sup></code></li> <li>At most <code>2 * 10<sup>5</sup></code> calls will be made in <strong>total</strong> to <code>add</code>, <code>edit</code>, <code>rmv</code>, and <code>execTop</code> methods.</li> <li>The input is generated such that <code>taskId</code> will be valid.</li> </ul>
Design; Hash Table; Ordered Set; Heap (Priority Queue)
Java
class TaskManager { private final Map<Integer, int[]> d = new HashMap<>(); private final TreeSet<int[]> st = new TreeSet<>((a, b) -> { if (a[0] == b[0]) { return b[1] - a[1]; } return b[0] - a[0]; }); public TaskManager(List<List<Integer>> tasks) { for (var task : tasks) { add(task.get(0), task.get(1), task.get(2)); } } public void add(int userId, int taskId, int priority) { d.put(taskId, new int[] {userId, priority}); st.add(new int[] {priority, taskId}); } public void edit(int taskId, int newPriority) { var e = d.get(taskId); int userId = e[0], priority = e[1]; st.remove(new int[] {priority, taskId}); st.add(new int[] {newPriority, taskId}); d.put(taskId, new int[] {userId, newPriority}); } public void rmv(int taskId) { var e = d.remove(taskId); int priority = e[1]; st.remove(new int[] {priority, taskId}); } public int execTop() { if (st.isEmpty()) { return -1; } var e = st.pollFirst(); var t = d.remove(e[1]); return t[0]; } } /** * Your TaskManager object will be instantiated and called as such: * TaskManager obj = new TaskManager(tasks); * obj.add(userId,taskId,priority); * obj.edit(taskId,newPriority); * obj.rmv(taskId); * int param_4 = obj.execTop(); */
3,408
Design Task Manager
Medium
<p>There is a task management system that allows users to manage their tasks, each associated with a priority. The system should efficiently handle adding, modifying, executing, and removing tasks.</p> <p>Implement the <code>TaskManager</code> class:</p> <ul> <li> <p><code>TaskManager(vector&lt;vector&lt;int&gt;&gt;&amp; tasks)</code> initializes the task manager with a list of user-task-priority triples. Each element in the input list is of the form <code>[userId, taskId, priority]</code>, which adds a task to the specified user with the given priority.</p> </li> <li> <p><code>void add(int userId, int taskId, int priority)</code> adds a task with the specified <code>taskId</code> and <code>priority</code> to the user with <code>userId</code>. It is <strong>guaranteed</strong> that <code>taskId</code> does not <em>exist</em> in the system.</p> </li> <li> <p><code>void edit(int taskId, int newPriority)</code> updates the priority of the existing <code>taskId</code> to <code>newPriority</code>. It is <strong>guaranteed</strong> that <code>taskId</code> <em>exists</em> in the system.</p> </li> <li> <p><code>void rmv(int taskId)</code> removes the task identified by <code>taskId</code> from the system. It is <strong>guaranteed</strong> that <code>taskId</code> <em>exists</em> in the system.</p> </li> <li> <p><code>int execTop()</code> executes the task with the <strong>highest</strong> priority across all users. If there are multiple tasks with the same <strong>highest</strong> priority, execute the one with the highest <code>taskId</code>. After executing, the<strong> </strong><code>taskId</code><strong> </strong>is <strong>removed</strong> from the system. Return the <code>userId</code> associated with the executed task. If no tasks are available, return -1.</p> </li> </ul> <p><strong>Note</strong> that a user may be assigned multiple tasks.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;TaskManager&quot;, &quot;add&quot;, &quot;edit&quot;, &quot;execTop&quot;, &quot;rmv&quot;, &quot;add&quot;, &quot;execTop&quot;]<br /> [[[[1, 101, 10], [2, 102, 20], [3, 103, 15]]], [4, 104, 5], [102, 8], [], [101], [5, 105, 15], []]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, null, null, 3, null, null, 5] </span></p> <p><strong>Explanation</strong></p> TaskManager taskManager = new TaskManager([[1, 101, 10], [2, 102, 20], [3, 103, 15]]); // Initializes with three tasks for Users 1, 2, and 3.<br /> taskManager.add(4, 104, 5); // Adds task 104 with priority 5 for User 4.<br /> taskManager.edit(102, 8); // Updates priority of task 102 to 8.<br /> taskManager.execTop(); // return 3. Executes task 103 for User 3.<br /> taskManager.rmv(101); // Removes task 101 from the system.<br /> taskManager.add(5, 105, 15); // Adds task 105 with priority 15 for User 5.<br /> taskManager.execTop(); // return 5. Executes task 105 for User 5.</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= tasks.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= userId &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= taskId &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= priority &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= newPriority &lt;= 10<sup>9</sup></code></li> <li>At most <code>2 * 10<sup>5</sup></code> calls will be made in <strong>total</strong> to <code>add</code>, <code>edit</code>, <code>rmv</code>, and <code>execTop</code> methods.</li> <li>The input is generated such that <code>taskId</code> will be valid.</li> </ul>
Design; Hash Table; Ordered Set; Heap (Priority Queue)
Python
class TaskManager: def __init__(self, tasks: List[List[int]]): self.d = {} self.st = SortedList() for task in tasks: self.add(*task) def add(self, userId: int, taskId: int, priority: int) -> None: self.d[taskId] = (userId, priority) self.st.add((-priority, -taskId)) def edit(self, taskId: int, newPriority: int) -> None: userId, priority = self.d[taskId] self.st.discard((-priority, -taskId)) self.d[taskId] = (userId, newPriority) self.st.add((-newPriority, -taskId)) def rmv(self, taskId: int) -> None: _, priority = self.d[taskId] self.d.pop(taskId) self.st.remove((-priority, -taskId)) def execTop(self) -> int: if not self.st: return -1 taskId = -self.st.pop(0)[1] userId, _ = self.d[taskId] self.d.pop(taskId) return userId # Your TaskManager object will be instantiated and called as such: # obj = TaskManager(tasks) # obj.add(userId,taskId,priority) # obj.edit(taskId,newPriority) # obj.rmv(taskId) # param_4 = obj.execTop()
3,411
Maximum Subarray With Equal Products
Easy
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>An array <code>arr</code> is called <strong>product equivalent</strong> if <code>prod(arr) == lcm(arr) * gcd(arr)</code>, where:</p> <ul> <li><code>prod(arr)</code> is the product of all elements of <code>arr</code>.</li> <li><code>gcd(arr)</code> is the <span data-keyword="gcd-function">GCD</span> of all elements of <code>arr</code>.</li> <li><code>lcm(arr)</code> is the <span data-keyword="lcm-function">LCM</span> of all elements of <code>arr</code>.</li> </ul> <p>Return the length of the <strong>longest</strong> <strong>product equivalent</strong> <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</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,2,1,2,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>The longest product equivalent subarray is <code>[1, 2, 1, 1, 1]</code>, where&nbsp;<code>prod([1, 2, 1, 1, 1]) = 2</code>,&nbsp;<code>gcd([1, 2, 1, 1, 1]) = 1</code>, and&nbsp;<code>lcm([1, 2, 1, 1, 1]) = 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,5,6]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>The longest product equivalent subarray is <code>[3, 4, 5].</code></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1,4,5,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10</code></li> </ul>
Array; Math; Enumeration; Number Theory; Sliding Window
C++
class Solution { public: int maxLength(vector<int>& nums) { int mx = 0, ml = 1; for (int x : nums) { mx = max(mx, x); ml = lcm(ml, x); } long long maxP = (long long) ml * mx; int n = nums.size(); int ans = 0; for (int i = 0; i < n; ++i) { long long p = 1, g = 0, l = 1; for (int j = i; j < n; ++j) { p *= nums[j]; g = gcd(g, nums[j]); l = lcm(l, nums[j]); if (p == g * l) { ans = max(ans, j - i + 1); } if (p > maxP) { break; } } } return ans; } };
3,411
Maximum Subarray With Equal Products
Easy
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>An array <code>arr</code> is called <strong>product equivalent</strong> if <code>prod(arr) == lcm(arr) * gcd(arr)</code>, where:</p> <ul> <li><code>prod(arr)</code> is the product of all elements of <code>arr</code>.</li> <li><code>gcd(arr)</code> is the <span data-keyword="gcd-function">GCD</span> of all elements of <code>arr</code>.</li> <li><code>lcm(arr)</code> is the <span data-keyword="lcm-function">LCM</span> of all elements of <code>arr</code>.</li> </ul> <p>Return the length of the <strong>longest</strong> <strong>product equivalent</strong> <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</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,2,1,2,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>The longest product equivalent subarray is <code>[1, 2, 1, 1, 1]</code>, where&nbsp;<code>prod([1, 2, 1, 1, 1]) = 2</code>,&nbsp;<code>gcd([1, 2, 1, 1, 1]) = 1</code>, and&nbsp;<code>lcm([1, 2, 1, 1, 1]) = 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,5,6]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>The longest product equivalent subarray is <code>[3, 4, 5].</code></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1,4,5,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10</code></li> </ul>
Array; Math; Enumeration; Number Theory; Sliding Window
Go
func maxLength(nums []int) int { mx, ml := 0, 1 for _, x := range nums { mx = max(mx, x) ml = lcm(ml, x) } maxP := ml * mx n := len(nums) ans := 0 for i := 0; i < n; i++ { p, g, l := 1, 0, 1 for j := i; j < n; j++ { p *= nums[j] g = gcd(g, nums[j]) l = lcm(l, nums[j]) if p == g*l { ans = max(ans, j-i+1) } if p > maxP { break } } } return ans } func gcd(a, b int) int { for b != 0 { a, b = b, a%b } return a } func lcm(a, b int) int { return a / gcd(a, b) * b }
3,411
Maximum Subarray With Equal Products
Easy
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>An array <code>arr</code> is called <strong>product equivalent</strong> if <code>prod(arr) == lcm(arr) * gcd(arr)</code>, where:</p> <ul> <li><code>prod(arr)</code> is the product of all elements of <code>arr</code>.</li> <li><code>gcd(arr)</code> is the <span data-keyword="gcd-function">GCD</span> of all elements of <code>arr</code>.</li> <li><code>lcm(arr)</code> is the <span data-keyword="lcm-function">LCM</span> of all elements of <code>arr</code>.</li> </ul> <p>Return the length of the <strong>longest</strong> <strong>product equivalent</strong> <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</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,2,1,2,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>The longest product equivalent subarray is <code>[1, 2, 1, 1, 1]</code>, where&nbsp;<code>prod([1, 2, 1, 1, 1]) = 2</code>,&nbsp;<code>gcd([1, 2, 1, 1, 1]) = 1</code>, and&nbsp;<code>lcm([1, 2, 1, 1, 1]) = 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,5,6]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>The longest product equivalent subarray is <code>[3, 4, 5].</code></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1,4,5,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10</code></li> </ul>
Array; Math; Enumeration; Number Theory; Sliding Window
Java
class Solution { public int maxLength(int[] nums) { int mx = 0, ml = 1; for (int x : nums) { mx = Math.max(mx, x); ml = lcm(ml, x); } int maxP = ml * mx; int n = nums.length; int ans = 0; for (int i = 0; i < n; ++i) { int p = 1, g = 0, l = 1; for (int j = i; j < n; ++j) { p *= nums[j]; g = gcd(g, nums[j]); l = lcm(l, nums[j]); if (p == g * l) { ans = Math.max(ans, j - i + 1); } if (p > maxP) { break; } } } return ans; } private int gcd(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } private int lcm(int a, int b) { return a / gcd(a, b) * b; } }
3,411
Maximum Subarray With Equal Products
Easy
<p>You are given an array of <strong>positive</strong> integers <code>nums</code>.</p> <p>An array <code>arr</code> is called <strong>product equivalent</strong> if <code>prod(arr) == lcm(arr) * gcd(arr)</code>, where:</p> <ul> <li><code>prod(arr)</code> is the product of all elements of <code>arr</code>.</li> <li><code>gcd(arr)</code> is the <span data-keyword="gcd-function">GCD</span> of all elements of <code>arr</code>.</li> <li><code>lcm(arr)</code> is the <span data-keyword="lcm-function">LCM</span> of all elements of <code>arr</code>.</li> </ul> <p>Return the length of the <strong>longest</strong> <strong>product equivalent</strong> <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</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,2,1,2,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>The longest product equivalent subarray is <code>[1, 2, 1, 1, 1]</code>, where&nbsp;<code>prod([1, 2, 1, 1, 1]) = 2</code>,&nbsp;<code>gcd([1, 2, 1, 1, 1]) = 1</code>, and&nbsp;<code>lcm([1, 2, 1, 1, 1]) = 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,4,5,6]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong>&nbsp;</p> <p>The longest product equivalent subarray is <code>[3, 4, 5].</code></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1,4,5,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10</code></li> </ul>
Array; Math; Enumeration; Number Theory; Sliding Window
Python
class Solution: def maxLength(self, nums: List[int]) -> int: n = len(nums) ans = 0 max_p = lcm(*nums) * max(nums) for i in range(n): p, g, l = 1, 0, 1 for j in range(i, n): p *= nums[j] g = gcd(g, nums[j]) l = lcm(l, nums[j]) if p == g * l: ans = max(ans, j - i + 1) if p > max_p: break return ans
3,412
Find Mirror Score of a String
Medium
<p>You are given a string <code>s</code>.</p> <p>We define the <strong>mirror</strong> of a letter in the English alphabet as its corresponding letter when the alphabet is reversed. For example, the mirror of <code>&#39;a&#39;</code> is <code>&#39;z&#39;</code>, and the mirror of <code>&#39;y&#39;</code> is <code>&#39;b&#39;</code>.</p> <p>Initially, all characters in the string <code>s</code> are <strong>unmarked</strong>.</p> <p>You start with a score of 0, and you perform the following process on the string <code>s</code>:</p> <ul> <li>Iterate through the string from left to right.</li> <li>At each index <code>i</code>, find the closest <strong>unmarked</strong> index <code>j</code> such that <code>j &lt; i</code> and <code>s[j]</code> is the mirror of <code>s[i]</code>. Then, <strong>mark</strong> both indices <code>i</code> and <code>j</code>, and add the value <code>i - j</code> to the total score.</li> <li>If no such index <code>j</code> exists for the index <code>i</code>, move on to the next index without making any changes.</li> </ul> <p>Return the total score at the end of the process.</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;aczzx&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>i = 0</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 1</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 2</code>. The closest index <code>j</code> that satisfies the conditions is <code>j = 0</code>, so we mark both indices 0 and 2, and then add <code>2 - 0 = 2</code> to the score.</li> <li><code>i = 3</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 4</code>. The closest index <code>j</code> that satisfies the conditions is <code>j = 1</code>, so we mark both indices 1 and 4, and then add <code>4 - 1 = 3</code> to the score.</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;abcdef&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>For each index <code>i</code>, there is no index <code>j</code> that satisfies the conditions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Stack; Hash Table; String; Simulation
C++
class Solution { public: long long calculateScore(string s) { unordered_map<char, vector<int>> d; int n = s.length(); long long ans = 0; for (int i = 0; i < n; ++i) { char x = s[i]; char y = 'a' + 'z' - x; if (d.contains(y)) { vector<int>& ls = d[y]; int j = ls.back(); ls.pop_back(); if (ls.empty()) { d.erase(y); } ans += i - j; } else { d[x].push_back(i); } } return ans; } };
3,412
Find Mirror Score of a String
Medium
<p>You are given a string <code>s</code>.</p> <p>We define the <strong>mirror</strong> of a letter in the English alphabet as its corresponding letter when the alphabet is reversed. For example, the mirror of <code>&#39;a&#39;</code> is <code>&#39;z&#39;</code>, and the mirror of <code>&#39;y&#39;</code> is <code>&#39;b&#39;</code>.</p> <p>Initially, all characters in the string <code>s</code> are <strong>unmarked</strong>.</p> <p>You start with a score of 0, and you perform the following process on the string <code>s</code>:</p> <ul> <li>Iterate through the string from left to right.</li> <li>At each index <code>i</code>, find the closest <strong>unmarked</strong> index <code>j</code> such that <code>j &lt; i</code> and <code>s[j]</code> is the mirror of <code>s[i]</code>. Then, <strong>mark</strong> both indices <code>i</code> and <code>j</code>, and add the value <code>i - j</code> to the total score.</li> <li>If no such index <code>j</code> exists for the index <code>i</code>, move on to the next index without making any changes.</li> </ul> <p>Return the total score at the end of the process.</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;aczzx&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>i = 0</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 1</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 2</code>. The closest index <code>j</code> that satisfies the conditions is <code>j = 0</code>, so we mark both indices 0 and 2, and then add <code>2 - 0 = 2</code> to the score.</li> <li><code>i = 3</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 4</code>. The closest index <code>j</code> that satisfies the conditions is <code>j = 1</code>, so we mark both indices 1 and 4, and then add <code>4 - 1 = 3</code> to the score.</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;abcdef&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>For each index <code>i</code>, there is no index <code>j</code> that satisfies the conditions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Stack; Hash Table; String; Simulation
Go
func calculateScore(s string) (ans int64) { d := make(map[rune][]int) for i, x := range s { y := 'a' + 'z' - x if ls, ok := d[y]; ok { j := ls[len(ls)-1] d[y] = ls[:len(ls)-1] if len(d[y]) == 0 { delete(d, y) } ans += int64(i - j) } else { d[x] = append(d[x], i) } } return }
3,412
Find Mirror Score of a String
Medium
<p>You are given a string <code>s</code>.</p> <p>We define the <strong>mirror</strong> of a letter in the English alphabet as its corresponding letter when the alphabet is reversed. For example, the mirror of <code>&#39;a&#39;</code> is <code>&#39;z&#39;</code>, and the mirror of <code>&#39;y&#39;</code> is <code>&#39;b&#39;</code>.</p> <p>Initially, all characters in the string <code>s</code> are <strong>unmarked</strong>.</p> <p>You start with a score of 0, and you perform the following process on the string <code>s</code>:</p> <ul> <li>Iterate through the string from left to right.</li> <li>At each index <code>i</code>, find the closest <strong>unmarked</strong> index <code>j</code> such that <code>j &lt; i</code> and <code>s[j]</code> is the mirror of <code>s[i]</code>. Then, <strong>mark</strong> both indices <code>i</code> and <code>j</code>, and add the value <code>i - j</code> to the total score.</li> <li>If no such index <code>j</code> exists for the index <code>i</code>, move on to the next index without making any changes.</li> </ul> <p>Return the total score at the end of the process.</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;aczzx&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>i = 0</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 1</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 2</code>. The closest index <code>j</code> that satisfies the conditions is <code>j = 0</code>, so we mark both indices 0 and 2, and then add <code>2 - 0 = 2</code> to the score.</li> <li><code>i = 3</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 4</code>. The closest index <code>j</code> that satisfies the conditions is <code>j = 1</code>, so we mark both indices 1 and 4, and then add <code>4 - 1 = 3</code> to the score.</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;abcdef&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>For each index <code>i</code>, there is no index <code>j</code> that satisfies the conditions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Stack; Hash Table; String; Simulation
Java
class Solution { public long calculateScore(String s) { Map<Character, List<Integer>> d = new HashMap<>(26); int n = s.length(); long ans = 0; for (int i = 0; i < n; ++i) { char x = s.charAt(i); char y = (char) ('a' + 'z' - x); if (d.containsKey(y)) { var ls = d.get(y); int j = ls.remove(ls.size() - 1); if (ls.isEmpty()) { d.remove(y); } ans += i - j; } else { d.computeIfAbsent(x, k -> new ArrayList<>()).add(i); } } return ans; } }
3,412
Find Mirror Score of a String
Medium
<p>You are given a string <code>s</code>.</p> <p>We define the <strong>mirror</strong> of a letter in the English alphabet as its corresponding letter when the alphabet is reversed. For example, the mirror of <code>&#39;a&#39;</code> is <code>&#39;z&#39;</code>, and the mirror of <code>&#39;y&#39;</code> is <code>&#39;b&#39;</code>.</p> <p>Initially, all characters in the string <code>s</code> are <strong>unmarked</strong>.</p> <p>You start with a score of 0, and you perform the following process on the string <code>s</code>:</p> <ul> <li>Iterate through the string from left to right.</li> <li>At each index <code>i</code>, find the closest <strong>unmarked</strong> index <code>j</code> such that <code>j &lt; i</code> and <code>s[j]</code> is the mirror of <code>s[i]</code>. Then, <strong>mark</strong> both indices <code>i</code> and <code>j</code>, and add the value <code>i - j</code> to the total score.</li> <li>If no such index <code>j</code> exists for the index <code>i</code>, move on to the next index without making any changes.</li> </ul> <p>Return the total score at the end of the process.</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;aczzx&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>i = 0</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 1</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 2</code>. The closest index <code>j</code> that satisfies the conditions is <code>j = 0</code>, so we mark both indices 0 and 2, and then add <code>2 - 0 = 2</code> to the score.</li> <li><code>i = 3</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 4</code>. The closest index <code>j</code> that satisfies the conditions is <code>j = 1</code>, so we mark both indices 1 and 4, and then add <code>4 - 1 = 3</code> to the score.</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;abcdef&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>For each index <code>i</code>, there is no index <code>j</code> that satisfies the conditions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Stack; Hash Table; String; Simulation
Python
class Solution: def calculateScore(self, s: str) -> int: d = defaultdict(list) ans = 0 for i, x in enumerate(s): y = chr(ord("a") + ord("z") - ord(x)) if d[y]: j = d[y].pop() ans += i - j else: d[x].append(i) return ans
3,412
Find Mirror Score of a String
Medium
<p>You are given a string <code>s</code>.</p> <p>We define the <strong>mirror</strong> of a letter in the English alphabet as its corresponding letter when the alphabet is reversed. For example, the mirror of <code>&#39;a&#39;</code> is <code>&#39;z&#39;</code>, and the mirror of <code>&#39;y&#39;</code> is <code>&#39;b&#39;</code>.</p> <p>Initially, all characters in the string <code>s</code> are <strong>unmarked</strong>.</p> <p>You start with a score of 0, and you perform the following process on the string <code>s</code>:</p> <ul> <li>Iterate through the string from left to right.</li> <li>At each index <code>i</code>, find the closest <strong>unmarked</strong> index <code>j</code> such that <code>j &lt; i</code> and <code>s[j]</code> is the mirror of <code>s[i]</code>. Then, <strong>mark</strong> both indices <code>i</code> and <code>j</code>, and add the value <code>i - j</code> to the total score.</li> <li>If no such index <code>j</code> exists for the index <code>i</code>, move on to the next index without making any changes.</li> </ul> <p>Return the total score at the end of the process.</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;aczzx&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li><code>i = 0</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 1</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 2</code>. The closest index <code>j</code> that satisfies the conditions is <code>j = 0</code>, so we mark both indices 0 and 2, and then add <code>2 - 0 = 2</code> to the score.</li> <li><code>i = 3</code>. There is no index <code>j</code> that satisfies the conditions, so we skip.</li> <li><code>i = 4</code>. The closest index <code>j</code> that satisfies the conditions is <code>j = 1</code>, so we mark both indices 1 and 4, and then add <code>4 - 1 = 3</code> to the score.</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;abcdef&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>For each index <code>i</code>, there is no index <code>j</code> that satisfies the conditions.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Stack; Hash Table; String; Simulation
TypeScript
function calculateScore(s: string): number { const d: Map<string, number[]> = new Map(); const n = s.length; let ans = 0; for (let i = 0; i < n; i++) { const x = s[i]; const y = String.fromCharCode('a'.charCodeAt(0) + 'z'.charCodeAt(0) - x.charCodeAt(0)); if (d.has(y)) { const ls = d.get(y)!; const j = ls.pop()!; if (ls.length === 0) { d.delete(y); } ans += i - j; } else { if (!d.has(x)) { d.set(x, []); } d.get(x)!.push(i); } } return ans; }
3,415
Find Products with Three Consecutive Digits
Easy
<p>Table: <code>Products</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | product_id | int | | name | varchar | +-------------+---------+ product_id is the unique key for this table. Each row of this table contains the ID and name of a product. </pre> <p>Write a solution to find all <strong>products</strong> whose names contain a <strong>sequence of exactly three consecutive digits in a row</strong>.&nbsp;</p> <p>Return <em>the result table ordered by</em> <code>product_id</code> <em>in <strong>ascending</strong> order.</em></p> <p>The result format is in the following example.</p> <p><strong>Note</strong> that the name may contain multiple such sequences, but each should have length three.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>products table:</p> <pre class="example-io"> +-------------+--------------------+ | product_id | name | +-------------+--------------------+ | 1 | ABC123XYZ | | 2 | A12B34C | | 3 | Product56789 | | 4 | NoDigitsHere | | 5 | 789Product | | 6 | Item003Description | | 7 | Product12X34 | +-------------+--------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+--------------------+ | product_id | name | +-------------+--------------------+ | 1 | ABC123XYZ | | 5 | 789Product | | 6 | Item003Description | +-------------+--------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>Product 1: ABC123XYZ contains the digits 123.</li> <li>Product 5: 789Product&nbsp;contains the digits 789.</li> <li>Product 6: Item003Description&nbsp;contains 003, which is exactly three digits.</li> </ul> <p><strong>Note:</strong></p> <ul> <li>Results are ordered by <code>product_id</code> in ascending order.</li> <li>Only products with exactly three consecutive digits in their names are included in the result.</li> </ul> </div>
Database
Python
import pandas as pd def find_products(products: pd.DataFrame) -> pd.DataFrame: filtered = products[ products["name"].str.contains(r"(^|[^0-9])[0-9]{3}([^0-9]|$)", regex=True) ] return filtered.sort_values(by="product_id")
3,415
Find Products with Three Consecutive Digits
Easy
<p>Table: <code>Products</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | product_id | int | | name | varchar | +-------------+---------+ product_id is the unique key for this table. Each row of this table contains the ID and name of a product. </pre> <p>Write a solution to find all <strong>products</strong> whose names contain a <strong>sequence of exactly three consecutive digits in a row</strong>.&nbsp;</p> <p>Return <em>the result table ordered by</em> <code>product_id</code> <em>in <strong>ascending</strong> order.</em></p> <p>The result format is in the following example.</p> <p><strong>Note</strong> that the name may contain multiple such sequences, but each should have length three.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>products table:</p> <pre class="example-io"> +-------------+--------------------+ | product_id | name | +-------------+--------------------+ | 1 | ABC123XYZ | | 2 | A12B34C | | 3 | Product56789 | | 4 | NoDigitsHere | | 5 | 789Product | | 6 | Item003Description | | 7 | Product12X34 | +-------------+--------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+--------------------+ | product_id | name | +-------------+--------------------+ | 1 | ABC123XYZ | | 5 | 789Product | | 6 | Item003Description | +-------------+--------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>Product 1: ABC123XYZ contains the digits 123.</li> <li>Product 5: 789Product&nbsp;contains the digits 789.</li> <li>Product 6: Item003Description&nbsp;contains 003, which is exactly three digits.</li> </ul> <p><strong>Note:</strong></p> <ul> <li>Results are ordered by <code>product_id</code> in ascending order.</li> <li>Only products with exactly three consecutive digits in their names are included in the result.</li> </ul> </div>
Database
SQL
# Write your MySQL query statement below SELECT product_id, name FROM Products WHERE name REGEXP '(^|[^0-9])[0-9]{3}([^0-9]|$)' ORDER BY 1;
3,417
Zigzag Grid Traversal With Skip
Easy
<p>You are given an <code>m x n</code> 2D array <code>grid</code> of <strong>positive</strong> integers.</p> <p>Your task is to traverse <code>grid</code> in a <strong>zigzag</strong> pattern while skipping every <strong>alternate</strong> cell.</p> <p>Zigzag pattern traversal is defined as following the below actions:</p> <ul> <li>Start at the top-left cell <code>(0, 0)</code>.</li> <li>Move <em>right</em> within a row until the end of the row is reached.</li> <li>Drop down to the next row, then traverse <em>left</em> until the beginning of the row is reached.</li> <li>Continue <strong>alternating</strong> between right and left traversal until every row has been traversed.</li> </ul> <p><strong>Note </strong>that you <strong>must skip</strong> every <em>alternate</em> cell during the traversal.</p> <p>Return an array of integers <code>result</code> containing, <strong>in order</strong>, the value of the cells visited during the zigzag traversal with skips.</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,2],[3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,4]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example0.png" style="width: 200px; height: 200px;" /></strong></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[2,1],[2,1],[2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example1.png" style="width: 200px; height: 240px;" /></p> </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],[4,5,6],[7,8,9]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,5,7,9]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example2.png" style="width: 260px; height: 250px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == grid.length &lt;= 50</code></li> <li><code>2 &lt;= m == grid[i].length &lt;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 2500</code></li> </ul>
Array; Matrix; Simulation
C++
class Solution { public: vector<int> zigzagTraversal(vector<vector<int>>& grid) { vector<int> ans; bool ok = true; for (int i = 0; i < grid.size(); ++i) { if (i % 2 != 0) { ranges::reverse(grid[i]); } for (int x : grid[i]) { if (ok) { ans.push_back(x); } ok = !ok; } } return ans; } };
3,417
Zigzag Grid Traversal With Skip
Easy
<p>You are given an <code>m x n</code> 2D array <code>grid</code> of <strong>positive</strong> integers.</p> <p>Your task is to traverse <code>grid</code> in a <strong>zigzag</strong> pattern while skipping every <strong>alternate</strong> cell.</p> <p>Zigzag pattern traversal is defined as following the below actions:</p> <ul> <li>Start at the top-left cell <code>(0, 0)</code>.</li> <li>Move <em>right</em> within a row until the end of the row is reached.</li> <li>Drop down to the next row, then traverse <em>left</em> until the beginning of the row is reached.</li> <li>Continue <strong>alternating</strong> between right and left traversal until every row has been traversed.</li> </ul> <p><strong>Note </strong>that you <strong>must skip</strong> every <em>alternate</em> cell during the traversal.</p> <p>Return an array of integers <code>result</code> containing, <strong>in order</strong>, the value of the cells visited during the zigzag traversal with skips.</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,2],[3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,4]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example0.png" style="width: 200px; height: 200px;" /></strong></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[2,1],[2,1],[2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example1.png" style="width: 200px; height: 240px;" /></p> </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],[4,5,6],[7,8,9]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,5,7,9]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example2.png" style="width: 260px; height: 250px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == grid.length &lt;= 50</code></li> <li><code>2 &lt;= m == grid[i].length &lt;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 2500</code></li> </ul>
Array; Matrix; Simulation
Go
func zigzagTraversal(grid [][]int) (ans []int) { ok := true for i, row := range grid { if i%2 != 0 { slices.Reverse(row) } for _, x := range row { if ok { ans = append(ans, x) } ok = !ok } } return }
3,417
Zigzag Grid Traversal With Skip
Easy
<p>You are given an <code>m x n</code> 2D array <code>grid</code> of <strong>positive</strong> integers.</p> <p>Your task is to traverse <code>grid</code> in a <strong>zigzag</strong> pattern while skipping every <strong>alternate</strong> cell.</p> <p>Zigzag pattern traversal is defined as following the below actions:</p> <ul> <li>Start at the top-left cell <code>(0, 0)</code>.</li> <li>Move <em>right</em> within a row until the end of the row is reached.</li> <li>Drop down to the next row, then traverse <em>left</em> until the beginning of the row is reached.</li> <li>Continue <strong>alternating</strong> between right and left traversal until every row has been traversed.</li> </ul> <p><strong>Note </strong>that you <strong>must skip</strong> every <em>alternate</em> cell during the traversal.</p> <p>Return an array of integers <code>result</code> containing, <strong>in order</strong>, the value of the cells visited during the zigzag traversal with skips.</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,2],[3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,4]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example0.png" style="width: 200px; height: 200px;" /></strong></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[2,1],[2,1],[2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example1.png" style="width: 200px; height: 240px;" /></p> </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],[4,5,6],[7,8,9]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,5,7,9]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example2.png" style="width: 260px; height: 250px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == grid.length &lt;= 50</code></li> <li><code>2 &lt;= m == grid[i].length &lt;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 2500</code></li> </ul>
Array; Matrix; Simulation
Java
class Solution { public List<Integer> zigzagTraversal(int[][] grid) { boolean ok = true; List<Integer> ans = new ArrayList<>(); for (int i = 0; i < grid.length; ++i) { if (i % 2 == 1) { reverse(grid[i]); } for (int x : grid[i]) { if (ok) { ans.add(x); } ok = !ok; } } return ans; } private void reverse(int[] nums) { for (int i = 0, j = nums.length - 1; i < j; ++i, --j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } } }
3,417
Zigzag Grid Traversal With Skip
Easy
<p>You are given an <code>m x n</code> 2D array <code>grid</code> of <strong>positive</strong> integers.</p> <p>Your task is to traverse <code>grid</code> in a <strong>zigzag</strong> pattern while skipping every <strong>alternate</strong> cell.</p> <p>Zigzag pattern traversal is defined as following the below actions:</p> <ul> <li>Start at the top-left cell <code>(0, 0)</code>.</li> <li>Move <em>right</em> within a row until the end of the row is reached.</li> <li>Drop down to the next row, then traverse <em>left</em> until the beginning of the row is reached.</li> <li>Continue <strong>alternating</strong> between right and left traversal until every row has been traversed.</li> </ul> <p><strong>Note </strong>that you <strong>must skip</strong> every <em>alternate</em> cell during the traversal.</p> <p>Return an array of integers <code>result</code> containing, <strong>in order</strong>, the value of the cells visited during the zigzag traversal with skips.</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,2],[3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,4]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example0.png" style="width: 200px; height: 200px;" /></strong></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[2,1],[2,1],[2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example1.png" style="width: 200px; height: 240px;" /></p> </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],[4,5,6],[7,8,9]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,5,7,9]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example2.png" style="width: 260px; height: 250px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == grid.length &lt;= 50</code></li> <li><code>2 &lt;= m == grid[i].length &lt;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 2500</code></li> </ul>
Array; Matrix; Simulation
Python
class Solution: def zigzagTraversal(self, grid: List[List[int]]) -> List[int]: ok = True ans = [] for i, row in enumerate(grid): if i % 2: row.reverse() for x in row: if ok: ans.append(x) ok = not ok return ans
3,417
Zigzag Grid Traversal With Skip
Easy
<p>You are given an <code>m x n</code> 2D array <code>grid</code> of <strong>positive</strong> integers.</p> <p>Your task is to traverse <code>grid</code> in a <strong>zigzag</strong> pattern while skipping every <strong>alternate</strong> cell.</p> <p>Zigzag pattern traversal is defined as following the below actions:</p> <ul> <li>Start at the top-left cell <code>(0, 0)</code>.</li> <li>Move <em>right</em> within a row until the end of the row is reached.</li> <li>Drop down to the next row, then traverse <em>left</em> until the beginning of the row is reached.</li> <li>Continue <strong>alternating</strong> between right and left traversal until every row has been traversed.</li> </ul> <p><strong>Note </strong>that you <strong>must skip</strong> every <em>alternate</em> cell during the traversal.</p> <p>Return an array of integers <code>result</code> containing, <strong>in order</strong>, the value of the cells visited during the zigzag traversal with skips.</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,2],[3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,4]</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example0.png" style="width: 200px; height: 200px;" /></strong></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[2,1],[2,1],[2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1,2]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example1.png" style="width: 200px; height: 240px;" /></p> </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],[4,5,6],[7,8,9]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3,5,7,9]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3417.Zigzag%20Grid%20Traversal%20With%20Skip/images/4012_example2.png" style="width: 260px; height: 250px;" /></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == grid.length &lt;= 50</code></li> <li><code>2 &lt;= m == grid[i].length &lt;= 50</code></li> <li><code>1 &lt;= grid[i][j] &lt;= 2500</code></li> </ul>
Array; Matrix; Simulation
TypeScript
function zigzagTraversal(grid: number[][]): number[] { const ans: number[] = []; let ok: boolean = true; for (let i = 0; i < grid.length; ++i) { if (i % 2) { grid[i].reverse(); } for (const x of grid[i]) { if (ok) { ans.push(x); } ok = !ok; } } return ans; }
3,418
Maximum Amount of Money Robot Can Earn
Medium
<p>You are given an <code>m x n</code> grid. A robot starts at the top-left corner of the grid <code>(0, 0)</code> and wants to reach the bottom-right corner <code>(m - 1, n - 1)</code>. The robot can move either right or down at any point in time.</p> <p>The grid contains a value <code>coins[i][j]</code> in each cell:</p> <ul> <li>If <code>coins[i][j] &gt;= 0</code>, the robot gains that many coins.</li> <li>If <code>coins[i][j] &lt; 0</code>, the robot encounters a robber, and the robber steals the <strong>absolute</strong> value of <code>coins[i][j]</code> coins.</li> </ul> <p>The robot has a special ability to <strong>neutralize robbers</strong> in at most <strong>2 cells</strong> on its path, preventing them from stealing coins in those cells.</p> <p><strong>Note:</strong> The robot&#39;s total coins can be negative.</p> <p>Return the <strong>maximum</strong> profit the robot can gain on the route.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coins = [[0,1,-1],[1,-2,3],[2,-3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>An optimal path for maximum coins is:</p> <ol> <li>Start at <code>(0, 0)</code> with <code>0</code> coins (total coins = <code>0</code>).</li> <li>Move to <code>(0, 1)</code>, gaining <code>1</code> coin (total coins = <code>0 + 1 = 1</code>).</li> <li>Move to <code>(1, 1)</code>, where there&#39;s a robber stealing <code>2</code> coins. The robot uses one neutralization here, avoiding the robbery (total coins = <code>1</code>).</li> <li>Move to <code>(1, 2)</code>, gaining <code>3</code> coins (total coins = <code>1 + 3 = 4</code>).</li> <li>Move to <code>(2, 2)</code>, gaining <code>4</code> coins (total coins = <code>4 + 4 = 8</code>).</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coins = [[10,10,10],[10,10,10]]</span></p> <p><strong>Output:</strong> <span class="example-io">40</span></p> <p><strong>Explanation:</strong></p> <p>An optimal path for maximum coins is:</p> <ol> <li>Start at <code>(0, 0)</code> with <code>10</code> coins (total coins = <code>10</code>).</li> <li>Move to <code>(0, 1)</code>, gaining <code>10</code> coins (total coins = <code>10 + 10 = 20</code>).</li> <li>Move to <code>(0, 2)</code>, gaining another <code>10</code> coins (total coins = <code>20 + 10 = 30</code>).</li> <li>Move to <code>(1, 2)</code>, gaining the final <code>10</code> coins (total coins = <code>30 + 10 = 40</code>).</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == coins.length</code></li> <li><code>n == coins[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>-1000 &lt;= coins[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
C++
class Solution { public: int maximumAmount(vector<vector<int>>& coins) { int m = coins.size(), n = coins[0].size(); vector<vector<vector<int>>> f(m, vector<vector<int>>(n, vector<int>(3, -1))); auto dfs = [&](this auto&& dfs, int i, int j, int k) -> int { if (i >= m || j >= n) { return INT_MIN / 2; } if (f[i][j][k] != -1) { return f[i][j][k]; } if (i == m - 1 && j == n - 1) { return k > 0 ? max(0, coins[i][j]) : coins[i][j]; } int ans = coins[i][j] + max(dfs(i + 1, j, k), dfs(i, j + 1, k)); if (coins[i][j] < 0 && k > 0) { ans = max({ans, dfs(i + 1, j, k - 1), dfs(i, j + 1, k - 1)}); } return f[i][j][k] = ans; }; return dfs(0, 0, 2); } };
3,418
Maximum Amount of Money Robot Can Earn
Medium
<p>You are given an <code>m x n</code> grid. A robot starts at the top-left corner of the grid <code>(0, 0)</code> and wants to reach the bottom-right corner <code>(m - 1, n - 1)</code>. The robot can move either right or down at any point in time.</p> <p>The grid contains a value <code>coins[i][j]</code> in each cell:</p> <ul> <li>If <code>coins[i][j] &gt;= 0</code>, the robot gains that many coins.</li> <li>If <code>coins[i][j] &lt; 0</code>, the robot encounters a robber, and the robber steals the <strong>absolute</strong> value of <code>coins[i][j]</code> coins.</li> </ul> <p>The robot has a special ability to <strong>neutralize robbers</strong> in at most <strong>2 cells</strong> on its path, preventing them from stealing coins in those cells.</p> <p><strong>Note:</strong> The robot&#39;s total coins can be negative.</p> <p>Return the <strong>maximum</strong> profit the robot can gain on the route.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coins = [[0,1,-1],[1,-2,3],[2,-3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>An optimal path for maximum coins is:</p> <ol> <li>Start at <code>(0, 0)</code> with <code>0</code> coins (total coins = <code>0</code>).</li> <li>Move to <code>(0, 1)</code>, gaining <code>1</code> coin (total coins = <code>0 + 1 = 1</code>).</li> <li>Move to <code>(1, 1)</code>, where there&#39;s a robber stealing <code>2</code> coins. The robot uses one neutralization here, avoiding the robbery (total coins = <code>1</code>).</li> <li>Move to <code>(1, 2)</code>, gaining <code>3</code> coins (total coins = <code>1 + 3 = 4</code>).</li> <li>Move to <code>(2, 2)</code>, gaining <code>4</code> coins (total coins = <code>4 + 4 = 8</code>).</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coins = [[10,10,10],[10,10,10]]</span></p> <p><strong>Output:</strong> <span class="example-io">40</span></p> <p><strong>Explanation:</strong></p> <p>An optimal path for maximum coins is:</p> <ol> <li>Start at <code>(0, 0)</code> with <code>10</code> coins (total coins = <code>10</code>).</li> <li>Move to <code>(0, 1)</code>, gaining <code>10</code> coins (total coins = <code>10 + 10 = 20</code>).</li> <li>Move to <code>(0, 2)</code>, gaining another <code>10</code> coins (total coins = <code>20 + 10 = 30</code>).</li> <li>Move to <code>(1, 2)</code>, gaining the final <code>10</code> coins (total coins = <code>30 + 10 = 40</code>).</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == coins.length</code></li> <li><code>n == coins[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>-1000 &lt;= coins[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
Go
func maximumAmount(coins [][]int) int { m, n := len(coins), len(coins[0]) f := make([][][]int, m) for i := range f { f[i] = make([][]int, n) for j := range f[i] { f[i][j] = make([]int, 3) for k := range f[i][j] { f[i][j][k] = math.MinInt32 } } } var dfs func(i, j, k int) int dfs = func(i, j, k int) int { if i >= m || j >= n { return math.MinInt32 / 2 } if f[i][j][k] != math.MinInt32 { return f[i][j][k] } if i == m-1 && j == n-1 { if k > 0 { return max(0, coins[i][j]) } return coins[i][j] } ans := coins[i][j] + max(dfs(i+1, j, k), dfs(i, j+1, k)) if coins[i][j] < 0 && k > 0 { ans = max(ans, max(dfs(i+1, j, k-1), dfs(i, j+1, k-1))) } f[i][j][k] = ans return ans } return dfs(0, 0, 2) }
3,418
Maximum Amount of Money Robot Can Earn
Medium
<p>You are given an <code>m x n</code> grid. A robot starts at the top-left corner of the grid <code>(0, 0)</code> and wants to reach the bottom-right corner <code>(m - 1, n - 1)</code>. The robot can move either right or down at any point in time.</p> <p>The grid contains a value <code>coins[i][j]</code> in each cell:</p> <ul> <li>If <code>coins[i][j] &gt;= 0</code>, the robot gains that many coins.</li> <li>If <code>coins[i][j] &lt; 0</code>, the robot encounters a robber, and the robber steals the <strong>absolute</strong> value of <code>coins[i][j]</code> coins.</li> </ul> <p>The robot has a special ability to <strong>neutralize robbers</strong> in at most <strong>2 cells</strong> on its path, preventing them from stealing coins in those cells.</p> <p><strong>Note:</strong> The robot&#39;s total coins can be negative.</p> <p>Return the <strong>maximum</strong> profit the robot can gain on the route.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coins = [[0,1,-1],[1,-2,3],[2,-3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>An optimal path for maximum coins is:</p> <ol> <li>Start at <code>(0, 0)</code> with <code>0</code> coins (total coins = <code>0</code>).</li> <li>Move to <code>(0, 1)</code>, gaining <code>1</code> coin (total coins = <code>0 + 1 = 1</code>).</li> <li>Move to <code>(1, 1)</code>, where there&#39;s a robber stealing <code>2</code> coins. The robot uses one neutralization here, avoiding the robbery (total coins = <code>1</code>).</li> <li>Move to <code>(1, 2)</code>, gaining <code>3</code> coins (total coins = <code>1 + 3 = 4</code>).</li> <li>Move to <code>(2, 2)</code>, gaining <code>4</code> coins (total coins = <code>4 + 4 = 8</code>).</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coins = [[10,10,10],[10,10,10]]</span></p> <p><strong>Output:</strong> <span class="example-io">40</span></p> <p><strong>Explanation:</strong></p> <p>An optimal path for maximum coins is:</p> <ol> <li>Start at <code>(0, 0)</code> with <code>10</code> coins (total coins = <code>10</code>).</li> <li>Move to <code>(0, 1)</code>, gaining <code>10</code> coins (total coins = <code>10 + 10 = 20</code>).</li> <li>Move to <code>(0, 2)</code>, gaining another <code>10</code> coins (total coins = <code>20 + 10 = 30</code>).</li> <li>Move to <code>(1, 2)</code>, gaining the final <code>10</code> coins (total coins = <code>30 + 10 = 40</code>).</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == coins.length</code></li> <li><code>n == coins[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>-1000 &lt;= coins[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
Java
class Solution { private Integer[][][] f; private int[][] coins; private int m; private int n; public int maximumAmount(int[][] coins) { m = coins.length; n = coins[0].length; this.coins = coins; f = new Integer[m][n][3]; return dfs(0, 0, 2); } private int dfs(int i, int j, int k) { if (i >= m || j >= n) { return Integer.MIN_VALUE / 2; } if (f[i][j][k] != null) { return f[i][j][k]; } if (i == m - 1 && j == n - 1) { return k > 0 ? Math.max(0, coins[i][j]) : coins[i][j]; } int ans = coins[i][j] + Math.max(dfs(i + 1, j, k), dfs(i, j + 1, k)); if (coins[i][j] < 0 && k > 0) { ans = Math.max(ans, Math.max(dfs(i + 1, j, k - 1), dfs(i, j + 1, k - 1))); } return f[i][j][k] = ans; } }
3,418
Maximum Amount of Money Robot Can Earn
Medium
<p>You are given an <code>m x n</code> grid. A robot starts at the top-left corner of the grid <code>(0, 0)</code> and wants to reach the bottom-right corner <code>(m - 1, n - 1)</code>. The robot can move either right or down at any point in time.</p> <p>The grid contains a value <code>coins[i][j]</code> in each cell:</p> <ul> <li>If <code>coins[i][j] &gt;= 0</code>, the robot gains that many coins.</li> <li>If <code>coins[i][j] &lt; 0</code>, the robot encounters a robber, and the robber steals the <strong>absolute</strong> value of <code>coins[i][j]</code> coins.</li> </ul> <p>The robot has a special ability to <strong>neutralize robbers</strong> in at most <strong>2 cells</strong> on its path, preventing them from stealing coins in those cells.</p> <p><strong>Note:</strong> The robot&#39;s total coins can be negative.</p> <p>Return the <strong>maximum</strong> profit the robot can gain on the route.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coins = [[0,1,-1],[1,-2,3],[2,-3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>An optimal path for maximum coins is:</p> <ol> <li>Start at <code>(0, 0)</code> with <code>0</code> coins (total coins = <code>0</code>).</li> <li>Move to <code>(0, 1)</code>, gaining <code>1</code> coin (total coins = <code>0 + 1 = 1</code>).</li> <li>Move to <code>(1, 1)</code>, where there&#39;s a robber stealing <code>2</code> coins. The robot uses one neutralization here, avoiding the robbery (total coins = <code>1</code>).</li> <li>Move to <code>(1, 2)</code>, gaining <code>3</code> coins (total coins = <code>1 + 3 = 4</code>).</li> <li>Move to <code>(2, 2)</code>, gaining <code>4</code> coins (total coins = <code>4 + 4 = 8</code>).</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coins = [[10,10,10],[10,10,10]]</span></p> <p><strong>Output:</strong> <span class="example-io">40</span></p> <p><strong>Explanation:</strong></p> <p>An optimal path for maximum coins is:</p> <ol> <li>Start at <code>(0, 0)</code> with <code>10</code> coins (total coins = <code>10</code>).</li> <li>Move to <code>(0, 1)</code>, gaining <code>10</code> coins (total coins = <code>10 + 10 = 20</code>).</li> <li>Move to <code>(0, 2)</code>, gaining another <code>10</code> coins (total coins = <code>20 + 10 = 30</code>).</li> <li>Move to <code>(1, 2)</code>, gaining the final <code>10</code> coins (total coins = <code>30 + 10 = 40</code>).</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == coins.length</code></li> <li><code>n == coins[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>-1000 &lt;= coins[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
Python
class Solution: def maximumAmount(self, coins: List[List[int]]) -> int: @cache def dfs(i: int, j: int, k: int) -> int: if i >= m or j >= n: return -inf if i == m - 1 and j == n - 1: return max(coins[i][j], 0) if k else coins[i][j] ans = coins[i][j] + max(dfs(i + 1, j, k), dfs(i, j + 1, k)) if coins[i][j] < 0 and k: ans = max(ans, dfs(i + 1, j, k - 1), dfs(i, j + 1, k - 1)) return ans m, n = len(coins), len(coins[0]) return dfs(0, 0, 2)
3,418
Maximum Amount of Money Robot Can Earn
Medium
<p>You are given an <code>m x n</code> grid. A robot starts at the top-left corner of the grid <code>(0, 0)</code> and wants to reach the bottom-right corner <code>(m - 1, n - 1)</code>. The robot can move either right or down at any point in time.</p> <p>The grid contains a value <code>coins[i][j]</code> in each cell:</p> <ul> <li>If <code>coins[i][j] &gt;= 0</code>, the robot gains that many coins.</li> <li>If <code>coins[i][j] &lt; 0</code>, the robot encounters a robber, and the robber steals the <strong>absolute</strong> value of <code>coins[i][j]</code> coins.</li> </ul> <p>The robot has a special ability to <strong>neutralize robbers</strong> in at most <strong>2 cells</strong> on its path, preventing them from stealing coins in those cells.</p> <p><strong>Note:</strong> The robot&#39;s total coins can be negative.</p> <p>Return the <strong>maximum</strong> profit the robot can gain on the route.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coins = [[0,1,-1],[1,-2,3],[2,-3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p>An optimal path for maximum coins is:</p> <ol> <li>Start at <code>(0, 0)</code> with <code>0</code> coins (total coins = <code>0</code>).</li> <li>Move to <code>(0, 1)</code>, gaining <code>1</code> coin (total coins = <code>0 + 1 = 1</code>).</li> <li>Move to <code>(1, 1)</code>, where there&#39;s a robber stealing <code>2</code> coins. The robot uses one neutralization here, avoiding the robbery (total coins = <code>1</code>).</li> <li>Move to <code>(1, 2)</code>, gaining <code>3</code> coins (total coins = <code>1 + 3 = 4</code>).</li> <li>Move to <code>(2, 2)</code>, gaining <code>4</code> coins (total coins = <code>4 + 4 = 8</code>).</li> </ol> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">coins = [[10,10,10],[10,10,10]]</span></p> <p><strong>Output:</strong> <span class="example-io">40</span></p> <p><strong>Explanation:</strong></p> <p>An optimal path for maximum coins is:</p> <ol> <li>Start at <code>(0, 0)</code> with <code>10</code> coins (total coins = <code>10</code>).</li> <li>Move to <code>(0, 1)</code>, gaining <code>10</code> coins (total coins = <code>10 + 10 = 20</code>).</li> <li>Move to <code>(0, 2)</code>, gaining another <code>10</code> coins (total coins = <code>20 + 10 = 30</code>).</li> <li>Move to <code>(1, 2)</code>, gaining the final <code>10</code> coins (total coins = <code>30 + 10 = 40</code>).</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == coins.length</code></li> <li><code>n == coins[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 500</code></li> <li><code>-1000 &lt;= coins[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
TypeScript
function maximumAmount(coins: number[][]): number { const [m, n] = [coins.length, coins[0].length]; const f = Array.from({ length: m }, () => Array.from({ length: n }, () => Array(3).fill(-Infinity)), ); const dfs = (i: number, j: number, k: number): number => { if (i >= m || j >= n) { return -Infinity; } if (f[i][j][k] !== -Infinity) { return f[i][j][k]; } if (i === m - 1 && j === n - 1) { return k > 0 ? Math.max(0, coins[i][j]) : coins[i][j]; } let ans = coins[i][j] + Math.max(dfs(i + 1, j, k), dfs(i, j + 1, k)); if (coins[i][j] < 0 && k > 0) { ans = Math.max(ans, dfs(i + 1, j, k - 1), dfs(i, j + 1, k - 1)); } return (f[i][j][k] = ans); }; return dfs(0, 0, 2); }
3,421
Find Students Who Improved
Medium
<p>Table: <code>Scores</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | student_id | int | | subject | varchar | | score | int | | exam_date | varchar | +-------------+---------+ (student_id, subject, exam_date) is the primary key for this table. Each row contains information about a student&#39;s score in a specific subject on a particular exam date. score is between 0 and 100 (inclusive). </pre> <p>Write a solution to find the <strong>students who have shown improvement</strong>. A student is considered to have shown improvement if they meet <strong>both</strong> of these conditions:</p> <ul> <li>Have taken exams in the <strong>same subject</strong> on at least two different dates</li> <li>Their <strong>latest score</strong> in that subject is <strong>higher</strong> than their <strong>first score</strong></li> </ul> <p>Return <em>the result table</em>&nbsp;<em>ordered by</em> <code>student_id,</code> <code>subject</code> <em>in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Scores table:</p> <pre class="example-io"> +------------+----------+-------+------------+ | student_id | subject | score | exam_date | +------------+----------+-------+------------+ | 101 | Math | 70 | 2023-01-15 | | 101 | Math | 85 | 2023-02-15 | | 101 | Physics | 65 | 2023-01-15 | | 101 | Physics | 60 | 2023-02-15 | | 102 | Math | 80 | 2023-01-15 | | 102 | Math | 85 | 2023-02-15 | | 103 | Math | 90 | 2023-01-15 | | 104 | Physics | 75 | 2023-01-15 | | 104 | Physics | 85 | 2023-02-15 | +------------+----------+-------+------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------+----------+-------------+--------------+ | student_id | subject | first_score | latest_score | +------------+----------+-------------+--------------+ | 101 | Math | 70 | 85 | | 102 | Math | 80 | 85 | | 104 | Physics | 75 | 85 | +------------+----------+-------------+--------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>Student 101 in Math: Improved from 70 to 85</li> <li>Student 101 in Physics: No improvement (dropped from 65 to 60)</li> <li>Student 102 in Math: Improved from 80 to 85</li> <li>Student 103 in Math: Only one exam, not eligible</li> <li>Student 104 in Physics: Improved from 75 to 85</li> </ul> <p>Result table is ordered by student_id, subject.</p> </div>
Database
SQL
WITH RankedScores AS ( SELECT student_id, subject, score, exam_date, ROW_NUMBER() OVER ( PARTITION BY student_id, subject ORDER BY exam_date ASC ) AS rn_first, ROW_NUMBER() OVER ( PARTITION BY student_id, subject ORDER BY exam_date DESC ) AS rn_latest FROM Scores ), FirstAndLatestScores AS ( SELECT f.student_id, f.subject, f.score AS first_score, l.score AS latest_score FROM RankedScores f JOIN RankedScores l ON f.student_id = l.student_id AND f.subject = l.subject WHERE f.rn_first = 1 AND l.rn_latest = 1 ) SELECT * FROM FirstAndLatestScores WHERE latest_score > first_score ORDER BY 1, 2;
3,422
Minimum Operations to Make Subarray Elements Equal
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. You can perform the following operation any number of times:</p> <ul> <li>Increase or decrease any element of <code>nums</code> by 1.</li> </ul> <p>Return the <strong>minimum</strong> number of operations required to ensure that <strong>at least</strong> one <span data-keyword="subarray">subarray</span> of size <code>k</code> in <code>nums</code> has all elements equal.</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 = [4,-3,2,1,-4,6], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Use 4 operations to add 4 to <code>nums[1]</code>. The resulting array is <span class="example-io"><code>[4, 1, 2, 1, -4, 6]</code>.</span></li> <li><span class="example-io">Use 1 operation to subtract 1 from <code>nums[2]</code>. The resulting array is <code>[4, 1, 1, 1, -4, 6]</code>.</span></li> <li><span class="example-io">The array now contains a subarray <code>[1, 1, 1]</code> of size <code>k = 3</code> with all elements equal. Hence, the answer is 5.</span></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-2,-2,3,1,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p>The subarray <code>[-2, -2]</code> of size <code>k = 2</code> already contains all equal elements, so no operations are needed. Hence, the answer is 0.</p> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>2 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Math; Sliding Window; Heap (Priority Queue)
C++
class Solution { public: long long minOperations(vector<int>& nums, int k) { multiset<int> l, r; long long s1 = 0, s2 = 0, ans = 1e18; for (int i = 0; i < nums.size(); ++i) { l.insert(nums[i]); s1 += nums[i]; int y = *l.rbegin(); l.erase(l.find(y)); s1 -= y; r.insert(y); s2 += y; if (r.size() - l.size() > 1) { y = *r.begin(); r.erase(r.find(y)); s2 -= y; l.insert(y); s1 += y; } if (i >= k - 1) { long long x = *r.begin(); ans = min(ans, s2 - x * (int) r.size() + x * (int) l.size() - s1); int j = i - k + 1; if (r.contains(nums[j])) { r.erase(r.find(nums[j])); s2 -= nums[j]; } else { l.erase(l.find(nums[j])); s1 -= nums[j]; } } } return ans; } };
3,422
Minimum Operations to Make Subarray Elements Equal
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. You can perform the following operation any number of times:</p> <ul> <li>Increase or decrease any element of <code>nums</code> by 1.</li> </ul> <p>Return the <strong>minimum</strong> number of operations required to ensure that <strong>at least</strong> one <span data-keyword="subarray">subarray</span> of size <code>k</code> in <code>nums</code> has all elements equal.</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 = [4,-3,2,1,-4,6], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Use 4 operations to add 4 to <code>nums[1]</code>. The resulting array is <span class="example-io"><code>[4, 1, 2, 1, -4, 6]</code>.</span></li> <li><span class="example-io">Use 1 operation to subtract 1 from <code>nums[2]</code>. The resulting array is <code>[4, 1, 1, 1, -4, 6]</code>.</span></li> <li><span class="example-io">The array now contains a subarray <code>[1, 1, 1]</code> of size <code>k = 3</code> with all elements equal. Hence, the answer is 5.</span></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-2,-2,3,1,4], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li> <p>The subarray <code>[-2, -2]</code> of size <code>k = 2</code> already contains all equal elements, so no operations are needed. Hence, the answer is 0.</p> </li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>2 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Math; Sliding Window; Heap (Priority Queue)
Go
func minOperations(nums []int, k int) int64 { l := redblacktree.New[int, int]() r := redblacktree.New[int, int]() merge := func(st *redblacktree.Tree[int, int], x, v int) { c, _ := st.Get(x) if c+v == 0 { st.Remove(x) } else { st.Put(x, c+v) } } var s1, s2, sz1, sz2 int ans := math.MaxInt64 for i, x := range nums { merge(l, x, 1) s1 += x y := l.Right().Key merge(l, y, -1) s1 -= y merge(r, y, 1) s2 += y sz2++ if sz2-sz1 > 1 { y = r.Left().Key merge(r, y, -1) s2 -= y sz2-- merge(l, y, 1) s1 += y sz1++ } if j := i - k + 1; j >= 0 { ans = min(ans, s2-r.Left().Key*sz2+r.Left().Key*sz1-s1) if _, ok := r.Get(nums[j]); ok { merge(r, nums[j], -1) s2 -= nums[j] sz2-- } else { merge(l, nums[j], -1) s1 -= nums[j] sz1-- } } } return int64(ans) }