id
int64
1
3.71k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
3,277
Maximum XOR Score Subarray Queries
Hard
<p>You are given an array <code>nums</code> of <code>n</code> integers, and a 2D integer array <code>queries</code> of size <code>q</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>For each query, you must find the <strong>maximum XOR score</strong> of any <span data-keyword="subarray">subarray</span> of <code>nums[l<sub>i</sub>..r<sub>i</sub>]</code>.</p> <p>The <strong>XOR score</strong> of an array <code>a</code> is found by repeatedly applying the following operations on <code>a</code> so that only one element remains, that is the <strong>score</strong>:</p> <ul> <li>Simultaneously replace <code>a[i]</code> with <code>a[i] XOR a[i + 1]</code> for all indices <code>i</code> except the last one.</li> <li>Remove the last element of <code>a</code>.</li> </ul> <p>Return an array <code>answer</code> of size <code>q</code> where <code>answer[i]</code> is the answer to query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,8,4,32,16,1], queries = [[0,2],[1,4],[0,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">[12,60,60]</span></p> <p><strong>Explanation:</strong></p> <p>In the first query, <code>nums[0..2]</code> has 6 subarrays <code>[2]</code>, <code>[8]</code>, <code>[4]</code>, <code>[2, 8]</code>, <code>[8, 4]</code>, and <code>[2, 8, 4]</code> each with a respective XOR score of 2, 8, 4, 10, 12, and 6. The answer for the query is 12, the largest of all XOR scores.</p> <p>In the second query, the subarray of <code>nums[1..4]</code> with the largest XOR score is <code>nums[1..4]</code> with a score of 60.</p> <p>In the third query, the subarray of <code>nums[0..5]</code> with the largest XOR score is <code>nums[1..4]</code> with a score of 60.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,7,3,2,8,5,1], queries = [[0,3],[1,5],[2,4],[2,6],[5,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">[7,14,11,14,5]</span></p> <p><strong>Explanation:</strong></p> <table height="70" width="472"> <thead> <tr> <th>Index</th> <th>nums[l<sub>i</sub>..r<sub>i</sub>]</th> <th>Maximum XOR Score Subarray</th> <th>Maximum Subarray XOR Score</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>[0, 7, 3, 2]</td> <td>[7]</td> <td>7</td> </tr> <tr> <td>1</td> <td>[7, 3, 2, 8, 5]</td> <td>[7, 3, 2, 8]</td> <td>14</td> </tr> <tr> <td>2</td> <td>[3, 2, 8]</td> <td>[3, 2, 8]</td> <td>11</td> </tr> <tr> <td>3</td> <td>[3, 2, 8, 5, 1]</td> <td>[2, 8, 5, 1]</td> <td>14</td> </tr> <tr> <td>4</td> <td>[5, 1]</td> <td>[5]</td> <td>5</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 2000</code></li> <li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= q == queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2 </code></li> <li><code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt;= n - 1</code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: vector<int> maximumSubarrayXor(vector<int>& nums, vector<vector<int>>& queries) { int n = nums.size(); vector<vector<int>> f(n, vector<int>(n)); vector<vector<int>> g(n, vector<int>(n)); for (int i = n - 1; i >= 0; --i) { f[i][i] = nums[i]; g[i][i] = nums[i]; for (int j = i + 1; j < n; ++j) { f[i][j] = f[i][j - 1] ^ f[i + 1][j]; g[i][j] = max({f[i][j], g[i][j - 1], g[i + 1][j]}); } } vector<int> ans; for (const auto& q : queries) { int l = q[0], r = q[1]; ans.push_back(g[l][r]); } return ans; } };
3,277
Maximum XOR Score Subarray Queries
Hard
<p>You are given an array <code>nums</code> of <code>n</code> integers, and a 2D integer array <code>queries</code> of size <code>q</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>For each query, you must find the <strong>maximum XOR score</strong> of any <span data-keyword="subarray">subarray</span> of <code>nums[l<sub>i</sub>..r<sub>i</sub>]</code>.</p> <p>The <strong>XOR score</strong> of an array <code>a</code> is found by repeatedly applying the following operations on <code>a</code> so that only one element remains, that is the <strong>score</strong>:</p> <ul> <li>Simultaneously replace <code>a[i]</code> with <code>a[i] XOR a[i + 1]</code> for all indices <code>i</code> except the last one.</li> <li>Remove the last element of <code>a</code>.</li> </ul> <p>Return an array <code>answer</code> of size <code>q</code> where <code>answer[i]</code> is the answer to query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,8,4,32,16,1], queries = [[0,2],[1,4],[0,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">[12,60,60]</span></p> <p><strong>Explanation:</strong></p> <p>In the first query, <code>nums[0..2]</code> has 6 subarrays <code>[2]</code>, <code>[8]</code>, <code>[4]</code>, <code>[2, 8]</code>, <code>[8, 4]</code>, and <code>[2, 8, 4]</code> each with a respective XOR score of 2, 8, 4, 10, 12, and 6. The answer for the query is 12, the largest of all XOR scores.</p> <p>In the second query, the subarray of <code>nums[1..4]</code> with the largest XOR score is <code>nums[1..4]</code> with a score of 60.</p> <p>In the third query, the subarray of <code>nums[0..5]</code> with the largest XOR score is <code>nums[1..4]</code> with a score of 60.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,7,3,2,8,5,1], queries = [[0,3],[1,5],[2,4],[2,6],[5,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">[7,14,11,14,5]</span></p> <p><strong>Explanation:</strong></p> <table height="70" width="472"> <thead> <tr> <th>Index</th> <th>nums[l<sub>i</sub>..r<sub>i</sub>]</th> <th>Maximum XOR Score Subarray</th> <th>Maximum Subarray XOR Score</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>[0, 7, 3, 2]</td> <td>[7]</td> <td>7</td> </tr> <tr> <td>1</td> <td>[7, 3, 2, 8, 5]</td> <td>[7, 3, 2, 8]</td> <td>14</td> </tr> <tr> <td>2</td> <td>[3, 2, 8]</td> <td>[3, 2, 8]</td> <td>11</td> </tr> <tr> <td>3</td> <td>[3, 2, 8, 5, 1]</td> <td>[2, 8, 5, 1]</td> <td>14</td> </tr> <tr> <td>4</td> <td>[5, 1]</td> <td>[5]</td> <td>5</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 2000</code></li> <li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= q == queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2 </code></li> <li><code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt;= n - 1</code></li> </ul>
Array; Dynamic Programming
Go
func maximumSubarrayXor(nums []int, queries [][]int) (ans []int) { n := len(nums) f := make([][]int, n) g := make([][]int, n) for i := 0; i < n; i++ { f[i] = make([]int, n) g[i] = make([]int, n) } for i := n - 1; i >= 0; i-- { f[i][i] = nums[i] g[i][i] = nums[i] for j := i + 1; j < n; j++ { f[i][j] = f[i][j-1] ^ f[i+1][j] g[i][j] = max(f[i][j], max(g[i][j-1], g[i+1][j])) } } for _, q := range queries { l, r := q[0], q[1] ans = append(ans, g[l][r]) } return }
3,277
Maximum XOR Score Subarray Queries
Hard
<p>You are given an array <code>nums</code> of <code>n</code> integers, and a 2D integer array <code>queries</code> of size <code>q</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>For each query, you must find the <strong>maximum XOR score</strong> of any <span data-keyword="subarray">subarray</span> of <code>nums[l<sub>i</sub>..r<sub>i</sub>]</code>.</p> <p>The <strong>XOR score</strong> of an array <code>a</code> is found by repeatedly applying the following operations on <code>a</code> so that only one element remains, that is the <strong>score</strong>:</p> <ul> <li>Simultaneously replace <code>a[i]</code> with <code>a[i] XOR a[i + 1]</code> for all indices <code>i</code> except the last one.</li> <li>Remove the last element of <code>a</code>.</li> </ul> <p>Return an array <code>answer</code> of size <code>q</code> where <code>answer[i]</code> is the answer to query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,8,4,32,16,1], queries = [[0,2],[1,4],[0,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">[12,60,60]</span></p> <p><strong>Explanation:</strong></p> <p>In the first query, <code>nums[0..2]</code> has 6 subarrays <code>[2]</code>, <code>[8]</code>, <code>[4]</code>, <code>[2, 8]</code>, <code>[8, 4]</code>, and <code>[2, 8, 4]</code> each with a respective XOR score of 2, 8, 4, 10, 12, and 6. The answer for the query is 12, the largest of all XOR scores.</p> <p>In the second query, the subarray of <code>nums[1..4]</code> with the largest XOR score is <code>nums[1..4]</code> with a score of 60.</p> <p>In the third query, the subarray of <code>nums[0..5]</code> with the largest XOR score is <code>nums[1..4]</code> with a score of 60.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,7,3,2,8,5,1], queries = [[0,3],[1,5],[2,4],[2,6],[5,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">[7,14,11,14,5]</span></p> <p><strong>Explanation:</strong></p> <table height="70" width="472"> <thead> <tr> <th>Index</th> <th>nums[l<sub>i</sub>..r<sub>i</sub>]</th> <th>Maximum XOR Score Subarray</th> <th>Maximum Subarray XOR Score</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>[0, 7, 3, 2]</td> <td>[7]</td> <td>7</td> </tr> <tr> <td>1</td> <td>[7, 3, 2, 8, 5]</td> <td>[7, 3, 2, 8]</td> <td>14</td> </tr> <tr> <td>2</td> <td>[3, 2, 8]</td> <td>[3, 2, 8]</td> <td>11</td> </tr> <tr> <td>3</td> <td>[3, 2, 8, 5, 1]</td> <td>[2, 8, 5, 1]</td> <td>14</td> </tr> <tr> <td>4</td> <td>[5, 1]</td> <td>[5]</td> <td>5</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 2000</code></li> <li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= q == queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2 </code></li> <li><code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt;= n - 1</code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int[] maximumSubarrayXor(int[] nums, int[][] queries) { int n = nums.length; int[][] f = new int[n][n]; int[][] g = new int[n][n]; for (int i = n - 1; i >= 0; --i) { f[i][i] = nums[i]; g[i][i] = nums[i]; for (int j = i + 1; j < n; ++j) { f[i][j] = f[i][j - 1] ^ f[i + 1][j]; g[i][j] = Math.max(f[i][j], Math.max(g[i][j - 1], g[i + 1][j])); } } int m = queries.length; int[] ans = new int[m]; for (int i = 0; i < m; ++i) { int l = queries[i][0], r = queries[i][1]; ans[i] = g[l][r]; } return ans; } }
3,277
Maximum XOR Score Subarray Queries
Hard
<p>You are given an array <code>nums</code> of <code>n</code> integers, and a 2D integer array <code>queries</code> of size <code>q</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>For each query, you must find the <strong>maximum XOR score</strong> of any <span data-keyword="subarray">subarray</span> of <code>nums[l<sub>i</sub>..r<sub>i</sub>]</code>.</p> <p>The <strong>XOR score</strong> of an array <code>a</code> is found by repeatedly applying the following operations on <code>a</code> so that only one element remains, that is the <strong>score</strong>:</p> <ul> <li>Simultaneously replace <code>a[i]</code> with <code>a[i] XOR a[i + 1]</code> for all indices <code>i</code> except the last one.</li> <li>Remove the last element of <code>a</code>.</li> </ul> <p>Return an array <code>answer</code> of size <code>q</code> where <code>answer[i]</code> is the answer to query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,8,4,32,16,1], queries = [[0,2],[1,4],[0,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">[12,60,60]</span></p> <p><strong>Explanation:</strong></p> <p>In the first query, <code>nums[0..2]</code> has 6 subarrays <code>[2]</code>, <code>[8]</code>, <code>[4]</code>, <code>[2, 8]</code>, <code>[8, 4]</code>, and <code>[2, 8, 4]</code> each with a respective XOR score of 2, 8, 4, 10, 12, and 6. The answer for the query is 12, the largest of all XOR scores.</p> <p>In the second query, the subarray of <code>nums[1..4]</code> with the largest XOR score is <code>nums[1..4]</code> with a score of 60.</p> <p>In the third query, the subarray of <code>nums[0..5]</code> with the largest XOR score is <code>nums[1..4]</code> with a score of 60.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,7,3,2,8,5,1], queries = [[0,3],[1,5],[2,4],[2,6],[5,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">[7,14,11,14,5]</span></p> <p><strong>Explanation:</strong></p> <table height="70" width="472"> <thead> <tr> <th>Index</th> <th>nums[l<sub>i</sub>..r<sub>i</sub>]</th> <th>Maximum XOR Score Subarray</th> <th>Maximum Subarray XOR Score</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>[0, 7, 3, 2]</td> <td>[7]</td> <td>7</td> </tr> <tr> <td>1</td> <td>[7, 3, 2, 8, 5]</td> <td>[7, 3, 2, 8]</td> <td>14</td> </tr> <tr> <td>2</td> <td>[3, 2, 8]</td> <td>[3, 2, 8]</td> <td>11</td> </tr> <tr> <td>3</td> <td>[3, 2, 8, 5, 1]</td> <td>[2, 8, 5, 1]</td> <td>14</td> </tr> <tr> <td>4</td> <td>[5, 1]</td> <td>[5]</td> <td>5</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 2000</code></li> <li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= q == queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2 </code></li> <li><code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt;= n - 1</code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maximumSubarrayXor( self, nums: List[int], queries: List[List[int]] ) -> List[int]: n = len(nums) f = [[0] * n for _ in range(n)] g = [[0] * n for _ in range(n)] for i in range(n - 1, -1, -1): f[i][i] = g[i][i] = nums[i] for j in range(i + 1, n): f[i][j] = f[i][j - 1] ^ f[i + 1][j] g[i][j] = max(f[i][j], g[i][j - 1], g[i + 1][j]) return [g[l][r] for l, r in queries]
3,277
Maximum XOR Score Subarray Queries
Hard
<p>You are given an array <code>nums</code> of <code>n</code> integers, and a 2D integer array <code>queries</code> of size <code>q</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>.</p> <p>For each query, you must find the <strong>maximum XOR score</strong> of any <span data-keyword="subarray">subarray</span> of <code>nums[l<sub>i</sub>..r<sub>i</sub>]</code>.</p> <p>The <strong>XOR score</strong> of an array <code>a</code> is found by repeatedly applying the following operations on <code>a</code> so that only one element remains, that is the <strong>score</strong>:</p> <ul> <li>Simultaneously replace <code>a[i]</code> with <code>a[i] XOR a[i + 1]</code> for all indices <code>i</code> except the last one.</li> <li>Remove the last element of <code>a</code>.</li> </ul> <p>Return an array <code>answer</code> of size <code>q</code> where <code>answer[i]</code> is the answer to query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,8,4,32,16,1], queries = [[0,2],[1,4],[0,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">[12,60,60]</span></p> <p><strong>Explanation:</strong></p> <p>In the first query, <code>nums[0..2]</code> has 6 subarrays <code>[2]</code>, <code>[8]</code>, <code>[4]</code>, <code>[2, 8]</code>, <code>[8, 4]</code>, and <code>[2, 8, 4]</code> each with a respective XOR score of 2, 8, 4, 10, 12, and 6. The answer for the query is 12, the largest of all XOR scores.</p> <p>In the second query, the subarray of <code>nums[1..4]</code> with the largest XOR score is <code>nums[1..4]</code> with a score of 60.</p> <p>In the third query, the subarray of <code>nums[0..5]</code> with the largest XOR score is <code>nums[1..4]</code> with a score of 60.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,7,3,2,8,5,1], queries = [[0,3],[1,5],[2,4],[2,6],[5,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">[7,14,11,14,5]</span></p> <p><strong>Explanation:</strong></p> <table height="70" width="472"> <thead> <tr> <th>Index</th> <th>nums[l<sub>i</sub>..r<sub>i</sub>]</th> <th>Maximum XOR Score Subarray</th> <th>Maximum Subarray XOR Score</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>[0, 7, 3, 2]</td> <td>[7]</td> <td>7</td> </tr> <tr> <td>1</td> <td>[7, 3, 2, 8, 5]</td> <td>[7, 3, 2, 8]</td> <td>14</td> </tr> <tr> <td>2</td> <td>[3, 2, 8]</td> <td>[3, 2, 8]</td> <td>11</td> </tr> <tr> <td>3</td> <td>[3, 2, 8, 5, 1]</td> <td>[2, 8, 5, 1]</td> <td>14</td> </tr> <tr> <td>4</td> <td>[5, 1]</td> <td>[5]</td> <td>5</td> </tr> </tbody> </table> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length &lt;= 2000</code></li> <li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= q == queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length == 2 </code></li> <li><code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt;= n - 1</code></li> </ul>
Array; Dynamic Programming
TypeScript
function maximumSubarrayXor(nums: number[], queries: number[][]): number[] { const n = nums.length; const f: number[][] = Array.from({ length: n }, () => Array(n).fill(0)); const g: number[][] = Array.from({ length: n }, () => Array(n).fill(0)); for (let i = n - 1; i >= 0; i--) { f[i][i] = nums[i]; g[i][i] = nums[i]; for (let j = i + 1; j < n; j++) { f[i][j] = f[i][j - 1] ^ f[i + 1][j]; g[i][j] = Math.max(f[i][j], Math.max(g[i][j - 1], g[i + 1][j])); } } return queries.map(([l, r]) => g[l][r]); }
3,278
Find Candidates for Data Scientist Position II
Medium
<p>Table: <font face="monospace"><code>Candidates</code></font></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | candidate_id | int | | skill | varchar | | proficiency | int | +--------------+---------+ (candidate_id, skill) is the unique key for this table. Each row includes candidate_id, skill, and proficiency level (1-5). </pre> <p>Table: <font face="monospace"><code>Projects</code></font></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | project_id | int | | skill | varchar | | importance | int | +--------------+---------+ (project_id, skill) is the primary key for this table. Each row includes project_id, required skill, and its importance (1-5) for the project. </pre> <p>Leetcode is staffing for multiple data science projects. Write a solution to find the <strong>best candidate</strong> for<strong> each project</strong> based on the following criteria:</p> <ol> <li>Candidates must have <strong>all</strong> the skills required for a project.</li> <li>Calculate a <strong>score</strong> for each candidate-project pair as follows: <ul> <li><strong>Start</strong> with <code>100</code> points</li> <li><strong>Add</strong> <code>10</code> points for each skill where <strong>proficiency &gt; importance</strong></li> <li><strong>Subtract</strong> <code>5</code> points for each skill where <strong>proficiency &lt; importance</strong></li> <li>If the candidate&#39;s skill proficiency <strong>equal </strong>to the project&#39;s skill importance, the score remains unchanged</li> </ul> </li> </ol> <p>Include only the top candidate (highest score) for each project. If there&rsquo;s a <strong>tie</strong>, choose the candidate with the <strong>lower</strong> <code>candidate_id</code>. If there is <strong>no suitable candidate</strong> for a project, <strong>do not return</strong>&nbsp;that project.</p> <p>Return a result table ordered by <code>project_id</code> in ascending order.</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><code>Candidates</code> table:</p> <pre class="example-io"> +--------------+-----------+-------------+ | candidate_id | skill | proficiency | +--------------+-----------+-------------+ | 101 | Python | 5 | | 101 | Tableau | 3 | | 101 | PostgreSQL| 4 | | 101 | TensorFlow| 2 | | 102 | Python | 4 | | 102 | Tableau | 5 | | 102 | PostgreSQL| 4 | | 102 | R | 4 | | 103 | Python | 3 | | 103 | Tableau | 5 | | 103 | PostgreSQL| 5 | | 103 | Spark | 4 | +--------------+-----------+-------------+ </pre> <p><code>Projects</code> table:</p> <pre class="example-io"> +-------------+-----------+------------+ | project_id | skill | importance | +-------------+-----------+------------+ | 501 | Python | 4 | | 501 | Tableau | 3 | | 501 | PostgreSQL| 5 | | 502 | Python | 3 | | 502 | Tableau | 4 | | 502 | R | 2 | +-------------+-----------+------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+--------------+-------+ | project_id | candidate_id | score | +-------------+--------------+-------+ | 501 | 101 | 105 | | 502 | 102 | 130 | +-------------+--------------+-------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>For Project 501, Candidate 101 has the highest score of 105. All other candidates have the same score but Candidate 101 has the lowest candidate_id among them.</li> <li>For Project 502, Candidate 102 has the highest score of 130.</li> </ul> <p>The output table is ordered by project_id in ascending order.</p> </div>
Database
SQL
WITH S AS ( SELECT candidate_id, project_id, COUNT(*) matched_skills, SUM( CASE WHEN proficiency > importance THEN 10 WHEN proficiency < importance THEN -5 ELSE 0 END ) + 100 AS score FROM Candidates JOIN Projects USING (skill) GROUP BY 1, 2 ), T AS ( SELECT project_id, COUNT(1) required_skills FROM Projects GROUP BY 1 ), P AS ( SELECT project_id, candidate_id, score, RANK() OVER ( PARTITION BY project_id ORDER BY score DESC, candidate_id ) rk FROM S JOIN T USING (project_id) WHERE matched_skills = required_skills ) SELECT project_id, candidate_id, score FROM P WHERE rk = 1 ORDER BY 1;
3,279
Maximum Total Area Occupied by Pistons
Hard
<p>There are several pistons in an old car engine, and we want to calculate the <strong>maximum</strong> possible area <strong>under</strong> the pistons.</p> <p>You are given:</p> <ul> <li>An integer <code>height</code>, representing the <strong>maximum</strong> height a piston can reach.</li> <li>An integer array <code>positions</code>, where <code>positions[i]</code> is the current position of piston <code>i</code>, which is equal to the current area <strong>under</strong> it.</li> <li>A string <code>directions</code>, where <code>directions[i]</code> is the current moving direction of piston <code>i</code>, <code>&#39;U&#39;</code> for up, and <code>&#39;D&#39;</code> for down.</li> </ul> <p>Each second:</p> <ul> <li>Every piston moves in its current direction 1 unit. e.g., if the direction is up, <code>positions[i]</code> is incremented by 1.</li> <li>If a piston has reached one of the ends, i.e., <code>positions[i] == 0</code> or <code>positions[i] == height</code>, its direction will change.</li> </ul> <p>Return the <em>maximum possible area</em> under all the pistons.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = 5, positions = [2,5], directions = &quot;UD&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The current position of the pistons has the maximum possible area under it.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = 6, positions = [0,0,6,3], directions = &quot;UUDU&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>After 3 seconds, the pistons will be in positions <code>[3, 3, 3, 6]</code>, which has the maximum possible area under it.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= height &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= positions.length == directions.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= positions[i] &lt;= height</code></li> <li><code>directions[i]</code> is either <code>&#39;U&#39;</code> or <code>&#39;D&#39;</code>.</li> </ul>
Array; Hash Table; String; Counting; Prefix Sum; Simulation
C++
class Solution { public: long long maxArea(int height, vector<int>& positions, string directions) { map<int, int> delta; int diff = 0; long long res = 0; for (int i = 0; i < positions.size(); ++i) { int pos = positions[i]; char dir = directions[i]; res += pos; if (dir == 'U') { ++diff; delta[height - pos] -= 2; delta[height * 2 - pos] += 2; } else { --diff; delta[pos] += 2; delta[height + pos] -= 2; } } long long ans = res; int pre = 0; for (const auto& [cur, d] : delta) { res += static_cast<long long>(cur - pre) * diff; pre = cur; diff += d; ans = max(ans, res); } return ans; } };
3,279
Maximum Total Area Occupied by Pistons
Hard
<p>There are several pistons in an old car engine, and we want to calculate the <strong>maximum</strong> possible area <strong>under</strong> the pistons.</p> <p>You are given:</p> <ul> <li>An integer <code>height</code>, representing the <strong>maximum</strong> height a piston can reach.</li> <li>An integer array <code>positions</code>, where <code>positions[i]</code> is the current position of piston <code>i</code>, which is equal to the current area <strong>under</strong> it.</li> <li>A string <code>directions</code>, where <code>directions[i]</code> is the current moving direction of piston <code>i</code>, <code>&#39;U&#39;</code> for up, and <code>&#39;D&#39;</code> for down.</li> </ul> <p>Each second:</p> <ul> <li>Every piston moves in its current direction 1 unit. e.g., if the direction is up, <code>positions[i]</code> is incremented by 1.</li> <li>If a piston has reached one of the ends, i.e., <code>positions[i] == 0</code> or <code>positions[i] == height</code>, its direction will change.</li> </ul> <p>Return the <em>maximum possible area</em> under all the pistons.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = 5, positions = [2,5], directions = &quot;UD&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The current position of the pistons has the maximum possible area under it.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = 6, positions = [0,0,6,3], directions = &quot;UUDU&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>After 3 seconds, the pistons will be in positions <code>[3, 3, 3, 6]</code>, which has the maximum possible area under it.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= height &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= positions.length == directions.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= positions[i] &lt;= height</code></li> <li><code>directions[i]</code> is either <code>&#39;U&#39;</code> or <code>&#39;D&#39;</code>.</li> </ul>
Array; Hash Table; String; Counting; Prefix Sum; Simulation
Go
func maxArea(height int, positions []int, directions string) int64 { delta := make(map[int]int) diff := 0 var res int64 = 0 for i, pos := range positions { dir := directions[i] res += int64(pos) if dir == 'U' { diff++ delta[height-pos] -= 2 delta[height*2-pos] += 2 } else { diff-- delta[pos] += 2 delta[height+pos] -= 2 } } ans := res pre := 0 keys := make([]int, 0, len(delta)) for key := range delta { keys = append(keys, key) } sort.Ints(keys) for _, cur := range keys { d := delta[cur] res += int64(cur-pre) * int64(diff) pre = cur diff += d ans = max(ans, res) } return ans }
3,279
Maximum Total Area Occupied by Pistons
Hard
<p>There are several pistons in an old car engine, and we want to calculate the <strong>maximum</strong> possible area <strong>under</strong> the pistons.</p> <p>You are given:</p> <ul> <li>An integer <code>height</code>, representing the <strong>maximum</strong> height a piston can reach.</li> <li>An integer array <code>positions</code>, where <code>positions[i]</code> is the current position of piston <code>i</code>, which is equal to the current area <strong>under</strong> it.</li> <li>A string <code>directions</code>, where <code>directions[i]</code> is the current moving direction of piston <code>i</code>, <code>&#39;U&#39;</code> for up, and <code>&#39;D&#39;</code> for down.</li> </ul> <p>Each second:</p> <ul> <li>Every piston moves in its current direction 1 unit. e.g., if the direction is up, <code>positions[i]</code> is incremented by 1.</li> <li>If a piston has reached one of the ends, i.e., <code>positions[i] == 0</code> or <code>positions[i] == height</code>, its direction will change.</li> </ul> <p>Return the <em>maximum possible area</em> under all the pistons.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = 5, positions = [2,5], directions = &quot;UD&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The current position of the pistons has the maximum possible area under it.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = 6, positions = [0,0,6,3], directions = &quot;UUDU&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>After 3 seconds, the pistons will be in positions <code>[3, 3, 3, 6]</code>, which has the maximum possible area under it.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= height &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= positions.length == directions.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= positions[i] &lt;= height</code></li> <li><code>directions[i]</code> is either <code>&#39;U&#39;</code> or <code>&#39;D&#39;</code>.</li> </ul>
Array; Hash Table; String; Counting; Prefix Sum; Simulation
Java
class Solution { public long maxArea(int height, int[] positions, String directions) { Map<Integer, Integer> delta = new TreeMap<>(); int diff = 0; long res = 0; for (int i = 0; i < positions.length; ++i) { int pos = positions[i]; char dir = directions.charAt(i); res += pos; if (dir == 'U') { ++diff; delta.merge(height - pos, -2, Integer::sum); delta.merge(height * 2 - pos, 2, Integer::sum); } else { --diff; delta.merge(pos, 2, Integer::sum); delta.merge(height + pos, -2, Integer::sum); } } long ans = res; int pre = 0; for (var e : delta.entrySet()) { int cur = e.getKey(); int d = e.getValue(); res += (long) (cur - pre) * diff; pre = cur; diff += d; ans = Math.max(ans, res); } return ans; } }
3,279
Maximum Total Area Occupied by Pistons
Hard
<p>There are several pistons in an old car engine, and we want to calculate the <strong>maximum</strong> possible area <strong>under</strong> the pistons.</p> <p>You are given:</p> <ul> <li>An integer <code>height</code>, representing the <strong>maximum</strong> height a piston can reach.</li> <li>An integer array <code>positions</code>, where <code>positions[i]</code> is the current position of piston <code>i</code>, which is equal to the current area <strong>under</strong> it.</li> <li>A string <code>directions</code>, where <code>directions[i]</code> is the current moving direction of piston <code>i</code>, <code>&#39;U&#39;</code> for up, and <code>&#39;D&#39;</code> for down.</li> </ul> <p>Each second:</p> <ul> <li>Every piston moves in its current direction 1 unit. e.g., if the direction is up, <code>positions[i]</code> is incremented by 1.</li> <li>If a piston has reached one of the ends, i.e., <code>positions[i] == 0</code> or <code>positions[i] == height</code>, its direction will change.</li> </ul> <p>Return the <em>maximum possible area</em> under all the pistons.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = 5, positions = [2,5], directions = &quot;UD&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The current position of the pistons has the maximum possible area under it.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = 6, positions = [0,0,6,3], directions = &quot;UUDU&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>After 3 seconds, the pistons will be in positions <code>[3, 3, 3, 6]</code>, which has the maximum possible area under it.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= height &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= positions.length == directions.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= positions[i] &lt;= height</code></li> <li><code>directions[i]</code> is either <code>&#39;U&#39;</code> or <code>&#39;D&#39;</code>.</li> </ul>
Array; Hash Table; String; Counting; Prefix Sum; Simulation
Python
class Solution: def maxArea(self, height: int, positions: List[int], directions: str) -> int: delta = defaultdict(int) diff = res = 0 for pos, dir in zip(positions, directions): res += pos if dir == "U": diff += 1 delta[height - pos] -= 2 delta[height * 2 - pos] += 2 else: diff -= 1 delta[pos] += 2 delta[height + pos] -= 2 ans = res pre = 0 for cur, d in sorted(delta.items()): res += (cur - pre) * diff pre = cur diff += d ans = max(ans, res) return ans
3,279
Maximum Total Area Occupied by Pistons
Hard
<p>There are several pistons in an old car engine, and we want to calculate the <strong>maximum</strong> possible area <strong>under</strong> the pistons.</p> <p>You are given:</p> <ul> <li>An integer <code>height</code>, representing the <strong>maximum</strong> height a piston can reach.</li> <li>An integer array <code>positions</code>, where <code>positions[i]</code> is the current position of piston <code>i</code>, which is equal to the current area <strong>under</strong> it.</li> <li>A string <code>directions</code>, where <code>directions[i]</code> is the current moving direction of piston <code>i</code>, <code>&#39;U&#39;</code> for up, and <code>&#39;D&#39;</code> for down.</li> </ul> <p>Each second:</p> <ul> <li>Every piston moves in its current direction 1 unit. e.g., if the direction is up, <code>positions[i]</code> is incremented by 1.</li> <li>If a piston has reached one of the ends, i.e., <code>positions[i] == 0</code> or <code>positions[i] == height</code>, its direction will change.</li> </ul> <p>Return the <em>maximum possible area</em> under all the pistons.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = 5, positions = [2,5], directions = &quot;UD&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The current position of the pistons has the maximum possible area under it.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = 6, positions = [0,0,6,3], directions = &quot;UUDU&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>After 3 seconds, the pistons will be in positions <code>[3, 3, 3, 6]</code>, which has the maximum possible area under it.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= height &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= positions.length == directions.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= positions[i] &lt;= height</code></li> <li><code>directions[i]</code> is either <code>&#39;U&#39;</code> or <code>&#39;D&#39;</code>.</li> </ul>
Array; Hash Table; String; Counting; Prefix Sum; Simulation
TypeScript
function maxArea(height: number, positions: number[], directions: string): number {}
3,280
Convert Date to Binary
Easy
<p>You are given a string <code>date</code> representing a Gregorian calendar date in the <code>yyyy-mm-dd</code> format.</p> <p><code>date</code> can be written in its binary representation obtained by converting year, month, and day to their binary representations without any leading zeroes and writing them down in <code>year-month-day</code> format.</p> <p>Return the <strong>binary</strong> representation of <code>date</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">date = &quot;2080-02-29&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;100000100000-10-11101&quot;</span></p> <p><strong>Explanation:</strong></p> <p><span class="example-io">100000100000, 10, and 11101 are the binary representations of 2080, 02, and 29 respectively.</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">date = &quot;1900-01-01&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;11101101100-1-1&quot;</span></p> <p><strong>Explanation:</strong></p> <p><span class="example-io">11101101100, 1, and 1 are the binary representations of 1900, 1, and 1 respectively.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>date.length == 10</code></li> <li><code>date[4] == date[7] == &#39;-&#39;</code>, and all other <code>date[i]</code>&#39;s are digits.</li> <li>The input is generated such that <code>date</code> represents a valid Gregorian calendar date between Jan 1<sup>st</sup>, 1900 and Dec 31<sup>st</sup>, 2100 (both inclusive).</li> </ul>
Math; String
C++
class Solution { public: string convertDateToBinary(string date) { auto bin = [](string s) -> string { string t = bitset<32>(stoi(s)).to_string(); return t.substr(t.find('1')); }; return bin(date.substr(0, 4)) + "-" + bin(date.substr(5, 2)) + "-" + bin(date.substr(8, 2)); } };
3,280
Convert Date to Binary
Easy
<p>You are given a string <code>date</code> representing a Gregorian calendar date in the <code>yyyy-mm-dd</code> format.</p> <p><code>date</code> can be written in its binary representation obtained by converting year, month, and day to their binary representations without any leading zeroes and writing them down in <code>year-month-day</code> format.</p> <p>Return the <strong>binary</strong> representation of <code>date</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">date = &quot;2080-02-29&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;100000100000-10-11101&quot;</span></p> <p><strong>Explanation:</strong></p> <p><span class="example-io">100000100000, 10, and 11101 are the binary representations of 2080, 02, and 29 respectively.</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">date = &quot;1900-01-01&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;11101101100-1-1&quot;</span></p> <p><strong>Explanation:</strong></p> <p><span class="example-io">11101101100, 1, and 1 are the binary representations of 1900, 1, and 1 respectively.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>date.length == 10</code></li> <li><code>date[4] == date[7] == &#39;-&#39;</code>, and all other <code>date[i]</code>&#39;s are digits.</li> <li>The input is generated such that <code>date</code> represents a valid Gregorian calendar date between Jan 1<sup>st</sup>, 1900 and Dec 31<sup>st</sup>, 2100 (both inclusive).</li> </ul>
Math; String
Go
func convertDateToBinary(date string) string { ans := []string{} for _, s := range strings.Split(date, "-") { x, _ := strconv.Atoi(s) ans = append(ans, strconv.FormatUint(uint64(x), 2)) } return strings.Join(ans, "-") }
3,280
Convert Date to Binary
Easy
<p>You are given a string <code>date</code> representing a Gregorian calendar date in the <code>yyyy-mm-dd</code> format.</p> <p><code>date</code> can be written in its binary representation obtained by converting year, month, and day to their binary representations without any leading zeroes and writing them down in <code>year-month-day</code> format.</p> <p>Return the <strong>binary</strong> representation of <code>date</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">date = &quot;2080-02-29&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;100000100000-10-11101&quot;</span></p> <p><strong>Explanation:</strong></p> <p><span class="example-io">100000100000, 10, and 11101 are the binary representations of 2080, 02, and 29 respectively.</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">date = &quot;1900-01-01&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;11101101100-1-1&quot;</span></p> <p><strong>Explanation:</strong></p> <p><span class="example-io">11101101100, 1, and 1 are the binary representations of 1900, 1, and 1 respectively.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>date.length == 10</code></li> <li><code>date[4] == date[7] == &#39;-&#39;</code>, and all other <code>date[i]</code>&#39;s are digits.</li> <li>The input is generated such that <code>date</code> represents a valid Gregorian calendar date between Jan 1<sup>st</sup>, 1900 and Dec 31<sup>st</sup>, 2100 (both inclusive).</li> </ul>
Math; String
Java
class Solution { public String convertDateToBinary(String date) { List<String> ans = new ArrayList<>(); for (var s : date.split("-")) { int x = Integer.parseInt(s); ans.add(Integer.toBinaryString(x)); } return String.join("-", ans); } }
3,280
Convert Date to Binary
Easy
<p>You are given a string <code>date</code> representing a Gregorian calendar date in the <code>yyyy-mm-dd</code> format.</p> <p><code>date</code> can be written in its binary representation obtained by converting year, month, and day to their binary representations without any leading zeroes and writing them down in <code>year-month-day</code> format.</p> <p>Return the <strong>binary</strong> representation of <code>date</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">date = &quot;2080-02-29&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;100000100000-10-11101&quot;</span></p> <p><strong>Explanation:</strong></p> <p><span class="example-io">100000100000, 10, and 11101 are the binary representations of 2080, 02, and 29 respectively.</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">date = &quot;1900-01-01&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;11101101100-1-1&quot;</span></p> <p><strong>Explanation:</strong></p> <p><span class="example-io">11101101100, 1, and 1 are the binary representations of 1900, 1, and 1 respectively.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>date.length == 10</code></li> <li><code>date[4] == date[7] == &#39;-&#39;</code>, and all other <code>date[i]</code>&#39;s are digits.</li> <li>The input is generated such that <code>date</code> represents a valid Gregorian calendar date between Jan 1<sup>st</sup>, 1900 and Dec 31<sup>st</sup>, 2100 (both inclusive).</li> </ul>
Math; String
Python
class Solution: def convertDateToBinary(self, date: str) -> str: return "-".join(f"{int(s):b}" for s in date.split("-"))
3,280
Convert Date to Binary
Easy
<p>You are given a string <code>date</code> representing a Gregorian calendar date in the <code>yyyy-mm-dd</code> format.</p> <p><code>date</code> can be written in its binary representation obtained by converting year, month, and day to their binary representations without any leading zeroes and writing them down in <code>year-month-day</code> format.</p> <p>Return the <strong>binary</strong> representation of <code>date</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">date = &quot;2080-02-29&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;100000100000-10-11101&quot;</span></p> <p><strong>Explanation:</strong></p> <p><span class="example-io">100000100000, 10, and 11101 are the binary representations of 2080, 02, and 29 respectively.</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">date = &quot;1900-01-01&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;11101101100-1-1&quot;</span></p> <p><strong>Explanation:</strong></p> <p><span class="example-io">11101101100, 1, and 1 are the binary representations of 1900, 1, and 1 respectively.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>date.length == 10</code></li> <li><code>date[4] == date[7] == &#39;-&#39;</code>, and all other <code>date[i]</code>&#39;s are digits.</li> <li>The input is generated such that <code>date</code> represents a valid Gregorian calendar date between Jan 1<sup>st</sup>, 1900 and Dec 31<sup>st</sup>, 2100 (both inclusive).</li> </ul>
Math; String
TypeScript
function convertDateToBinary(date: string): string { return date .split('-') .map(s => (+s).toString(2)) .join('-'); }
3,281
Maximize Score of Numbers in Ranges
Medium
<p>You are given an array of integers <code>start</code> and an integer <code>d</code>, representing <code>n</code> intervals <code>[start[i], start[i] + d]</code>.</p> <p>You are asked to choose <code>n</code> integers where the <code>i<sup>th</sup></code> integer must belong to the <code>i<sup>th</sup></code> interval. The <strong>score</strong> of the chosen integers is defined as the <strong>minimum</strong> absolute difference between any two integers that have been chosen.</p> <p>Return the <strong>maximum</strong> <em>possible score</em> of the chosen integers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [6,0,3], d = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible score can be obtained by choosing integers: 8, 0, and 4. The score of these chosen integers is <code>min(|8 - 0|, |8 - 4|, |0 - 4|)</code> which equals 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [2,6,13,13], d = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible score can be obtained by choosing integers: 2, 7, 13, and 18. The score of these chosen integers is <code>min(|2 - 7|, |2 - 13|, |2 - 18|, |7 - 13|, |7 - 18|, |13 - 18|)</code> which equals 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= start.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= start[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= d &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Binary Search; Sorting
C++
class Solution { public: int maxPossibleScore(vector<int>& start, int d) { ranges::sort(start); auto check = [&](int mi) -> bool { long long last = LLONG_MIN; for (int st : start) { if (last + mi > st + d) { return false; } last = max((long long) st, last + mi); } return true; }; int l = 0, r = start.back() + d - start[0]; while (l < r) { int mid = l + (r - l + 1) / 2; if (check(mid)) { l = mid; } else { r = mid - 1; } } return l; } };
3,281
Maximize Score of Numbers in Ranges
Medium
<p>You are given an array of integers <code>start</code> and an integer <code>d</code>, representing <code>n</code> intervals <code>[start[i], start[i] + d]</code>.</p> <p>You are asked to choose <code>n</code> integers where the <code>i<sup>th</sup></code> integer must belong to the <code>i<sup>th</sup></code> interval. The <strong>score</strong> of the chosen integers is defined as the <strong>minimum</strong> absolute difference between any two integers that have been chosen.</p> <p>Return the <strong>maximum</strong> <em>possible score</em> of the chosen integers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [6,0,3], d = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible score can be obtained by choosing integers: 8, 0, and 4. The score of these chosen integers is <code>min(|8 - 0|, |8 - 4|, |0 - 4|)</code> which equals 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [2,6,13,13], d = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible score can be obtained by choosing integers: 2, 7, 13, and 18. The score of these chosen integers is <code>min(|2 - 7|, |2 - 13|, |2 - 18|, |7 - 13|, |7 - 18|, |13 - 18|)</code> which equals 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= start.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= start[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= d &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Binary Search; Sorting
Go
func maxPossibleScore(start []int, d int) int { check := func(mi int) bool { last := math.MinInt64 for _, st := range start { if last+mi > st+d { return false } last = max(st, last+mi) } return true } sort.Ints(start) l, r := 0, start[len(start)-1]+d-start[0] for l < r { mid := (l + r + 1) >> 1 if check(mid) { l = mid } else { r = mid - 1 } } return l }
3,281
Maximize Score of Numbers in Ranges
Medium
<p>You are given an array of integers <code>start</code> and an integer <code>d</code>, representing <code>n</code> intervals <code>[start[i], start[i] + d]</code>.</p> <p>You are asked to choose <code>n</code> integers where the <code>i<sup>th</sup></code> integer must belong to the <code>i<sup>th</sup></code> interval. The <strong>score</strong> of the chosen integers is defined as the <strong>minimum</strong> absolute difference between any two integers that have been chosen.</p> <p>Return the <strong>maximum</strong> <em>possible score</em> of the chosen integers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [6,0,3], d = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible score can be obtained by choosing integers: 8, 0, and 4. The score of these chosen integers is <code>min(|8 - 0|, |8 - 4|, |0 - 4|)</code> which equals 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [2,6,13,13], d = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible score can be obtained by choosing integers: 2, 7, 13, and 18. The score of these chosen integers is <code>min(|2 - 7|, |2 - 13|, |2 - 18|, |7 - 13|, |7 - 18|, |13 - 18|)</code> which equals 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= start.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= start[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= d &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Binary Search; Sorting
Java
class Solution { private int[] start; private int d; public int maxPossibleScore(int[] start, int d) { Arrays.sort(start); this.start = start; this.d = d; int n = start.length; int l = 0, r = start[n - 1] + d - start[0]; while (l < r) { int mid = (l + r + 1) >>> 1; if (check(mid)) { l = mid; } else { r = mid - 1; } } return l; } private boolean check(int mi) { long last = Long.MIN_VALUE; for (int st : start) { if (last + mi > st + d) { return false; } last = Math.max(st, last + mi); } return true; } }
3,281
Maximize Score of Numbers in Ranges
Medium
<p>You are given an array of integers <code>start</code> and an integer <code>d</code>, representing <code>n</code> intervals <code>[start[i], start[i] + d]</code>.</p> <p>You are asked to choose <code>n</code> integers where the <code>i<sup>th</sup></code> integer must belong to the <code>i<sup>th</sup></code> interval. The <strong>score</strong> of the chosen integers is defined as the <strong>minimum</strong> absolute difference between any two integers that have been chosen.</p> <p>Return the <strong>maximum</strong> <em>possible score</em> of the chosen integers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [6,0,3], d = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible score can be obtained by choosing integers: 8, 0, and 4. The score of these chosen integers is <code>min(|8 - 0|, |8 - 4|, |0 - 4|)</code> which equals 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [2,6,13,13], d = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible score can be obtained by choosing integers: 2, 7, 13, and 18. The score of these chosen integers is <code>min(|2 - 7|, |2 - 13|, |2 - 18|, |7 - 13|, |7 - 18|, |13 - 18|)</code> which equals 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= start.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= start[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= d &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Binary Search; Sorting
Python
class Solution: def maxPossibleScore(self, start: List[int], d: int) -> int: def check(mi: int) -> bool: last = -inf for st in start: if last + mi > st + d: return False last = max(st, last + mi) return True start.sort() l, r = 0, start[-1] + d - start[0] while l < r: mid = (l + r + 1) >> 1 if check(mid): l = mid else: r = mid - 1 return l
3,281
Maximize Score of Numbers in Ranges
Medium
<p>You are given an array of integers <code>start</code> and an integer <code>d</code>, representing <code>n</code> intervals <code>[start[i], start[i] + d]</code>.</p> <p>You are asked to choose <code>n</code> integers where the <code>i<sup>th</sup></code> integer must belong to the <code>i<sup>th</sup></code> interval. The <strong>score</strong> of the chosen integers is defined as the <strong>minimum</strong> absolute difference between any two integers that have been chosen.</p> <p>Return the <strong>maximum</strong> <em>possible score</em> of the chosen integers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [6,0,3], d = 2</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible score can be obtained by choosing integers: 8, 0, and 4. The score of these chosen integers is <code>min(|8 - 0|, |8 - 4|, |0 - 4|)</code> which equals 4.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [2,6,13,13], d = 5</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The maximum possible score can be obtained by choosing integers: 2, 7, 13, and 18. The score of these chosen integers is <code>min(|2 - 7|, |2 - 13|, |2 - 18|, |7 - 13|, |7 - 18|, |13 - 18|)</code> which equals 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= start.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= start[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= d &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Binary Search; Sorting
TypeScript
function maxPossibleScore(start: number[], d: number): number { start.sort((a, b) => a - b); let [l, r] = [0, start.at(-1)! + d - start[0]]; const check = (mi: number): boolean => { let last = -Infinity; for (const st of start) { if (last + mi > st + d) { return false; } last = Math.max(st, last + mi); } return true; }; while (l < r) { const mid = l + ((r - l + 1) >> 1); if (check(mid)) { l = mid; } else { r = mid - 1; } } return l; }
3,282
Reach End of Array With Max Score
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>Your goal is to start at index <code>0</code> and reach index <code>n - 1</code>. You can only jump to indices <strong>greater</strong> than your current index.</p> <p>The score for a jump from index <code>i</code> to index <code>j</code> is calculated as <code>(j - i) * nums[i]</code>.</p> <p>Return the <strong>maximum</strong> possible <b>total score</b> by the time you reach the last index.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,5]</span></p> <p><strong>Output:</strong> 7</p> <p><strong>Explanation:</strong></p> <p>First, jump to index 1 and then jump to the last index. The final score is <code>1 * 1 + 2 * 3 = 7</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,3,2]</span></p> <p><strong>Output:</strong> 16</p> <p><strong>Explanation:</strong></p> <p>Jump directly to the last index. The final score is <code>4 * 4 = 16</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>5</sup></code></li> </ul>
Greedy; Array
C++
class Solution { public: long long findMaximumScore(vector<int>& nums) { long long ans = 0; int mx = 0; for (int i = 0; i + 1 < nums.size(); ++i) { mx = max(mx, nums[i]); ans += mx; } return ans; } };
3,282
Reach End of Array With Max Score
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>Your goal is to start at index <code>0</code> and reach index <code>n - 1</code>. You can only jump to indices <strong>greater</strong> than your current index.</p> <p>The score for a jump from index <code>i</code> to index <code>j</code> is calculated as <code>(j - i) * nums[i]</code>.</p> <p>Return the <strong>maximum</strong> possible <b>total score</b> by the time you reach the last index.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,5]</span></p> <p><strong>Output:</strong> 7</p> <p><strong>Explanation:</strong></p> <p>First, jump to index 1 and then jump to the last index. The final score is <code>1 * 1 + 2 * 3 = 7</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,3,2]</span></p> <p><strong>Output:</strong> 16</p> <p><strong>Explanation:</strong></p> <p>Jump directly to the last index. The final score is <code>4 * 4 = 16</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>5</sup></code></li> </ul>
Greedy; Array
Go
func findMaximumScore(nums []int) (ans int64) { mx := 0 for _, x := range nums[:len(nums)-1] { mx = max(mx, x) ans += int64(mx) } return }
3,282
Reach End of Array With Max Score
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>Your goal is to start at index <code>0</code> and reach index <code>n - 1</code>. You can only jump to indices <strong>greater</strong> than your current index.</p> <p>The score for a jump from index <code>i</code> to index <code>j</code> is calculated as <code>(j - i) * nums[i]</code>.</p> <p>Return the <strong>maximum</strong> possible <b>total score</b> by the time you reach the last index.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,5]</span></p> <p><strong>Output:</strong> 7</p> <p><strong>Explanation:</strong></p> <p>First, jump to index 1 and then jump to the last index. The final score is <code>1 * 1 + 2 * 3 = 7</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,3,2]</span></p> <p><strong>Output:</strong> 16</p> <p><strong>Explanation:</strong></p> <p>Jump directly to the last index. The final score is <code>4 * 4 = 16</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>5</sup></code></li> </ul>
Greedy; Array
Java
class Solution { public long findMaximumScore(List<Integer> nums) { long ans = 0; int mx = 0; for (int i = 0; i + 1 < nums.size(); ++i) { mx = Math.max(mx, nums.get(i)); ans += mx; } return ans; } }
3,282
Reach End of Array With Max Score
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>Your goal is to start at index <code>0</code> and reach index <code>n - 1</code>. You can only jump to indices <strong>greater</strong> than your current index.</p> <p>The score for a jump from index <code>i</code> to index <code>j</code> is calculated as <code>(j - i) * nums[i]</code>.</p> <p>Return the <strong>maximum</strong> possible <b>total score</b> by the time you reach the last index.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,5]</span></p> <p><strong>Output:</strong> 7</p> <p><strong>Explanation:</strong></p> <p>First, jump to index 1 and then jump to the last index. The final score is <code>1 * 1 + 2 * 3 = 7</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,3,2]</span></p> <p><strong>Output:</strong> 16</p> <p><strong>Explanation:</strong></p> <p>Jump directly to the last index. The final score is <code>4 * 4 = 16</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>5</sup></code></li> </ul>
Greedy; Array
Python
class Solution: def findMaximumScore(self, nums: List[int]) -> int: ans = mx = 0 for x in nums[:-1]: mx = max(mx, x) ans += mx return ans
3,282
Reach End of Array With Max Score
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>Your goal is to start at index <code>0</code> and reach index <code>n - 1</code>. You can only jump to indices <strong>greater</strong> than your current index.</p> <p>The score for a jump from index <code>i</code> to index <code>j</code> is calculated as <code>(j - i) * nums[i]</code>.</p> <p>Return the <strong>maximum</strong> possible <b>total score</b> by the time you reach the last index.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,5]</span></p> <p><strong>Output:</strong> 7</p> <p><strong>Explanation:</strong></p> <p>First, jump to index 1 and then jump to the last index. The final score is <code>1 * 1 + 2 * 3 = 7</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,1,3,2]</span></p> <p><strong>Output:</strong> 16</p> <p><strong>Explanation:</strong></p> <p>Jump directly to the last index. The final score is <code>4 * 4 = 16</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>5</sup></code></li> </ul>
Greedy; Array
TypeScript
function findMaximumScore(nums: number[]): number { let [ans, mx]: [number, number] = [0, 0]; for (const x of nums.slice(0, -1)) { mx = Math.max(mx, x); ans += mx; } return ans; }
3,283
Maximum Number of Moves to Kill All Pawns
Hard
<p>There is a <code>50 x 50</code> chessboard with <strong>one</strong> knight and some pawns on it. You are given two integers <code>kx</code> and <code>ky</code> where <code>(kx, ky)</code> denotes the position of the knight, and a 2D array <code>positions</code> where <code>positions[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> denotes the position of the pawns on the chessboard.</p> <p>Alice and Bob play a <em>turn-based</em> game, where Alice goes first. In each player&#39;s turn:</p> <ul> <li>The player <em>selects </em>a pawn that still exists on the board and captures it with the knight in the <strong>fewest</strong> possible <strong>moves</strong>. <strong>Note</strong> that the player can select <strong>any</strong> pawn, it <strong>might not</strong> be one that can be captured in the <strong>least</strong> number of moves.</li> <li><span>In the process of capturing the <em>selected</em> pawn, the knight <strong>may</strong> pass other pawns <strong>without</strong> capturing them</span>. <strong>Only</strong> the <em>selected</em> pawn can be captured in <em>this</em> turn.</li> </ul> <p>Alice is trying to <strong>maximize</strong> the <strong>sum</strong> of the number of moves made by <em>both</em> players until there are no more pawns on the board, whereas Bob tries to <strong>minimize</strong> them.</p> <p>Return the <strong>maximum</strong> <em>total</em> number of moves made during the game that Alice can achieve, assuming both players play <strong>optimally</strong>.</p> <p>Note that in one <strong>move, </strong>a chess knight has eight possible positions it can move to, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3283.Maximum%20Number%20of%20Moves%20to%20Kill%20All%20Pawns/images/chess_knight.jpg" style="width: 275px; height: 273px;" /></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">kx = 1, ky = 1, positions = [[0,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3283.Maximum%20Number%20of%20Moves%20to%20Kill%20All%20Pawns/images/gif3.gif" style="width: 275px; height: 275px;" /></p> <p>The knight takes 4 moves to reach the pawn at <code>(0, 0)</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">kx = 0, ky = 2, positions = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3283.Maximum%20Number%20of%20Moves%20to%20Kill%20All%20Pawns/images/gif4.gif" style="width: 320px; height: 320px;" /></strong></p> <ul> <li>Alice picks the pawn at <code>(2, 2)</code> and captures it in two moves: <code>(0, 2) -&gt; (1, 4) -&gt; (2, 2)</code>.</li> <li>Bob picks the pawn at <code>(3, 3)</code> and captures it in two moves: <code>(2, 2) -&gt; (4, 1) -&gt; (3, 3)</code>.</li> <li>Alice picks the pawn at <code>(1, 1)</code> and captures it in four moves: <code>(3, 3) -&gt; (4, 1) -&gt; (2, 2) -&gt; (0, 3) -&gt; (1, 1)</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">kx = 0, ky = 0, positions = [[1,2],[2,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice picks the pawn at <code>(2, 4)</code> and captures it in two moves: <code>(0, 0) -&gt; (1, 2) -&gt; (2, 4)</code>. Note that the pawn at <code>(1, 2)</code> is not captured.</li> <li>Bob picks the pawn at <code>(1, 2)</code> and captures it in one move: <code>(2, 4) -&gt; (1, 2)</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= kx, ky &lt;= 49</code></li> <li><code>1 &lt;= positions.length &lt;= 15</code></li> <li><code>positions[i].length == 2</code></li> <li><code>0 &lt;= positions[i][0], positions[i][1] &lt;= 49</code></li> <li>All <code>positions[i]</code> are unique.</li> <li>The input is generated such that <code>positions[i] != [kx, ky]</code> for all <code>0 &lt;= i &lt; positions.length</code>.</li> </ul>
Bit Manipulation; Breadth-First Search; Array; Math; Bitmask; Game Theory
C++
class Solution { public: int maxMoves(int kx, int ky, vector<vector<int>>& positions) { int n = positions.size(); const int m = 50; const int dx[8] = {1, 1, 2, 2, -1, -1, -2, -2}; const int dy[8] = {2, -2, 1, -1, 2, -2, 1, -1}; int dist[n + 1][m][m]; memset(dist, -1, sizeof(dist)); for (int i = 0; i <= n; ++i) { int x = (i < n) ? positions[i][0] : kx; int y = (i < n) ? positions[i][1] : ky; queue<pair<int, int>> q; q.push({x, y}); dist[i][x][y] = 0; for (int step = 1; !q.empty(); ++step) { for (int k = q.size(); k > 0; --k) { auto [x1, y1] = q.front(); q.pop(); for (int j = 0; j < 8; ++j) { int x2 = x1 + dx[j], y2 = y1 + dy[j]; if (x2 >= 0 && x2 < m && y2 >= 0 && y2 < m && dist[i][x2][y2] == -1) { dist[i][x2][y2] = step; q.push({x2, y2}); } } } } } int f[n + 1][1 << n][2]; memset(f, -1, sizeof(f)); auto dfs = [&](this auto&& dfs, int last, int state, int k) -> int { if (state == 0) { return 0; } if (f[last][state][k] != -1) { return f[last][state][k]; } int res = (k == 1) ? 0 : INT_MAX; for (int i = 0; i < positions.size(); ++i) { int x = positions[i][0], y = positions[i][1]; if ((state >> i) & 1) { int t = dfs(i, state ^ (1 << i), k ^ 1) + dist[last][x][y]; if (k == 1) { res = max(res, t); } else { res = min(res, t); } } } return f[last][state][k] = res; }; return dfs(n, (1 << n) - 1, 1); } };
3,283
Maximum Number of Moves to Kill All Pawns
Hard
<p>There is a <code>50 x 50</code> chessboard with <strong>one</strong> knight and some pawns on it. You are given two integers <code>kx</code> and <code>ky</code> where <code>(kx, ky)</code> denotes the position of the knight, and a 2D array <code>positions</code> where <code>positions[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> denotes the position of the pawns on the chessboard.</p> <p>Alice and Bob play a <em>turn-based</em> game, where Alice goes first. In each player&#39;s turn:</p> <ul> <li>The player <em>selects </em>a pawn that still exists on the board and captures it with the knight in the <strong>fewest</strong> possible <strong>moves</strong>. <strong>Note</strong> that the player can select <strong>any</strong> pawn, it <strong>might not</strong> be one that can be captured in the <strong>least</strong> number of moves.</li> <li><span>In the process of capturing the <em>selected</em> pawn, the knight <strong>may</strong> pass other pawns <strong>without</strong> capturing them</span>. <strong>Only</strong> the <em>selected</em> pawn can be captured in <em>this</em> turn.</li> </ul> <p>Alice is trying to <strong>maximize</strong> the <strong>sum</strong> of the number of moves made by <em>both</em> players until there are no more pawns on the board, whereas Bob tries to <strong>minimize</strong> them.</p> <p>Return the <strong>maximum</strong> <em>total</em> number of moves made during the game that Alice can achieve, assuming both players play <strong>optimally</strong>.</p> <p>Note that in one <strong>move, </strong>a chess knight has eight possible positions it can move to, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3283.Maximum%20Number%20of%20Moves%20to%20Kill%20All%20Pawns/images/chess_knight.jpg" style="width: 275px; height: 273px;" /></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">kx = 1, ky = 1, positions = [[0,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3283.Maximum%20Number%20of%20Moves%20to%20Kill%20All%20Pawns/images/gif3.gif" style="width: 275px; height: 275px;" /></p> <p>The knight takes 4 moves to reach the pawn at <code>(0, 0)</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">kx = 0, ky = 2, positions = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3283.Maximum%20Number%20of%20Moves%20to%20Kill%20All%20Pawns/images/gif4.gif" style="width: 320px; height: 320px;" /></strong></p> <ul> <li>Alice picks the pawn at <code>(2, 2)</code> and captures it in two moves: <code>(0, 2) -&gt; (1, 4) -&gt; (2, 2)</code>.</li> <li>Bob picks the pawn at <code>(3, 3)</code> and captures it in two moves: <code>(2, 2) -&gt; (4, 1) -&gt; (3, 3)</code>.</li> <li>Alice picks the pawn at <code>(1, 1)</code> and captures it in four moves: <code>(3, 3) -&gt; (4, 1) -&gt; (2, 2) -&gt; (0, 3) -&gt; (1, 1)</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">kx = 0, ky = 0, positions = [[1,2],[2,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice picks the pawn at <code>(2, 4)</code> and captures it in two moves: <code>(0, 0) -&gt; (1, 2) -&gt; (2, 4)</code>. Note that the pawn at <code>(1, 2)</code> is not captured.</li> <li>Bob picks the pawn at <code>(1, 2)</code> and captures it in one move: <code>(2, 4) -&gt; (1, 2)</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= kx, ky &lt;= 49</code></li> <li><code>1 &lt;= positions.length &lt;= 15</code></li> <li><code>positions[i].length == 2</code></li> <li><code>0 &lt;= positions[i][0], positions[i][1] &lt;= 49</code></li> <li>All <code>positions[i]</code> are unique.</li> <li>The input is generated such that <code>positions[i] != [kx, ky]</code> for all <code>0 &lt;= i &lt; positions.length</code>.</li> </ul>
Bit Manipulation; Breadth-First Search; Array; Math; Bitmask; Game Theory
Go
func maxMoves(kx int, ky int, positions [][]int) int { n := len(positions) const m = 50 dx := []int{1, 1, 2, 2, -1, -1, -2, -2} dy := []int{2, -2, 1, -1, 2, -2, 1, -1} dist := make([][][]int, n+1) for i := range dist { dist[i] = make([][]int, m) for j := range dist[i] { dist[i][j] = make([]int, m) for k := range dist[i][j] { dist[i][j][k] = -1 } } } for i := 0; i <= n; i++ { x := kx y := ky if i < n { x = positions[i][0] y = positions[i][1] } q := [][2]int{[2]int{x, y}} dist[i][x][y] = 0 for step := 1; len(q) > 0; step++ { for k := len(q); k > 0; k-- { p := q[0] q = q[1:] x1, y1 := p[0], p[1] for j := 0; j < 8; j++ { x2 := x1 + dx[j] y2 := y1 + dy[j] if x2 >= 0 && x2 < m && y2 >= 0 && y2 < m && dist[i][x2][y2] == -1 { dist[i][x2][y2] = step q = append(q, [2]int{x2, y2}) } } } } } f := make([][][]int, n+1) for i := range f { f[i] = make([][]int, 1<<n) for j := range f[i] { f[i][j] = make([]int, 2) for k := range f[i][j] { f[i][j][k] = -1 } } } var dfs func(last, state, k int) int dfs = func(last, state, k int) int { if state == 0 { return 0 } if f[last][state][k] != -1 { return f[last][state][k] } var res int if k == 0 { res = math.MaxInt32 } for i, p := range positions { x, y := p[0], p[1] if (state>>i)&1 == 1 { t := dfs(i, state^(1<<i), k^1) + dist[last][x][y] if k == 1 { res = max(res, t) } else { res = min(res, t) } } } f[last][state][k] = res return res } return dfs(n, (1<<n)-1, 1) }
3,283
Maximum Number of Moves to Kill All Pawns
Hard
<p>There is a <code>50 x 50</code> chessboard with <strong>one</strong> knight and some pawns on it. You are given two integers <code>kx</code> and <code>ky</code> where <code>(kx, ky)</code> denotes the position of the knight, and a 2D array <code>positions</code> where <code>positions[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> denotes the position of the pawns on the chessboard.</p> <p>Alice and Bob play a <em>turn-based</em> game, where Alice goes first. In each player&#39;s turn:</p> <ul> <li>The player <em>selects </em>a pawn that still exists on the board and captures it with the knight in the <strong>fewest</strong> possible <strong>moves</strong>. <strong>Note</strong> that the player can select <strong>any</strong> pawn, it <strong>might not</strong> be one that can be captured in the <strong>least</strong> number of moves.</li> <li><span>In the process of capturing the <em>selected</em> pawn, the knight <strong>may</strong> pass other pawns <strong>without</strong> capturing them</span>. <strong>Only</strong> the <em>selected</em> pawn can be captured in <em>this</em> turn.</li> </ul> <p>Alice is trying to <strong>maximize</strong> the <strong>sum</strong> of the number of moves made by <em>both</em> players until there are no more pawns on the board, whereas Bob tries to <strong>minimize</strong> them.</p> <p>Return the <strong>maximum</strong> <em>total</em> number of moves made during the game that Alice can achieve, assuming both players play <strong>optimally</strong>.</p> <p>Note that in one <strong>move, </strong>a chess knight has eight possible positions it can move to, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3283.Maximum%20Number%20of%20Moves%20to%20Kill%20All%20Pawns/images/chess_knight.jpg" style="width: 275px; height: 273px;" /></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">kx = 1, ky = 1, positions = [[0,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3283.Maximum%20Number%20of%20Moves%20to%20Kill%20All%20Pawns/images/gif3.gif" style="width: 275px; height: 275px;" /></p> <p>The knight takes 4 moves to reach the pawn at <code>(0, 0)</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">kx = 0, ky = 2, positions = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3283.Maximum%20Number%20of%20Moves%20to%20Kill%20All%20Pawns/images/gif4.gif" style="width: 320px; height: 320px;" /></strong></p> <ul> <li>Alice picks the pawn at <code>(2, 2)</code> and captures it in two moves: <code>(0, 2) -&gt; (1, 4) -&gt; (2, 2)</code>.</li> <li>Bob picks the pawn at <code>(3, 3)</code> and captures it in two moves: <code>(2, 2) -&gt; (4, 1) -&gt; (3, 3)</code>.</li> <li>Alice picks the pawn at <code>(1, 1)</code> and captures it in four moves: <code>(3, 3) -&gt; (4, 1) -&gt; (2, 2) -&gt; (0, 3) -&gt; (1, 1)</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">kx = 0, ky = 0, positions = [[1,2],[2,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice picks the pawn at <code>(2, 4)</code> and captures it in two moves: <code>(0, 0) -&gt; (1, 2) -&gt; (2, 4)</code>. Note that the pawn at <code>(1, 2)</code> is not captured.</li> <li>Bob picks the pawn at <code>(1, 2)</code> and captures it in one move: <code>(2, 4) -&gt; (1, 2)</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= kx, ky &lt;= 49</code></li> <li><code>1 &lt;= positions.length &lt;= 15</code></li> <li><code>positions[i].length == 2</code></li> <li><code>0 &lt;= positions[i][0], positions[i][1] &lt;= 49</code></li> <li>All <code>positions[i]</code> are unique.</li> <li>The input is generated such that <code>positions[i] != [kx, ky]</code> for all <code>0 &lt;= i &lt; positions.length</code>.</li> </ul>
Bit Manipulation; Breadth-First Search; Array; Math; Bitmask; Game Theory
Java
class Solution { private Integer[][][] f; private Integer[][][] dist; private int[][] positions; private final int[] dx = {1, 1, 2, 2, -1, -1, -2, -2}; private final int[] dy = {2, -2, 1, -1, 2, -2, 1, -1}; public int maxMoves(int kx, int ky, int[][] positions) { int n = positions.length; final int m = 50; dist = new Integer[n + 1][m][m]; this.positions = positions; for (int i = 0; i <= n; ++i) { int x = i < n ? positions[i][0] : kx; int y = i < n ? positions[i][1] : ky; Deque<int[]> q = new ArrayDeque<>(); q.offer(new int[] {x, y}); for (int step = 1; !q.isEmpty(); ++step) { for (int k = q.size(); k > 0; --k) { var p = q.poll(); int x1 = p[0], y1 = p[1]; for (int j = 0; j < 8; ++j) { int x2 = x1 + dx[j], y2 = y1 + dy[j]; if (x2 >= 0 && x2 < m && y2 >= 0 && y2 < m && dist[i][x2][y2] == null) { dist[i][x2][y2] = step; q.offer(new int[] {x2, y2}); } } } } } f = new Integer[n + 1][1 << n][2]; return dfs(n, (1 << n) - 1, 1); } private int dfs(int last, int state, int k) { if (state == 0) { return 0; } if (f[last][state][k] != null) { return f[last][state][k]; } int res = k == 1 ? 0 : Integer.MAX_VALUE; for (int i = 0; i < positions.length; ++i) { int x = positions[i][0], y = positions[i][1]; if ((state >> i & 1) == 1) { int t = dfs(i, state ^ (1 << i), k ^ 1) + dist[last][x][y]; res = k == 1 ? Math.max(res, t) : Math.min(res, t); } } return f[last][state][k] = res; } }
3,283
Maximum Number of Moves to Kill All Pawns
Hard
<p>There is a <code>50 x 50</code> chessboard with <strong>one</strong> knight and some pawns on it. You are given two integers <code>kx</code> and <code>ky</code> where <code>(kx, ky)</code> denotes the position of the knight, and a 2D array <code>positions</code> where <code>positions[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> denotes the position of the pawns on the chessboard.</p> <p>Alice and Bob play a <em>turn-based</em> game, where Alice goes first. In each player&#39;s turn:</p> <ul> <li>The player <em>selects </em>a pawn that still exists on the board and captures it with the knight in the <strong>fewest</strong> possible <strong>moves</strong>. <strong>Note</strong> that the player can select <strong>any</strong> pawn, it <strong>might not</strong> be one that can be captured in the <strong>least</strong> number of moves.</li> <li><span>In the process of capturing the <em>selected</em> pawn, the knight <strong>may</strong> pass other pawns <strong>without</strong> capturing them</span>. <strong>Only</strong> the <em>selected</em> pawn can be captured in <em>this</em> turn.</li> </ul> <p>Alice is trying to <strong>maximize</strong> the <strong>sum</strong> of the number of moves made by <em>both</em> players until there are no more pawns on the board, whereas Bob tries to <strong>minimize</strong> them.</p> <p>Return the <strong>maximum</strong> <em>total</em> number of moves made during the game that Alice can achieve, assuming both players play <strong>optimally</strong>.</p> <p>Note that in one <strong>move, </strong>a chess knight has eight possible positions it can move to, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3283.Maximum%20Number%20of%20Moves%20to%20Kill%20All%20Pawns/images/chess_knight.jpg" style="width: 275px; height: 273px;" /></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">kx = 1, ky = 1, positions = [[0,0]]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3283.Maximum%20Number%20of%20Moves%20to%20Kill%20All%20Pawns/images/gif3.gif" style="width: 275px; height: 275px;" /></p> <p>The knight takes 4 moves to reach the pawn at <code>(0, 0)</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">kx = 0, ky = 2, positions = [[1,1],[2,2],[3,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p><strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3283.Maximum%20Number%20of%20Moves%20to%20Kill%20All%20Pawns/images/gif4.gif" style="width: 320px; height: 320px;" /></strong></p> <ul> <li>Alice picks the pawn at <code>(2, 2)</code> and captures it in two moves: <code>(0, 2) -&gt; (1, 4) -&gt; (2, 2)</code>.</li> <li>Bob picks the pawn at <code>(3, 3)</code> and captures it in two moves: <code>(2, 2) -&gt; (4, 1) -&gt; (3, 3)</code>.</li> <li>Alice picks the pawn at <code>(1, 1)</code> and captures it in four moves: <code>(3, 3) -&gt; (4, 1) -&gt; (2, 2) -&gt; (0, 3) -&gt; (1, 1)</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">kx = 0, ky = 0, positions = [[1,2],[2,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Alice picks the pawn at <code>(2, 4)</code> and captures it in two moves: <code>(0, 0) -&gt; (1, 2) -&gt; (2, 4)</code>. Note that the pawn at <code>(1, 2)</code> is not captured.</li> <li>Bob picks the pawn at <code>(1, 2)</code> and captures it in one move: <code>(2, 4) -&gt; (1, 2)</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= kx, ky &lt;= 49</code></li> <li><code>1 &lt;= positions.length &lt;= 15</code></li> <li><code>positions[i].length == 2</code></li> <li><code>0 &lt;= positions[i][0], positions[i][1] &lt;= 49</code></li> <li>All <code>positions[i]</code> are unique.</li> <li>The input is generated such that <code>positions[i] != [kx, ky]</code> for all <code>0 &lt;= i &lt; positions.length</code>.</li> </ul>
Bit Manipulation; Breadth-First Search; Array; Math; Bitmask; Game Theory
Python
class Solution: def maxMoves(self, kx: int, ky: int, positions: List[List[int]]) -> int: @cache def dfs(last: int, state: int, k: int) -> int: if state == 0: return 0 if k: res = 0 for i, (x, y) in enumerate(positions): if state >> i & 1: t = dfs(i, state ^ (1 << i), k ^ 1) + dist[last][x][y] if res < t: res = t return res else: res = inf for i, (x, y) in enumerate(positions): if state >> i & 1: t = dfs(i, state ^ (1 << i), k ^ 1) + dist[last][x][y] if res > t: res = t return res n = len(positions) m = 50 dist = [[[-1] * m for _ in range(m)] for _ in range(n + 1)] dx = [1, 1, 2, 2, -1, -1, -2, -2] dy = [2, -2, 1, -1, 2, -2, 1, -1] positions.append([kx, ky]) for i, (x, y) in enumerate(positions): dist[i][x][y] = 0 q = deque([(x, y)]) step = 0 while q: step += 1 for _ in range(len(q)): x1, y1 = q.popleft() for j in range(8): x2, y2 = x1 + dx[j], y1 + dy[j] if 0 <= x2 < m and 0 <= y2 < m and dist[i][x2][y2] == -1: dist[i][x2][y2] = step q.append((x2, y2)) ans = dfs(n, (1 << n) - 1, 1) dfs.cache_clear() return ans
3,284
Sum of Consecutive Subarrays
Medium
<p>We call an array <code>arr</code> of length <code>n</code> <strong>consecutive</strong> if one of the following holds:</p> <ul> <li><code>arr[i] - arr[i - 1] == 1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> <li><code>arr[i] - arr[i - 1] == -1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> </ul> <p>The <strong>value</strong> of an array is the sum of its elements.</p> <p>For example, <code>[3, 4, 5]</code> is a consecutive array of value 12 and <code>[9, 8]</code> is another of value 17. While <code>[3, 4, 3]</code> and <code>[8, 6]</code> are not consecutive.</p> <p>Given an array of integers <code>nums</code>, return the <em>sum</em> of the <strong>values</strong> of all <strong>consecutive </strong><span data-keyword="subarray-nonempty">subarrays</span>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7.</code></p> <p><strong>Note</strong> that an array of length 1 is also considered consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[1, 2, 3]</code>.<br /> Sum of their values would be: <code>1 + 2 + 3 + 3 + 5 + 6 = 20</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[1]</code>, <code>[3]</code>, <code>[5]</code>, <code>[7]</code>.<br /> Sum of their values would be: <code>1 + 3 + 5 + 7 = 16</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,6,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">32</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[7]</code>, <code>[6]</code>, <code>[1]</code>, <code>[2]</code>, <code>[7, 6]</code>, <code>[1, 2]</code>.<br /> Sum of their values would be: <code>7 + 6 + 1 + 2 + 13 + 3 = 32</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>5</sup></code></li> </ul>
Array; Two Pointers; Dynamic Programming
C++
class Solution { public: int getSum(vector<int>& nums) { const int mod = 1e9 + 7; long long s = nums[0], t = nums[0], ans = nums[0]; int f = 1, g = 1; for (int i = 1; i < nums.size(); ++i) { int x = nums[i - 1], y = nums[i]; if (y - x == 1) { ++f; s += 1LL * f * y; ans = (ans + s) % mod; } else { f = 1; s = y; } if (y - x == -1) { ++g; t += 1LL * g * y; ans = (ans + t) % mod; } else { g = 1; t = y; } if (abs(y - x) != 1) { ans = (ans + y) % mod; } } return ans; } };
3,284
Sum of Consecutive Subarrays
Medium
<p>We call an array <code>arr</code> of length <code>n</code> <strong>consecutive</strong> if one of the following holds:</p> <ul> <li><code>arr[i] - arr[i - 1] == 1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> <li><code>arr[i] - arr[i - 1] == -1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> </ul> <p>The <strong>value</strong> of an array is the sum of its elements.</p> <p>For example, <code>[3, 4, 5]</code> is a consecutive array of value 12 and <code>[9, 8]</code> is another of value 17. While <code>[3, 4, 3]</code> and <code>[8, 6]</code> are not consecutive.</p> <p>Given an array of integers <code>nums</code>, return the <em>sum</em> of the <strong>values</strong> of all <strong>consecutive </strong><span data-keyword="subarray-nonempty">subarrays</span>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7.</code></p> <p><strong>Note</strong> that an array of length 1 is also considered consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[1, 2, 3]</code>.<br /> Sum of their values would be: <code>1 + 2 + 3 + 3 + 5 + 6 = 20</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[1]</code>, <code>[3]</code>, <code>[5]</code>, <code>[7]</code>.<br /> Sum of their values would be: <code>1 + 3 + 5 + 7 = 16</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,6,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">32</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[7]</code>, <code>[6]</code>, <code>[1]</code>, <code>[2]</code>, <code>[7, 6]</code>, <code>[1, 2]</code>.<br /> Sum of their values would be: <code>7 + 6 + 1 + 2 + 13 + 3 = 32</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>5</sup></code></li> </ul>
Array; Two Pointers; Dynamic Programming
Go
func getSum(nums []int) int { const mod int = 1e9 + 7 f, g := 1, 1 s, t := nums[0], nums[0] ans := nums[0] for i := 1; i < len(nums); i++ { x, y := nums[i-1], nums[i] if y-x == 1 { f++ s += f * y ans = (ans + s) % mod } else { f = 1 s = y } if y-x == -1 { g++ t += g * y ans = (ans + t) % mod } else { g = 1 t = y } if abs(y-x) != 1 { ans = (ans + y) % mod } } return ans } func abs(x int) int { if x < 0 { return -x } return x }
3,284
Sum of Consecutive Subarrays
Medium
<p>We call an array <code>arr</code> of length <code>n</code> <strong>consecutive</strong> if one of the following holds:</p> <ul> <li><code>arr[i] - arr[i - 1] == 1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> <li><code>arr[i] - arr[i - 1] == -1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> </ul> <p>The <strong>value</strong> of an array is the sum of its elements.</p> <p>For example, <code>[3, 4, 5]</code> is a consecutive array of value 12 and <code>[9, 8]</code> is another of value 17. While <code>[3, 4, 3]</code> and <code>[8, 6]</code> are not consecutive.</p> <p>Given an array of integers <code>nums</code>, return the <em>sum</em> of the <strong>values</strong> of all <strong>consecutive </strong><span data-keyword="subarray-nonempty">subarrays</span>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7.</code></p> <p><strong>Note</strong> that an array of length 1 is also considered consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[1, 2, 3]</code>.<br /> Sum of their values would be: <code>1 + 2 + 3 + 3 + 5 + 6 = 20</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[1]</code>, <code>[3]</code>, <code>[5]</code>, <code>[7]</code>.<br /> Sum of their values would be: <code>1 + 3 + 5 + 7 = 16</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,6,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">32</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[7]</code>, <code>[6]</code>, <code>[1]</code>, <code>[2]</code>, <code>[7, 6]</code>, <code>[1, 2]</code>.<br /> Sum of their values would be: <code>7 + 6 + 1 + 2 + 13 + 3 = 32</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>5</sup></code></li> </ul>
Array; Two Pointers; Dynamic Programming
Java
class Solution { public int getSum(int[] nums) { final int mod = (int) 1e9 + 7; long s = nums[0], t = nums[0], ans = nums[0]; int f = 1, g = 1; for (int i = 1; i < nums.length; ++i) { int x = nums[i - 1], y = nums[i]; if (y - x == 1) { ++f; s += 1L * f * y; ans = (ans + s) % mod; } else { f = 1; s = y; } if (y - x == -1) { ++g; t += 1L * g * y; ans = (ans + t) % mod; } else { g = 1; t = y; } if (Math.abs(y - x) != 1) { ans = (ans + y) % mod; } } return (int) ans; } }
3,284
Sum of Consecutive Subarrays
Medium
<p>We call an array <code>arr</code> of length <code>n</code> <strong>consecutive</strong> if one of the following holds:</p> <ul> <li><code>arr[i] - arr[i - 1] == 1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> <li><code>arr[i] - arr[i - 1] == -1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> </ul> <p>The <strong>value</strong> of an array is the sum of its elements.</p> <p>For example, <code>[3, 4, 5]</code> is a consecutive array of value 12 and <code>[9, 8]</code> is another of value 17. While <code>[3, 4, 3]</code> and <code>[8, 6]</code> are not consecutive.</p> <p>Given an array of integers <code>nums</code>, return the <em>sum</em> of the <strong>values</strong> of all <strong>consecutive </strong><span data-keyword="subarray-nonempty">subarrays</span>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7.</code></p> <p><strong>Note</strong> that an array of length 1 is also considered consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[1, 2, 3]</code>.<br /> Sum of their values would be: <code>1 + 2 + 3 + 3 + 5 + 6 = 20</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[1]</code>, <code>[3]</code>, <code>[5]</code>, <code>[7]</code>.<br /> Sum of their values would be: <code>1 + 3 + 5 + 7 = 16</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,6,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">32</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[7]</code>, <code>[6]</code>, <code>[1]</code>, <code>[2]</code>, <code>[7, 6]</code>, <code>[1, 2]</code>.<br /> Sum of their values would be: <code>7 + 6 + 1 + 2 + 13 + 3 = 32</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>5</sup></code></li> </ul>
Array; Two Pointers; Dynamic Programming
Python
class Solution: def getSum(self, nums: List[int]) -> int: mod = 10**9 + 7 f = g = 1 s = t = nums[0] ans = nums[0] for x, y in pairwise(nums): if y - x == 1: f += 1 s += f * y ans = (ans + s) % mod else: f = 1 s = y if y - x == -1: g += 1 t += g * y ans = (ans + t) % mod else: g = 1 t = y if abs(y - x) != 1: ans = (ans + y) % mod return ans
3,284
Sum of Consecutive Subarrays
Medium
<p>We call an array <code>arr</code> of length <code>n</code> <strong>consecutive</strong> if one of the following holds:</p> <ul> <li><code>arr[i] - arr[i - 1] == 1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> <li><code>arr[i] - arr[i - 1] == -1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> </ul> <p>The <strong>value</strong> of an array is the sum of its elements.</p> <p>For example, <code>[3, 4, 5]</code> is a consecutive array of value 12 and <code>[9, 8]</code> is another of value 17. While <code>[3, 4, 3]</code> and <code>[8, 6]</code> are not consecutive.</p> <p>Given an array of integers <code>nums</code>, return the <em>sum</em> of the <strong>values</strong> of all <strong>consecutive </strong><span data-keyword="subarray-nonempty">subarrays</span>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7.</code></p> <p><strong>Note</strong> that an array of length 1 is also considered consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">20</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[1, 2, 3]</code>.<br /> Sum of their values would be: <code>1 + 2 + 3 + 3 + 5 + 6 = 20</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,5,7]</span></p> <p><strong>Output:</strong> <span class="example-io">16</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[1]</code>, <code>[3]</code>, <code>[5]</code>, <code>[7]</code>.<br /> Sum of their values would be: <code>1 + 3 + 5 + 7 = 16</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,6,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">32</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subarrays are: <code>[7]</code>, <code>[6]</code>, <code>[1]</code>, <code>[2]</code>, <code>[7, 6]</code>, <code>[1, 2]</code>.<br /> Sum of their values would be: <code>7 + 6 + 1 + 2 + 13 + 3 = 32</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>5</sup></code></li> </ul>
Array; Two Pointers; Dynamic Programming
TypeScript
function getSum(nums: number[]): number { const mod = 10 ** 9 + 7; let f = 1, g = 1; let s = nums[0], t = nums[0]; let ans = nums[0]; for (let i = 1; i < nums.length; i++) { const x = nums[i - 1]; const y = nums[i]; if (y - x === 1) { f++; s += f * y; ans = (ans + s) % mod; } else { f = 1; s = y; } if (y - x === -1) { g++; t += g * y; ans = (ans + t) % mod; } else { g = 1; t = y; } if (Math.abs(y - x) !== 1) { ans = (ans + y) % mod; } } return ans; }
3,285
Find Indices of Stable Mountains
Easy
<p>There are <code>n</code> mountains in a row, and each mountain has a height. You are given an integer array <code>height</code> where <code>height[i]</code> represents the height of mountain <code>i</code>, and an integer <code>threshold</code>.</p> <p>A mountain is called <strong>stable</strong> if the mountain just before it (<strong>if it exists</strong>) has a height <strong>strictly greater</strong> than <code>threshold</code>. <strong>Note</strong> that mountain 0 is <strong>not</strong> stable.</p> <p>Return an array containing the indices of <em>all</em> <strong>stable</strong> mountains in <strong>any</strong> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [1,2,3,4,5], threshold = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mountain 3 is stable because <code>height[2] == 3</code> is greater than <code>threshold == 2</code>.</li> <li>Mountain 4 is stable because <code>height[3] == 4</code> is greater than <code>threshold == 2</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [10,1,10,1,10], threshold = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [10,1,10,1,10], threshold = 10</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == height.length &lt;= 100</code></li> <li><code>1 &lt;= height[i] &lt;= 100</code></li> <li><code>1 &lt;= threshold &lt;= 100</code></li> </ul>
Array
C++
class Solution { public: vector<int> stableMountains(vector<int>& height, int threshold) { vector<int> ans; for (int i = 1; i < height.size(); ++i) { if (height[i - 1] > threshold) { ans.push_back(i); } } return ans; } };
3,285
Find Indices of Stable Mountains
Easy
<p>There are <code>n</code> mountains in a row, and each mountain has a height. You are given an integer array <code>height</code> where <code>height[i]</code> represents the height of mountain <code>i</code>, and an integer <code>threshold</code>.</p> <p>A mountain is called <strong>stable</strong> if the mountain just before it (<strong>if it exists</strong>) has a height <strong>strictly greater</strong> than <code>threshold</code>. <strong>Note</strong> that mountain 0 is <strong>not</strong> stable.</p> <p>Return an array containing the indices of <em>all</em> <strong>stable</strong> mountains in <strong>any</strong> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [1,2,3,4,5], threshold = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mountain 3 is stable because <code>height[2] == 3</code> is greater than <code>threshold == 2</code>.</li> <li>Mountain 4 is stable because <code>height[3] == 4</code> is greater than <code>threshold == 2</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [10,1,10,1,10], threshold = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [10,1,10,1,10], threshold = 10</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == height.length &lt;= 100</code></li> <li><code>1 &lt;= height[i] &lt;= 100</code></li> <li><code>1 &lt;= threshold &lt;= 100</code></li> </ul>
Array
Go
func stableMountains(height []int, threshold int) (ans []int) { for i := 1; i < len(height); i++ { if height[i-1] > threshold { ans = append(ans, i) } } return }
3,285
Find Indices of Stable Mountains
Easy
<p>There are <code>n</code> mountains in a row, and each mountain has a height. You are given an integer array <code>height</code> where <code>height[i]</code> represents the height of mountain <code>i</code>, and an integer <code>threshold</code>.</p> <p>A mountain is called <strong>stable</strong> if the mountain just before it (<strong>if it exists</strong>) has a height <strong>strictly greater</strong> than <code>threshold</code>. <strong>Note</strong> that mountain 0 is <strong>not</strong> stable.</p> <p>Return an array containing the indices of <em>all</em> <strong>stable</strong> mountains in <strong>any</strong> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [1,2,3,4,5], threshold = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mountain 3 is stable because <code>height[2] == 3</code> is greater than <code>threshold == 2</code>.</li> <li>Mountain 4 is stable because <code>height[3] == 4</code> is greater than <code>threshold == 2</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [10,1,10,1,10], threshold = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [10,1,10,1,10], threshold = 10</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == height.length &lt;= 100</code></li> <li><code>1 &lt;= height[i] &lt;= 100</code></li> <li><code>1 &lt;= threshold &lt;= 100</code></li> </ul>
Array
Java
class Solution { public List<Integer> stableMountains(int[] height, int threshold) { List<Integer> ans = new ArrayList<>(); for (int i = 1; i < height.length; ++i) { if (height[i - 1] > threshold) { ans.add(i); } } return ans; } }
3,285
Find Indices of Stable Mountains
Easy
<p>There are <code>n</code> mountains in a row, and each mountain has a height. You are given an integer array <code>height</code> where <code>height[i]</code> represents the height of mountain <code>i</code>, and an integer <code>threshold</code>.</p> <p>A mountain is called <strong>stable</strong> if the mountain just before it (<strong>if it exists</strong>) has a height <strong>strictly greater</strong> than <code>threshold</code>. <strong>Note</strong> that mountain 0 is <strong>not</strong> stable.</p> <p>Return an array containing the indices of <em>all</em> <strong>stable</strong> mountains in <strong>any</strong> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [1,2,3,4,5], threshold = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mountain 3 is stable because <code>height[2] == 3</code> is greater than <code>threshold == 2</code>.</li> <li>Mountain 4 is stable because <code>height[3] == 4</code> is greater than <code>threshold == 2</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [10,1,10,1,10], threshold = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [10,1,10,1,10], threshold = 10</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == height.length &lt;= 100</code></li> <li><code>1 &lt;= height[i] &lt;= 100</code></li> <li><code>1 &lt;= threshold &lt;= 100</code></li> </ul>
Array
Python
class Solution: def stableMountains(self, height: List[int], threshold: int) -> List[int]: return [i for i in range(1, len(height)) if height[i - 1] > threshold]
3,285
Find Indices of Stable Mountains
Easy
<p>There are <code>n</code> mountains in a row, and each mountain has a height. You are given an integer array <code>height</code> where <code>height[i]</code> represents the height of mountain <code>i</code>, and an integer <code>threshold</code>.</p> <p>A mountain is called <strong>stable</strong> if the mountain just before it (<strong>if it exists</strong>) has a height <strong>strictly greater</strong> than <code>threshold</code>. <strong>Note</strong> that mountain 0 is <strong>not</strong> stable.</p> <p>Return an array containing the indices of <em>all</em> <strong>stable</strong> mountains in <strong>any</strong> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [1,2,3,4,5], threshold = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Mountain 3 is stable because <code>height[2] == 3</code> is greater than <code>threshold == 2</code>.</li> <li>Mountain 4 is stable because <code>height[3] == 4</code> is greater than <code>threshold == 2</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [10,1,10,1,10], threshold = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[1,3]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">height = [10,1,10,1,10], threshold = 10</span></p> <p><strong>Output:</strong> <span class="example-io">[]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == height.length &lt;= 100</code></li> <li><code>1 &lt;= height[i] &lt;= 100</code></li> <li><code>1 &lt;= threshold &lt;= 100</code></li> </ul>
Array
TypeScript
function stableMountains(height: number[], threshold: number): number[] { const ans: number[] = []; for (let i = 1; i < height.length; ++i) { if (height[i - 1] > threshold) { ans.push(i); } } return ans; }
3,286
Find a Safe Walk Through a Grid
Medium
<p>You are given an <code>m x n</code> binary matrix <code>grid</code> and an integer <code>health</code>.</p> <p>You start on the upper-left corner <code>(0, 0)</code> and would like to get to the lower-right corner <code>(m - 1, n - 1)</code>.</p> <p>You can move up, down, left, or right from one cell to another adjacent cell as long as your health <em>remains</em> <strong>positive</strong>.</p> <p>Cells <code>(i, j)</code> with <code>grid[i][j] = 1</code> are considered <strong>unsafe</strong> and reduce your health by 1.</p> <p>Return <code>true</code> if you can reach the final cell with a health value of 1 or more, 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">grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]], health = 1</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The final cell can be reached safely by walking along the gray cells below.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_1drawio.png" style="width: 301px; height: 121px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1,1,0,0,0],[1,0,1,0,0,0],[0,1,1,1,0,1],[0,0,1,0,1,0]], health = 3</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>A minimum of 4 health points is needed to reach the final cell safely.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_2drawio.png" style="width: 361px; height: 161px;" /></div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,1,1],[1,0,1],[1,1,1]], health = 5</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The final cell can be reached safely by walking along the gray cells below.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_3drawio.png" style="width: 181px; height: 121px;" /></p> <p>Any path that does not go through the cell <code>(1, 1)</code> is unsafe since your health will drop to 0 when reaching the final cell.</p> </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><font face="monospace">2 &lt;= m * n</font></code></li> <li><code>1 &lt;= health &lt;= m + n</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> </ul>
Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
C++
class Solution { public: bool findSafeWalk(vector<vector<int>>& grid, int health) { int m = grid.size(); int n = grid[0].size(); vector<vector<int>> dist(m, vector<int>(n, INT_MAX)); dist[0][0] = grid[0][0]; queue<pair<int, int>> q; q.emplace(0, 0); int dirs[5] = {-1, 0, 1, 0, -1}; while (!q.empty()) { auto [x, y] = q.front(); q.pop(); for (int i = 0; i < 4; ++i) { int nx = x + dirs[i]; int ny = y + dirs[i + 1]; if (nx >= 0 && nx < m && ny >= 0 && ny < n && dist[nx][ny] > dist[x][y] + grid[nx][ny]) { dist[nx][ny] = dist[x][y] + grid[nx][ny]; q.emplace(nx, ny); } } } return dist[m - 1][n - 1] < health; } };
3,286
Find a Safe Walk Through a Grid
Medium
<p>You are given an <code>m x n</code> binary matrix <code>grid</code> and an integer <code>health</code>.</p> <p>You start on the upper-left corner <code>(0, 0)</code> and would like to get to the lower-right corner <code>(m - 1, n - 1)</code>.</p> <p>You can move up, down, left, or right from one cell to another adjacent cell as long as your health <em>remains</em> <strong>positive</strong>.</p> <p>Cells <code>(i, j)</code> with <code>grid[i][j] = 1</code> are considered <strong>unsafe</strong> and reduce your health by 1.</p> <p>Return <code>true</code> if you can reach the final cell with a health value of 1 or more, 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">grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]], health = 1</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The final cell can be reached safely by walking along the gray cells below.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_1drawio.png" style="width: 301px; height: 121px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1,1,0,0,0],[1,0,1,0,0,0],[0,1,1,1,0,1],[0,0,1,0,1,0]], health = 3</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>A minimum of 4 health points is needed to reach the final cell safely.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_2drawio.png" style="width: 361px; height: 161px;" /></div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,1,1],[1,0,1],[1,1,1]], health = 5</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The final cell can be reached safely by walking along the gray cells below.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_3drawio.png" style="width: 181px; height: 121px;" /></p> <p>Any path that does not go through the cell <code>(1, 1)</code> is unsafe since your health will drop to 0 when reaching the final cell.</p> </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><font face="monospace">2 &lt;= m * n</font></code></li> <li><code>1 &lt;= health &lt;= m + n</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> </ul>
Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
Go
func findSafeWalk(grid [][]int, health int) bool { m, n := len(grid), len(grid[0]) dist := make([][]int, m) for i := range dist { dist[i] = make([]int, n) for j := range dist[i] { dist[i][j] = math.MaxInt32 } } dist[0][0] = grid[0][0] q := [][2]int{{0, 0}} dirs := []int{-1, 0, 1, 0, -1} for len(q) > 0 { curr := q[0] q = q[1:] x, y := curr[0], curr[1] for i := 0; i < 4; i++ { nx, ny := x+dirs[i], y+dirs[i+1] if nx >= 0 && nx < m && ny >= 0 && ny < n && dist[nx][ny] > dist[x][y]+grid[nx][ny] { dist[nx][ny] = dist[x][y] + grid[nx][ny] q = append(q, [2]int{nx, ny}) } } } return dist[m-1][n-1] < health }
3,286
Find a Safe Walk Through a Grid
Medium
<p>You are given an <code>m x n</code> binary matrix <code>grid</code> and an integer <code>health</code>.</p> <p>You start on the upper-left corner <code>(0, 0)</code> and would like to get to the lower-right corner <code>(m - 1, n - 1)</code>.</p> <p>You can move up, down, left, or right from one cell to another adjacent cell as long as your health <em>remains</em> <strong>positive</strong>.</p> <p>Cells <code>(i, j)</code> with <code>grid[i][j] = 1</code> are considered <strong>unsafe</strong> and reduce your health by 1.</p> <p>Return <code>true</code> if you can reach the final cell with a health value of 1 or more, 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">grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]], health = 1</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The final cell can be reached safely by walking along the gray cells below.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_1drawio.png" style="width: 301px; height: 121px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1,1,0,0,0],[1,0,1,0,0,0],[0,1,1,1,0,1],[0,0,1,0,1,0]], health = 3</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>A minimum of 4 health points is needed to reach the final cell safely.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_2drawio.png" style="width: 361px; height: 161px;" /></div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,1,1],[1,0,1],[1,1,1]], health = 5</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The final cell can be reached safely by walking along the gray cells below.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_3drawio.png" style="width: 181px; height: 121px;" /></p> <p>Any path that does not go through the cell <code>(1, 1)</code> is unsafe since your health will drop to 0 when reaching the final cell.</p> </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><font face="monospace">2 &lt;= m * n</font></code></li> <li><code>1 &lt;= health &lt;= m + n</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> </ul>
Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
Java
class Solution { public boolean findSafeWalk(List<List<Integer>> grid, int health) { int m = grid.size(); int n = grid.get(0).size(); int[][] dist = new int[m][n]; for (int[] row : dist) { Arrays.fill(row, Integer.MAX_VALUE); } dist[0][0] = grid.get(0).get(0); Deque<int[]> q = new ArrayDeque<>(); q.offer(new int[] {0, 0}); final int[] dirs = {-1, 0, 1, 0, -1}; while (!q.isEmpty()) { int[] curr = q.poll(); int x = curr[0], y = curr[1]; for (int i = 0; i < 4; i++) { int nx = x + dirs[i]; int ny = y + dirs[i + 1]; if (nx >= 0 && nx < m && ny >= 0 && ny < n && dist[nx][ny] > dist[x][y] + grid.get(nx).get(ny)) { dist[nx][ny] = dist[x][y] + grid.get(nx).get(ny); q.offer(new int[] {nx, ny}); } } } return dist[m - 1][n - 1] < health; } }
3,286
Find a Safe Walk Through a Grid
Medium
<p>You are given an <code>m x n</code> binary matrix <code>grid</code> and an integer <code>health</code>.</p> <p>You start on the upper-left corner <code>(0, 0)</code> and would like to get to the lower-right corner <code>(m - 1, n - 1)</code>.</p> <p>You can move up, down, left, or right from one cell to another adjacent cell as long as your health <em>remains</em> <strong>positive</strong>.</p> <p>Cells <code>(i, j)</code> with <code>grid[i][j] = 1</code> are considered <strong>unsafe</strong> and reduce your health by 1.</p> <p>Return <code>true</code> if you can reach the final cell with a health value of 1 or more, 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">grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]], health = 1</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The final cell can be reached safely by walking along the gray cells below.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_1drawio.png" style="width: 301px; height: 121px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1,1,0,0,0],[1,0,1,0,0,0],[0,1,1,1,0,1],[0,0,1,0,1,0]], health = 3</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>A minimum of 4 health points is needed to reach the final cell safely.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_2drawio.png" style="width: 361px; height: 161px;" /></div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,1,1],[1,0,1],[1,1,1]], health = 5</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The final cell can be reached safely by walking along the gray cells below.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_3drawio.png" style="width: 181px; height: 121px;" /></p> <p>Any path that does not go through the cell <code>(1, 1)</code> is unsafe since your health will drop to 0 when reaching the final cell.</p> </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><font face="monospace">2 &lt;= m * n</font></code></li> <li><code>1 &lt;= health &lt;= m + n</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> </ul>
Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
Python
class Solution: def findSafeWalk(self, grid: List[List[int]], health: int) -> bool: m, n = len(grid), len(grid[0]) dist = [[inf] * n for _ in range(m)] dist[0][0] = grid[0][0] q = deque([(0, 0)]) dirs = (-1, 0, 1, 0, -1) while q: x, y = q.popleft() for a, b in pairwise(dirs): nx, ny = x + a, y + b if ( 0 <= nx < m and 0 <= ny < n and dist[nx][ny] > dist[x][y] + grid[nx][ny] ): dist[nx][ny] = dist[x][y] + grid[nx][ny] q.append((nx, ny)) return dist[-1][-1] < health
3,286
Find a Safe Walk Through a Grid
Medium
<p>You are given an <code>m x n</code> binary matrix <code>grid</code> and an integer <code>health</code>.</p> <p>You start on the upper-left corner <code>(0, 0)</code> and would like to get to the lower-right corner <code>(m - 1, n - 1)</code>.</p> <p>You can move up, down, left, or right from one cell to another adjacent cell as long as your health <em>remains</em> <strong>positive</strong>.</p> <p>Cells <code>(i, j)</code> with <code>grid[i][j] = 1</code> are considered <strong>unsafe</strong> and reduce your health by 1.</p> <p>Return <code>true</code> if you can reach the final cell with a health value of 1 or more, 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">grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]], health = 1</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The final cell can be reached safely by walking along the gray cells below.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_1drawio.png" style="width: 301px; height: 121px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[0,1,1,0,0,0],[1,0,1,0,0,0],[0,1,1,1,0,1],[0,0,1,0,1,0]], health = 3</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>A minimum of 4 health points is needed to reach the final cell safely.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_2drawio.png" style="width: 361px; height: 161px;" /></div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">grid = [[1,1,1],[1,0,1],[1,1,1]], health = 5</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The final cell can be reached safely by walking along the gray cells below.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3200-3299/3286.Find%20a%20Safe%20Walk%20Through%20a%20Grid/images/3868_examples_3drawio.png" style="width: 181px; height: 121px;" /></p> <p>Any path that does not go through the cell <code>(1, 1)</code> is unsafe since your health will drop to 0 when reaching the final cell.</p> </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><font face="monospace">2 &lt;= m * n</font></code></li> <li><code>1 &lt;= health &lt;= m + n</code></li> <li><code>grid[i][j]</code> is either 0 or 1.</li> </ul>
Breadth-First Search; Graph; Array; Matrix; Shortest Path; Heap (Priority Queue)
TypeScript
function findSafeWalk(grid: number[][], health: number): boolean { const m = grid.length; const n = grid[0].length; const dist: number[][] = Array.from({ length: m }, () => Array(n).fill(Infinity)); dist[0][0] = grid[0][0]; const q: [number, number][] = [[0, 0]]; const dirs = [-1, 0, 1, 0, -1]; while (q.length > 0) { const [x, y] = q.shift()!; for (let i = 0; i < 4; i++) { const nx = x + dirs[i]; const ny = y + dirs[i + 1]; if ( nx >= 0 && nx < m && ny >= 0 && ny < n && dist[nx][ny] > dist[x][y] + grid[nx][ny] ) { dist[nx][ny] = dist[x][y] + grid[nx][ny]; q.push([nx, ny]); } } } return dist[m - 1][n - 1] < health; }
3,287
Find the Maximum Sequence Value of Array
Hard
<p>You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>value</strong> of a sequence <code>seq</code> of size <code>2 * x</code> is defined as:</p> <ul> <li><code>(seq[0] OR seq[1] OR ... OR seq[x - 1]) XOR (seq[x] OR seq[x + 1] OR ... OR seq[2 * x - 1])</code>.</li> </ul> <p>Return the <strong>maximum</strong> <strong>value</strong> of any <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code> having size <code>2 * k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,6,7], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[2, 7]</code> has the maximum value of <code>2 XOR 7 = 5</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,5,6,7], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[4, 5, 6, 7]</code> has the maximum value of <code>(4 OR 5) XOR (6 OR 7) = 2</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 400</code></li> <li><code>1 &lt;= nums[i] &lt; 2<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length / 2</code></li> </ul>
Bit Manipulation; Array; Dynamic Programming
C++
class Solution { public: int maxValue(vector<int>& nums, int k) { int m = 1 << 7; int n = nums.size(); vector<vector<vector<bool>>> f(n + 1, vector<vector<bool>>(k + 2, vector<bool>(m, false))); f[0][0][0] = true; for (int i = 0; i < n; i++) { for (int j = 0; j <= k; j++) { for (int x = 0; x < m; x++) { if (f[i][j][x]) { f[i + 1][j][x] = true; f[i + 1][j + 1][x | nums[i]] = true; } } } } vector<vector<vector<bool>>> g(n + 1, vector<vector<bool>>(k + 2, vector<bool>(m, false))); g[n][0][0] = true; for (int i = n; i > 0; i--) { for (int j = 0; j <= k; j++) { for (int y = 0; y < m; y++) { if (g[i][j][y]) { g[i - 1][j][y] = true; g[i - 1][j + 1][y | nums[i - 1]] = true; } } } } int ans = 0; for (int i = k; i <= n - k; i++) { for (int x = 0; x < m; x++) { if (f[i][k][x]) { for (int y = 0; y < m; y++) { if (g[i][k][y]) { ans = max(ans, x ^ y); } } } } } return ans; } };
3,287
Find the Maximum Sequence Value of Array
Hard
<p>You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>value</strong> of a sequence <code>seq</code> of size <code>2 * x</code> is defined as:</p> <ul> <li><code>(seq[0] OR seq[1] OR ... OR seq[x - 1]) XOR (seq[x] OR seq[x + 1] OR ... OR seq[2 * x - 1])</code>.</li> </ul> <p>Return the <strong>maximum</strong> <strong>value</strong> of any <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code> having size <code>2 * k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,6,7], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[2, 7]</code> has the maximum value of <code>2 XOR 7 = 5</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,5,6,7], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[4, 5, 6, 7]</code> has the maximum value of <code>(4 OR 5) XOR (6 OR 7) = 2</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 400</code></li> <li><code>1 &lt;= nums[i] &lt; 2<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length / 2</code></li> </ul>
Bit Manipulation; Array; Dynamic Programming
Go
func maxValue(nums []int, k int) int { m := 1 << 7 n := len(nums) f := make([][][]bool, n+1) for i := range f { f[i] = make([][]bool, k+2) for j := range f[i] { f[i][j] = make([]bool, m) } } f[0][0][0] = true for i := 0; i < n; i++ { for j := 0; j <= k; j++ { for x := 0; x < m; x++ { if f[i][j][x] { f[i+1][j][x] = true f[i+1][j+1][x|nums[i]] = true } } } } g := make([][][]bool, n+1) for i := range g { g[i] = make([][]bool, k+2) for j := range g[i] { g[i][j] = make([]bool, m) } } g[n][0][0] = true for i := n; i > 0; i-- { for j := 0; j <= k; j++ { for y := 0; y < m; y++ { if g[i][j][y] { g[i-1][j][y] = true g[i-1][j+1][y|nums[i-1]] = true } } } } ans := 0 for i := k; i <= n-k; i++ { for x := 0; x < m; x++ { if f[i][k][x] { for y := 0; y < m; y++ { if g[i][k][y] { ans = max(ans, x^y) } } } } } return ans }
3,287
Find the Maximum Sequence Value of Array
Hard
<p>You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>value</strong> of a sequence <code>seq</code> of size <code>2 * x</code> is defined as:</p> <ul> <li><code>(seq[0] OR seq[1] OR ... OR seq[x - 1]) XOR (seq[x] OR seq[x + 1] OR ... OR seq[2 * x - 1])</code>.</li> </ul> <p>Return the <strong>maximum</strong> <strong>value</strong> of any <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code> having size <code>2 * k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,6,7], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[2, 7]</code> has the maximum value of <code>2 XOR 7 = 5</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,5,6,7], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[4, 5, 6, 7]</code> has the maximum value of <code>(4 OR 5) XOR (6 OR 7) = 2</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 400</code></li> <li><code>1 &lt;= nums[i] &lt; 2<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length / 2</code></li> </ul>
Bit Manipulation; Array; Dynamic Programming
Java
class Solution { public int maxValue(int[] nums, int k) { int m = 1 << 7; int n = nums.length; boolean[][][] f = new boolean[n + 1][k + 2][m]; f[0][0][0] = true; for (int i = 0; i < n; i++) { for (int j = 0; j <= k; j++) { for (int x = 0; x < m; x++) { if (f[i][j][x]) { f[i + 1][j][x] = true; f[i + 1][j + 1][x | nums[i]] = true; } } } } boolean[][][] g = new boolean[n + 1][k + 2][m]; g[n][0][0] = true; for (int i = n; i > 0; i--) { for (int j = 0; j <= k; j++) { for (int y = 0; y < m; y++) { if (g[i][j][y]) { g[i - 1][j][y] = true; g[i - 1][j + 1][y | nums[i - 1]] = true; } } } } int ans = 0; for (int i = k; i <= n - k; i++) { for (int x = 0; x < m; x++) { if (f[i][k][x]) { for (int y = 0; y < m; y++) { if (g[i][k][y]) { ans = Math.max(ans, x ^ y); } } } } } return ans; } }
3,287
Find the Maximum Sequence Value of Array
Hard
<p>You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>value</strong> of a sequence <code>seq</code> of size <code>2 * x</code> is defined as:</p> <ul> <li><code>(seq[0] OR seq[1] OR ... OR seq[x - 1]) XOR (seq[x] OR seq[x + 1] OR ... OR seq[2 * x - 1])</code>.</li> </ul> <p>Return the <strong>maximum</strong> <strong>value</strong> of any <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code> having size <code>2 * k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,6,7], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[2, 7]</code> has the maximum value of <code>2 XOR 7 = 5</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,5,6,7], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[4, 5, 6, 7]</code> has the maximum value of <code>(4 OR 5) XOR (6 OR 7) = 2</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 400</code></li> <li><code>1 &lt;= nums[i] &lt; 2<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length / 2</code></li> </ul>
Bit Manipulation; Array; Dynamic Programming
Python
class Solution: def maxValue(self, nums: List[int], k: int) -> int: m = 1 << 7 n = len(nums) f = [[[False] * m for _ in range(k + 2)] for _ in range(n + 1)] f[0][0][0] = True for i in range(n): for j in range(k + 1): for x in range(m): f[i + 1][j][x] |= f[i][j][x] f[i + 1][j + 1][x | nums[i]] |= f[i][j][x] g = [[[False] * m for _ in range(k + 2)] for _ in range(n + 1)] g[n][0][0] = True for i in range(n, 0, -1): for j in range(k + 1): for y in range(m): g[i - 1][j][y] |= g[i][j][y] g[i - 1][j + 1][y | nums[i - 1]] |= g[i][j][y] ans = 0 for i in range(k, n - k + 1): for x in range(m): if f[i][k][x]: for y in range(m): if g[i][k][y]: ans = max(ans, x ^ y) return ans
3,287
Find the Maximum Sequence Value of Array
Hard
<p>You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>value</strong> of a sequence <code>seq</code> of size <code>2 * x</code> is defined as:</p> <ul> <li><code>(seq[0] OR seq[1] OR ... OR seq[x - 1]) XOR (seq[x] OR seq[x + 1] OR ... OR seq[2 * x - 1])</code>.</li> </ul> <p>Return the <strong>maximum</strong> <strong>value</strong> of any <span data-keyword="subsequence-array">subsequence</span> of <code>nums</code> having size <code>2 * k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,6,7], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[2, 7]</code> has the maximum value of <code>2 XOR 7 = 5</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,2,5,6,7], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The subsequence <code>[4, 5, 6, 7]</code> has the maximum value of <code>(4 OR 5) XOR (6 OR 7) = 2</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 400</code></li> <li><code>1 &lt;= nums[i] &lt; 2<sup>7</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length / 2</code></li> </ul>
Bit Manipulation; Array; Dynamic Programming
TypeScript
function maxValue(nums: number[], k: number): number { const m = 1 << 7; const n = nums.length; const f: boolean[][][] = Array.from({ length: n + 1 }, () => Array.from({ length: k + 2 }, () => Array(m).fill(false)), ); f[0][0][0] = true; for (let i = 0; i < n; i++) { for (let j = 0; j <= k; j++) { for (let x = 0; x < m; x++) { if (f[i][j][x]) { f[i + 1][j][x] = true; f[i + 1][j + 1][x | nums[i]] = true; } } } } const g: boolean[][][] = Array.from({ length: n + 1 }, () => Array.from({ length: k + 2 }, () => Array(m).fill(false)), ); g[n][0][0] = true; for (let i = n; i > 0; i--) { for (let j = 0; j <= k; j++) { for (let y = 0; y < m; y++) { if (g[i][j][y]) { g[i - 1][j][y] = true; g[i - 1][j + 1][y | nums[i - 1]] = true; } } } } let ans = 0; for (let i = k; i <= n - k; i++) { for (let x = 0; x < m; x++) { if (f[i][k][x]) { for (let y = 0; y < m; y++) { if (g[i][k][y]) { ans = Math.max(ans, x ^ y); } } } } } return ans; }
3,289
The Two Sneaky Numbers of Digitville
Easy
<p>In the town of Digitville, there was a list of numbers called <code>nums</code> containing integers from <code>0</code> to <code>n - 1</code>. Each number was supposed to appear <strong>exactly once</strong> in the list, however, <strong>two</strong> mischievous numbers sneaked in an <em>additional time</em>, making the list longer than usual.<!-- notionvc: c37cfb04-95eb-4273-85d5-3c52d0525b95 --></p> <p>As the town detective, your task is to find these two sneaky numbers. Return an array of size <strong>two</strong> containing the two numbers (in <em>any order</em>), so peace can return to Digitville.<!-- notionvc: 345db5be-c788-4828-9836-eefed31c982f --></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 = [0,1,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>The numbers 0 and 1 each appear twice in the array.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,3,2,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,3]</span></p> <p><strong>Explanation: </strong></p> <p>The numbers 2 and 3 each appear twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,1,5,4,3,4,6,0,9,5,8,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5]</span></p> <p><strong>Explanation: </strong></p> <p>The numbers 4 and 5 each appear twice in the array.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-stringify-border="0" data-stringify-indent="1"><code>2 &lt;= n &lt;= 100</code></li> <li data-stringify-border="0" data-stringify-indent="1"><code>nums.length == n + 2</code></li> <li data-stringify-border="0" data-stringify-indent="1"><code data-stringify-type="code">0 &lt;= nums[i] &lt; n</code></li> <li data-stringify-border="0" data-stringify-indent="1">The input is generated such that <code>nums</code> contains <strong>exactly</strong> two repeated elements.</li> </ul>
Array; Hash Table; Math
C++
class Solution { public: vector<int> getSneakyNumbers(vector<int>& nums) { vector<int> ans; int cnt[100]{}; for (int x : nums) { if (++cnt[x] == 2) { ans.push_back(x); } } return ans; } };
3,289
The Two Sneaky Numbers of Digitville
Easy
<p>In the town of Digitville, there was a list of numbers called <code>nums</code> containing integers from <code>0</code> to <code>n - 1</code>. Each number was supposed to appear <strong>exactly once</strong> in the list, however, <strong>two</strong> mischievous numbers sneaked in an <em>additional time</em>, making the list longer than usual.<!-- notionvc: c37cfb04-95eb-4273-85d5-3c52d0525b95 --></p> <p>As the town detective, your task is to find these two sneaky numbers. Return an array of size <strong>two</strong> containing the two numbers (in <em>any order</em>), so peace can return to Digitville.<!-- notionvc: 345db5be-c788-4828-9836-eefed31c982f --></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 = [0,1,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>The numbers 0 and 1 each appear twice in the array.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,3,2,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,3]</span></p> <p><strong>Explanation: </strong></p> <p>The numbers 2 and 3 each appear twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,1,5,4,3,4,6,0,9,5,8,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5]</span></p> <p><strong>Explanation: </strong></p> <p>The numbers 4 and 5 each appear twice in the array.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-stringify-border="0" data-stringify-indent="1"><code>2 &lt;= n &lt;= 100</code></li> <li data-stringify-border="0" data-stringify-indent="1"><code>nums.length == n + 2</code></li> <li data-stringify-border="0" data-stringify-indent="1"><code data-stringify-type="code">0 &lt;= nums[i] &lt; n</code></li> <li data-stringify-border="0" data-stringify-indent="1">The input is generated such that <code>nums</code> contains <strong>exactly</strong> two repeated elements.</li> </ul>
Array; Hash Table; Math
Go
func getSneakyNumbers(nums []int) (ans []int) { cnt := [100]int{} for _, x := range nums { cnt[x]++ if cnt[x] == 2 { ans = append(ans, x) } } return }
3,289
The Two Sneaky Numbers of Digitville
Easy
<p>In the town of Digitville, there was a list of numbers called <code>nums</code> containing integers from <code>0</code> to <code>n - 1</code>. Each number was supposed to appear <strong>exactly once</strong> in the list, however, <strong>two</strong> mischievous numbers sneaked in an <em>additional time</em>, making the list longer than usual.<!-- notionvc: c37cfb04-95eb-4273-85d5-3c52d0525b95 --></p> <p>As the town detective, your task is to find these two sneaky numbers. Return an array of size <strong>two</strong> containing the two numbers (in <em>any order</em>), so peace can return to Digitville.<!-- notionvc: 345db5be-c788-4828-9836-eefed31c982f --></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 = [0,1,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>The numbers 0 and 1 each appear twice in the array.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,3,2,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,3]</span></p> <p><strong>Explanation: </strong></p> <p>The numbers 2 and 3 each appear twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,1,5,4,3,4,6,0,9,5,8,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5]</span></p> <p><strong>Explanation: </strong></p> <p>The numbers 4 and 5 each appear twice in the array.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-stringify-border="0" data-stringify-indent="1"><code>2 &lt;= n &lt;= 100</code></li> <li data-stringify-border="0" data-stringify-indent="1"><code>nums.length == n + 2</code></li> <li data-stringify-border="0" data-stringify-indent="1"><code data-stringify-type="code">0 &lt;= nums[i] &lt; n</code></li> <li data-stringify-border="0" data-stringify-indent="1">The input is generated such that <code>nums</code> contains <strong>exactly</strong> two repeated elements.</li> </ul>
Array; Hash Table; Math
Java
class Solution { public int[] getSneakyNumbers(int[] nums) { int[] ans = new int[2]; int[] cnt = new int[100]; int k = 0; for (int x : nums) { if (++cnt[x] == 2) { ans[k++] = x; } } return ans; } }
3,289
The Two Sneaky Numbers of Digitville
Easy
<p>In the town of Digitville, there was a list of numbers called <code>nums</code> containing integers from <code>0</code> to <code>n - 1</code>. Each number was supposed to appear <strong>exactly once</strong> in the list, however, <strong>two</strong> mischievous numbers sneaked in an <em>additional time</em>, making the list longer than usual.<!-- notionvc: c37cfb04-95eb-4273-85d5-3c52d0525b95 --></p> <p>As the town detective, your task is to find these two sneaky numbers. Return an array of size <strong>two</strong> containing the two numbers (in <em>any order</em>), so peace can return to Digitville.<!-- notionvc: 345db5be-c788-4828-9836-eefed31c982f --></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 = [0,1,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>The numbers 0 and 1 each appear twice in the array.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,3,2,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,3]</span></p> <p><strong>Explanation: </strong></p> <p>The numbers 2 and 3 each appear twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,1,5,4,3,4,6,0,9,5,8,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5]</span></p> <p><strong>Explanation: </strong></p> <p>The numbers 4 and 5 each appear twice in the array.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-stringify-border="0" data-stringify-indent="1"><code>2 &lt;= n &lt;= 100</code></li> <li data-stringify-border="0" data-stringify-indent="1"><code>nums.length == n + 2</code></li> <li data-stringify-border="0" data-stringify-indent="1"><code data-stringify-type="code">0 &lt;= nums[i] &lt; n</code></li> <li data-stringify-border="0" data-stringify-indent="1">The input is generated such that <code>nums</code> contains <strong>exactly</strong> two repeated elements.</li> </ul>
Array; Hash Table; Math
Python
class Solution: def getSneakyNumbers(self, nums: List[int]) -> List[int]: cnt = Counter(nums) return [x for x, v in cnt.items() if v == 2]
3,289
The Two Sneaky Numbers of Digitville
Easy
<p>In the town of Digitville, there was a list of numbers called <code>nums</code> containing integers from <code>0</code> to <code>n - 1</code>. Each number was supposed to appear <strong>exactly once</strong> in the list, however, <strong>two</strong> mischievous numbers sneaked in an <em>additional time</em>, making the list longer than usual.<!-- notionvc: c37cfb04-95eb-4273-85d5-3c52d0525b95 --></p> <p>As the town detective, your task is to find these two sneaky numbers. Return an array of size <strong>two</strong> containing the two numbers (in <em>any order</em>), so peace can return to Digitville.<!-- notionvc: 345db5be-c788-4828-9836-eefed31c982f --></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 = [0,1,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1]</span></p> <p><strong>Explanation:</strong></p> <p>The numbers 0 and 1 each appear twice in the array.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,3,2,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,3]</span></p> <p><strong>Explanation: </strong></p> <p>The numbers 2 and 3 each appear twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [7,1,5,4,3,4,6,0,9,5,8,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5]</span></p> <p><strong>Explanation: </strong></p> <p>The numbers 4 and 5 each appear twice in the array.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-stringify-border="0" data-stringify-indent="1"><code>2 &lt;= n &lt;= 100</code></li> <li data-stringify-border="0" data-stringify-indent="1"><code>nums.length == n + 2</code></li> <li data-stringify-border="0" data-stringify-indent="1"><code data-stringify-type="code">0 &lt;= nums[i] &lt; n</code></li> <li data-stringify-border="0" data-stringify-indent="1">The input is generated such that <code>nums</code> contains <strong>exactly</strong> two repeated elements.</li> </ul>
Array; Hash Table; Math
TypeScript
function getSneakyNumbers(nums: number[]): number[] { const ans: number[] = []; const cnt: number[] = Array(100).fill(0); for (const x of nums) { if (++cnt[x] > 1) { ans.push(x); } } return ans; }
3,290
Maximum Multiplication Score
Medium
<p>You are given an integer array <code>a</code> of size 4 and another integer array <code>b</code> of size <strong>at least</strong> 4.</p> <p>You need to choose 4 indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, <code>i<sub>2</sub></code>, and <code>i<sub>3</sub></code> from the array <code>b</code> such that <code>i<sub>0</sub> &lt; i<sub>1</sub> &lt; i<sub>2</sub> &lt; i<sub>3</sub></code>. Your score will be equal to the value <code>a[0] * b[i<sub>0</sub>] + a[1] * b[i<sub>1</sub>] + a[2] * b[i<sub>2</sub>] + a[3] * b[i<sub>3</sub>]</code>.</p> <p>Return the <strong>maximum</strong> score you can achieve.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [3,2,5,6], b = [2,-6,4,-5,-3,2,-7]</span></p> <p><strong>Output:</strong> <span class="example-io">26</span></p> <p><strong>Explanation:</strong><br /> We can choose the indices 0, 1, 2, and 5. The score will be <code>3 * 2 + 2 * (-6) + 5 * 4 + 6 * 2 = 26</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [-1,4,5,-2], b = [-5,-1,-3,-2,-4]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> We can choose the indices 0, 1, 3, and 4. The score will be <code>(-1) * (-5) + 4 * (-1) + 5 * (-2) + (-2) * (-4) = -1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>a.length == 4</code></li> <li><code>4 &lt;= b.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= a[i], b[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: long long maxScore(vector<int>& a, vector<int>& b) { int m = a.size(), n = b.size(); long long f[m][n]; memset(f, -1, sizeof(f)); auto dfs = [&](this auto&& dfs, int i, int j) -> long long { if (j >= n) { return i >= m ? 0 : LLONG_MIN / 2; } if (i >= m) { return 0; } if (f[i][j] != -1) { return f[i][j]; } return f[i][j] = max(dfs(i, j + 1), 1LL * a[i] * b[j] + dfs(i + 1, j + 1)); }; return dfs(0, 0); } };
3,290
Maximum Multiplication Score
Medium
<p>You are given an integer array <code>a</code> of size 4 and another integer array <code>b</code> of size <strong>at least</strong> 4.</p> <p>You need to choose 4 indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, <code>i<sub>2</sub></code>, and <code>i<sub>3</sub></code> from the array <code>b</code> such that <code>i<sub>0</sub> &lt; i<sub>1</sub> &lt; i<sub>2</sub> &lt; i<sub>3</sub></code>. Your score will be equal to the value <code>a[0] * b[i<sub>0</sub>] + a[1] * b[i<sub>1</sub>] + a[2] * b[i<sub>2</sub>] + a[3] * b[i<sub>3</sub>]</code>.</p> <p>Return the <strong>maximum</strong> score you can achieve.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [3,2,5,6], b = [2,-6,4,-5,-3,2,-7]</span></p> <p><strong>Output:</strong> <span class="example-io">26</span></p> <p><strong>Explanation:</strong><br /> We can choose the indices 0, 1, 2, and 5. The score will be <code>3 * 2 + 2 * (-6) + 5 * 4 + 6 * 2 = 26</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [-1,4,5,-2], b = [-5,-1,-3,-2,-4]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> We can choose the indices 0, 1, 3, and 4. The score will be <code>(-1) * (-5) + 4 * (-1) + 5 * (-2) + (-2) * (-4) = -1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>a.length == 4</code></li> <li><code>4 &lt;= b.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= a[i], b[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Dynamic Programming
Go
func maxScore(a []int, b []int) int64 { m, n := len(a), len(b) f := make([][]int64, m) for i := range f { f[i] = make([]int64, n) for j := range f[i] { f[i][j] = -1 } } var dfs func(i, j int) int64 dfs = func(i, j int) int64 { if j >= n { if i >= m { return 0 } return math.MinInt64 / 2 } if i >= m { return 0 } if f[i][j] != -1 { return f[i][j] } f[i][j] = max(dfs(i, j+1), int64(a[i])*int64(b[j])+dfs(i+1, j+1)) return f[i][j] } return dfs(0, 0) }
3,290
Maximum Multiplication Score
Medium
<p>You are given an integer array <code>a</code> of size 4 and another integer array <code>b</code> of size <strong>at least</strong> 4.</p> <p>You need to choose 4 indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, <code>i<sub>2</sub></code>, and <code>i<sub>3</sub></code> from the array <code>b</code> such that <code>i<sub>0</sub> &lt; i<sub>1</sub> &lt; i<sub>2</sub> &lt; i<sub>3</sub></code>. Your score will be equal to the value <code>a[0] * b[i<sub>0</sub>] + a[1] * b[i<sub>1</sub>] + a[2] * b[i<sub>2</sub>] + a[3] * b[i<sub>3</sub>]</code>.</p> <p>Return the <strong>maximum</strong> score you can achieve.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [3,2,5,6], b = [2,-6,4,-5,-3,2,-7]</span></p> <p><strong>Output:</strong> <span class="example-io">26</span></p> <p><strong>Explanation:</strong><br /> We can choose the indices 0, 1, 2, and 5. The score will be <code>3 * 2 + 2 * (-6) + 5 * 4 + 6 * 2 = 26</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [-1,4,5,-2], b = [-5,-1,-3,-2,-4]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> We can choose the indices 0, 1, 3, and 4. The score will be <code>(-1) * (-5) + 4 * (-1) + 5 * (-2) + (-2) * (-4) = -1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>a.length == 4</code></li> <li><code>4 &lt;= b.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= a[i], b[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Dynamic Programming
Java
class Solution { private Long[][] f; private int[] a; private int[] b; public long maxScore(int[] a, int[] b) { f = new Long[a.length][b.length]; this.a = a; this.b = b; return dfs(0, 0); } private long dfs(int i, int j) { if (j >= b.length) { return i >= a.length ? 0 : Long.MIN_VALUE / 2; } if (i >= a.length) { return 0; } if (f[i][j] != null) { return f[i][j]; } return f[i][j] = Math.max(dfs(i, j + 1), 1L * a[i] * b[j] + dfs(i + 1, j + 1)); } }
3,290
Maximum Multiplication Score
Medium
<p>You are given an integer array <code>a</code> of size 4 and another integer array <code>b</code> of size <strong>at least</strong> 4.</p> <p>You need to choose 4 indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, <code>i<sub>2</sub></code>, and <code>i<sub>3</sub></code> from the array <code>b</code> such that <code>i<sub>0</sub> &lt; i<sub>1</sub> &lt; i<sub>2</sub> &lt; i<sub>3</sub></code>. Your score will be equal to the value <code>a[0] * b[i<sub>0</sub>] + a[1] * b[i<sub>1</sub>] + a[2] * b[i<sub>2</sub>] + a[3] * b[i<sub>3</sub>]</code>.</p> <p>Return the <strong>maximum</strong> score you can achieve.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [3,2,5,6], b = [2,-6,4,-5,-3,2,-7]</span></p> <p><strong>Output:</strong> <span class="example-io">26</span></p> <p><strong>Explanation:</strong><br /> We can choose the indices 0, 1, 2, and 5. The score will be <code>3 * 2 + 2 * (-6) + 5 * 4 + 6 * 2 = 26</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [-1,4,5,-2], b = [-5,-1,-3,-2,-4]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> We can choose the indices 0, 1, 3, and 4. The score will be <code>(-1) * (-5) + 4 * (-1) + 5 * (-2) + (-2) * (-4) = -1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>a.length == 4</code></li> <li><code>4 &lt;= b.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= a[i], b[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def maxScore(self, a: List[int], b: List[int]) -> int: @cache def dfs(i: int, j: int) -> int: if j >= len(b): return 0 if i >= len(a) else -inf if i >= len(a): return 0 return max(dfs(i, j + 1), a[i] * b[j] + dfs(i + 1, j + 1)) return dfs(0, 0)
3,290
Maximum Multiplication Score
Medium
<p>You are given an integer array <code>a</code> of size 4 and another integer array <code>b</code> of size <strong>at least</strong> 4.</p> <p>You need to choose 4 indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, <code>i<sub>2</sub></code>, and <code>i<sub>3</sub></code> from the array <code>b</code> such that <code>i<sub>0</sub> &lt; i<sub>1</sub> &lt; i<sub>2</sub> &lt; i<sub>3</sub></code>. Your score will be equal to the value <code>a[0] * b[i<sub>0</sub>] + a[1] * b[i<sub>1</sub>] + a[2] * b[i<sub>2</sub>] + a[3] * b[i<sub>3</sub>]</code>.</p> <p>Return the <strong>maximum</strong> score you can achieve.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [3,2,5,6], b = [2,-6,4,-5,-3,2,-7]</span></p> <p><strong>Output:</strong> <span class="example-io">26</span></p> <p><strong>Explanation:</strong><br /> We can choose the indices 0, 1, 2, and 5. The score will be <code>3 * 2 + 2 * (-6) + 5 * 4 + 6 * 2 = 26</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">a = [-1,4,5,-2], b = [-5,-1,-3,-2,-4]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> We can choose the indices 0, 1, 3, and 4. The score will be <code>(-1) * (-5) + 4 * (-1) + 5 * (-2) + (-2) * (-4) = -1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>a.length == 4</code></li> <li><code>4 &lt;= b.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= a[i], b[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Dynamic Programming
TypeScript
function maxScore(a: number[], b: number[]): number { const [m, n] = [a.length, b.length]; const f: number[][] = Array.from({ length: m }, () => Array(n).fill(-1)); const dfs = (i: number, j: number): number => { if (j >= n) { return i >= m ? 0 : -Infinity; } if (i >= m) { return 0; } if (f[i][j] !== -1) { return f[i][j]; } return (f[i][j] = Math.max(dfs(i, j + 1), a[i] * b[j] + dfs(i + 1, j + 1))); }; return dfs(0, 0); }
3,291
Minimum Number of Valid Strings to Form Target I
Medium
<p>You are given an array of strings <code>words</code> and a string <code>target</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> is a <span data-keyword="string-prefix">prefix</span> of <strong>any</strong> string in <code>words</code>.</p> <p>Return the <strong>minimum</strong> number of <strong>valid</strong> strings that can be <em>concatenated</em> to form <code>target</code>. If it is <strong>not</strong> possible to form <code>target</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abc&quot;,&quot;aaaaa&quot;,&quot;bcdef&quot;], target = &quot;aabcdabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 2 of <code>words[1]</code>, i.e. <code>&quot;aa&quot;</code>.</li> <li>Prefix of length 3 of <code>words[2]</code>, i.e. <code>&quot;bcd&quot;</code>.</li> <li>Prefix of length 3 of <code>words[0]</code>, i.e. <code>&quot;abc&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">words = [&quot;abababab&quot;,&quot;ab&quot;], target = &quot;ababaababa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abcdef&quot;], target = &quot;xyz&quot;</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;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li>The input is generated such that <code>sum(words[i].length) &lt;= 10<sup>5</sup></code>.</li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= target.length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
Trie; Segment Tree; Array; String; Binary Search; Dynamic Programming; String Matching; Hash Function; Rolling Hash
C++
class Trie { public: Trie* children[26]{}; void insert(string& word) { Trie* node = this; for (char& c : word) { int i = c - 'a'; if (!node->children[i]) { node->children[i] = new Trie(); } node = node->children[i]; } } }; class Solution { public: int minValidStrings(vector<string>& words, string target) { int n = target.size(); Trie* trie = new Trie(); for (auto& w : words) { trie->insert(w); } const int inf = 1 << 30; int f[n]; memset(f, -1, sizeof(f)); auto dfs = [&](this auto&& dfs, int i) -> int { if (i >= n) { return 0; } if (f[i] != -1) { return f[i]; } f[i] = inf; Trie* node = trie; for (int j = i; j < n; ++j) { int k = target[j] - 'a'; if (!node->children[k]) { break; } node = node->children[k]; f[i] = min(f[i], 1 + dfs(j + 1)); } return f[i]; }; int ans = dfs(0); return ans < inf ? ans : -1; } };
3,291
Minimum Number of Valid Strings to Form Target I
Medium
<p>You are given an array of strings <code>words</code> and a string <code>target</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> is a <span data-keyword="string-prefix">prefix</span> of <strong>any</strong> string in <code>words</code>.</p> <p>Return the <strong>minimum</strong> number of <strong>valid</strong> strings that can be <em>concatenated</em> to form <code>target</code>. If it is <strong>not</strong> possible to form <code>target</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abc&quot;,&quot;aaaaa&quot;,&quot;bcdef&quot;], target = &quot;aabcdabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 2 of <code>words[1]</code>, i.e. <code>&quot;aa&quot;</code>.</li> <li>Prefix of length 3 of <code>words[2]</code>, i.e. <code>&quot;bcd&quot;</code>.</li> <li>Prefix of length 3 of <code>words[0]</code>, i.e. <code>&quot;abc&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">words = [&quot;abababab&quot;,&quot;ab&quot;], target = &quot;ababaababa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abcdef&quot;], target = &quot;xyz&quot;</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;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li>The input is generated such that <code>sum(words[i].length) &lt;= 10<sup>5</sup></code>.</li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= target.length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
Trie; Segment Tree; Array; String; Binary Search; Dynamic Programming; String Matching; Hash Function; Rolling Hash
Go
type Trie struct { children [26]*Trie } func (t *Trie) insert(word string) { node := t for _, c := range word { idx := c - 'a' if node.children[idx] == nil { node.children[idx] = &Trie{} } node = node.children[idx] } } func minValidStrings(words []string, target string) int { n := len(target) trie := &Trie{} for _, w := range words { trie.insert(w) } const inf int = 1 << 30 f := make([]int, n) var dfs func(int) int dfs = func(i int) int { if i >= n { return 0 } if f[i] != 0 { return f[i] } node := trie f[i] = inf for j := i; j < n; j++ { k := int(target[j] - 'a') if node.children[k] == nil { break } f[i] = min(f[i], 1+dfs(j+1)) node = node.children[k] } return f[i] } if ans := dfs(0); ans < inf { return ans } return -1 }
3,291
Minimum Number of Valid Strings to Form Target I
Medium
<p>You are given an array of strings <code>words</code> and a string <code>target</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> is a <span data-keyword="string-prefix">prefix</span> of <strong>any</strong> string in <code>words</code>.</p> <p>Return the <strong>minimum</strong> number of <strong>valid</strong> strings that can be <em>concatenated</em> to form <code>target</code>. If it is <strong>not</strong> possible to form <code>target</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abc&quot;,&quot;aaaaa&quot;,&quot;bcdef&quot;], target = &quot;aabcdabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 2 of <code>words[1]</code>, i.e. <code>&quot;aa&quot;</code>.</li> <li>Prefix of length 3 of <code>words[2]</code>, i.e. <code>&quot;bcd&quot;</code>.</li> <li>Prefix of length 3 of <code>words[0]</code>, i.e. <code>&quot;abc&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">words = [&quot;abababab&quot;,&quot;ab&quot;], target = &quot;ababaababa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abcdef&quot;], target = &quot;xyz&quot;</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;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li>The input is generated such that <code>sum(words[i].length) &lt;= 10<sup>5</sup></code>.</li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= target.length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
Trie; Segment Tree; Array; String; Binary Search; Dynamic Programming; String Matching; Hash Function; Rolling Hash
Java
class Trie { Trie[] children = new Trie[26]; void insert(String w) { Trie node = this; for (int i = 0; i < w.length(); ++i) { int j = w.charAt(i) - 'a'; if (node.children[j] == null) { node.children[j] = new Trie(); } node = node.children[j]; } } } class Solution { private Integer[] f; private char[] s; private Trie trie; private final int inf = 1 << 30; public int minValidStrings(String[] words, String target) { trie = new Trie(); for (String w : words) { trie.insert(w); } s = target.toCharArray(); f = new Integer[s.length]; int ans = dfs(0); return ans < inf ? ans : -1; } private int dfs(int i) { if (i >= s.length) { return 0; } if (f[i] != null) { return f[i]; } Trie node = trie; f[i] = inf; for (int j = i; j < s.length; ++j) { int k = s[j] - 'a'; if (node.children[k] == null) { break; } f[i] = Math.min(f[i], 1 + dfs(j + 1)); node = node.children[k]; } return f[i]; } }
3,291
Minimum Number of Valid Strings to Form Target I
Medium
<p>You are given an array of strings <code>words</code> and a string <code>target</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> is a <span data-keyword="string-prefix">prefix</span> of <strong>any</strong> string in <code>words</code>.</p> <p>Return the <strong>minimum</strong> number of <strong>valid</strong> strings that can be <em>concatenated</em> to form <code>target</code>. If it is <strong>not</strong> possible to form <code>target</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abc&quot;,&quot;aaaaa&quot;,&quot;bcdef&quot;], target = &quot;aabcdabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 2 of <code>words[1]</code>, i.e. <code>&quot;aa&quot;</code>.</li> <li>Prefix of length 3 of <code>words[2]</code>, i.e. <code>&quot;bcd&quot;</code>.</li> <li>Prefix of length 3 of <code>words[0]</code>, i.e. <code>&quot;abc&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">words = [&quot;abababab&quot;,&quot;ab&quot;], target = &quot;ababaababa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abcdef&quot;], target = &quot;xyz&quot;</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;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li>The input is generated such that <code>sum(words[i].length) &lt;= 10<sup>5</sup></code>.</li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= target.length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
Trie; Segment Tree; Array; String; Binary Search; Dynamic Programming; String Matching; Hash Function; Rolling Hash
Python
def min(a: int, b: int) -> int: return a if a < b else b class Trie: def __init__(self): self.children: List[Optional[Trie]] = [None] * 26 def insert(self, w: str): node = self for i in map(lambda c: ord(c) - 97, w): if node.children[i] is None: node.children[i] = Trie() node = node.children[i] class Solution: def minValidStrings(self, words: List[str], target: str) -> int: @cache def dfs(i: int) -> int: if i >= n: return 0 node = trie ans = inf for j in range(i, n): k = ord(target[j]) - 97 if node.children[k] is None: break node = node.children[k] ans = min(ans, 1 + dfs(j + 1)) return ans trie = Trie() for w in words: trie.insert(w) n = len(target) ans = dfs(0) return ans if ans < inf else -1
3,291
Minimum Number of Valid Strings to Form Target I
Medium
<p>You are given an array of strings <code>words</code> and a string <code>target</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> is a <span data-keyword="string-prefix">prefix</span> of <strong>any</strong> string in <code>words</code>.</p> <p>Return the <strong>minimum</strong> number of <strong>valid</strong> strings that can be <em>concatenated</em> to form <code>target</code>. If it is <strong>not</strong> possible to form <code>target</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abc&quot;,&quot;aaaaa&quot;,&quot;bcdef&quot;], target = &quot;aabcdabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 2 of <code>words[1]</code>, i.e. <code>&quot;aa&quot;</code>.</li> <li>Prefix of length 3 of <code>words[2]</code>, i.e. <code>&quot;bcd&quot;</code>.</li> <li>Prefix of length 3 of <code>words[0]</code>, i.e. <code>&quot;abc&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">words = [&quot;abababab&quot;,&quot;ab&quot;], target = &quot;ababaababa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abcdef&quot;], target = &quot;xyz&quot;</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;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li>The input is generated such that <code>sum(words[i].length) &lt;= 10<sup>5</sup></code>.</li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= target.length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
Trie; Segment Tree; Array; String; Binary Search; Dynamic Programming; String Matching; Hash Function; Rolling Hash
TypeScript
class Trie { children: (Trie | null)[] = Array(26).fill(null); insert(word: string): void { let node: Trie = this; for (const c of word) { const i = c.charCodeAt(0) - 'a'.charCodeAt(0); if (!node.children[i]) { node.children[i] = new Trie(); } node = node.children[i]; } } } function minValidStrings(words: string[], target: string): number { const n = target.length; const trie = new Trie(); for (const w of words) { trie.insert(w); } const inf = 1 << 30; const f = Array(n).fill(0); const dfs = (i: number): number => { if (i >= n) { return 0; } if (f[i]) { return f[i]; } f[i] = inf; let node: Trie | null = trie; for (let j = i; j < n; ++j) { const k = target[j].charCodeAt(0) - 'a'.charCodeAt(0); if (!node?.children[k]) { break; } node = node.children[k]; f[i] = Math.min(f[i], 1 + dfs(j + 1)); } return f[i]; }; const ans = dfs(0); return ans < inf ? ans : -1; }
3,292
Minimum Number of Valid Strings to Form Target II
Hard
<p>You are given an array of strings <code>words</code> and a string <code>target</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> is a <span data-keyword="string-prefix">prefix</span> of <strong>any</strong> string in <code>words</code>.</p> <p>Return the <strong>minimum</strong> number of <strong>valid</strong> strings that can be <em>concatenated</em> to form <code>target</code>. If it is <strong>not</strong> possible to form <code>target</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abc&quot;,&quot;aaaaa&quot;,&quot;bcdef&quot;], target = &quot;aabcdabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 2 of <code>words[1]</code>, i.e. <code>&quot;aa&quot;</code>.</li> <li>Prefix of length 3 of <code>words[2]</code>, i.e. <code>&quot;bcd&quot;</code>.</li> <li>Prefix of length 3 of <code>words[0]</code>, i.e. <code>&quot;abc&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">words = [&quot;abababab&quot;,&quot;ab&quot;], target = &quot;ababaababa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abcdef&quot;], target = &quot;xyz&quot;</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;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 5 * 10<sup>4</sup></code></li> <li>The input is generated such that <code>sum(words[i].length) &lt;= 10<sup>5</sup></code>.</li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= target.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
Segment Tree; Array; String; Binary Search; Dynamic Programming; String Matching; Hash Function; Rolling Hash
C++
class Hashing { private: vector<long long> p; vector<long long> h; long long mod; public: Hashing(const string& word, long long base, int mod) { int n = word.size(); p.resize(n + 1); h.resize(n + 1); p[0] = 1; this->mod = mod; for (int i = 1; i <= n; i++) { p[i] = (p[i - 1] * base) % mod; h[i] = (h[i - 1] * base + word[i - 1]) % mod; } } long long query(int l, int r) { return (h[r] - h[l - 1] * p[r - l + 1] % mod + mod) % mod; } }; class Solution { public: int minValidStrings(vector<string>& words, string target) { int base = 13331, mod = 998244353; Hashing hashing(target, base, mod); int m = 0, n = target.size(); for (const string& word : words) { m = max(m, (int) word.size()); } vector<unordered_set<long long>> s(m + 1); for (const string& w : words) { long long h = 0; for (int j = 0; j < w.size(); j++) { h = (h * base + w[j]) % mod; s[j + 1].insert(h); } } auto f = [&](int i) -> int { int l = 0, r = min(n - i, m); while (l < r) { int mid = (l + r + 1) >> 1; long long sub = hashing.query(i + 1, i + mid); if (s[mid].count(sub)) { l = mid; } else { r = mid - 1; } } return l; }; int ans = 0, last = 0, mx = 0; for (int i = 0; i < n; i++) { int dist = f(i); mx = max(mx, i + dist); if (i == last) { if (i == mx) { return -1; } last = mx; ans++; } } return ans; } };
3,292
Minimum Number of Valid Strings to Form Target II
Hard
<p>You are given an array of strings <code>words</code> and a string <code>target</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> is a <span data-keyword="string-prefix">prefix</span> of <strong>any</strong> string in <code>words</code>.</p> <p>Return the <strong>minimum</strong> number of <strong>valid</strong> strings that can be <em>concatenated</em> to form <code>target</code>. If it is <strong>not</strong> possible to form <code>target</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abc&quot;,&quot;aaaaa&quot;,&quot;bcdef&quot;], target = &quot;aabcdabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 2 of <code>words[1]</code>, i.e. <code>&quot;aa&quot;</code>.</li> <li>Prefix of length 3 of <code>words[2]</code>, i.e. <code>&quot;bcd&quot;</code>.</li> <li>Prefix of length 3 of <code>words[0]</code>, i.e. <code>&quot;abc&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">words = [&quot;abababab&quot;,&quot;ab&quot;], target = &quot;ababaababa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abcdef&quot;], target = &quot;xyz&quot;</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;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 5 * 10<sup>4</sup></code></li> <li>The input is generated such that <code>sum(words[i].length) &lt;= 10<sup>5</sup></code>.</li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= target.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
Segment Tree; Array; String; Binary Search; Dynamic Programming; String Matching; Hash Function; Rolling Hash
Go
type Hashing struct { p []int64 h []int64 mod int64 } func NewHashing(word string, base int64, mod int64) *Hashing { n := len(word) p := make([]int64, n+1) h := make([]int64, n+1) p[0] = 1 for i := 1; i <= n; i++ { p[i] = (p[i-1] * base) % mod h[i] = (h[i-1]*base + int64(word[i-1])) % mod } return &Hashing{p, h, mod} } func (hashing *Hashing) Query(l, r int) int64 { return (hashing.h[r] - hashing.h[l-1]*hashing.p[r-l+1]%hashing.mod + hashing.mod) % hashing.mod } func minValidStrings(words []string, target string) (ans int) { base, mod := int64(13331), int64(998244353) hashing := NewHashing(target, base, mod) m, n := 0, len(target) for _, w := range words { m = max(m, len(w)) } s := make([]map[int64]bool, m+1) f := func(i int) int { l, r := 0, int(math.Min(float64(n-i), float64(m))) for l < r { mid := (l + r + 1) >> 1 sub := hashing.Query(i+1, i+mid) if s[mid][sub] { l = mid } else { r = mid - 1 } } return l } for _, w := range words { h := int64(0) for j := 0; j < len(w); j++ { h = (h*base + int64(w[j])) % mod if s[j+1] == nil { s[j+1] = make(map[int64]bool) } s[j+1][h] = true } } var last, mx int for i := 0; i < n; i++ { dist := f(i) mx = max(mx, i+dist) if i == last { if i == mx { return -1 } last = mx ans++ } } return ans }
3,292
Minimum Number of Valid Strings to Form Target II
Hard
<p>You are given an array of strings <code>words</code> and a string <code>target</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> is a <span data-keyword="string-prefix">prefix</span> of <strong>any</strong> string in <code>words</code>.</p> <p>Return the <strong>minimum</strong> number of <strong>valid</strong> strings that can be <em>concatenated</em> to form <code>target</code>. If it is <strong>not</strong> possible to form <code>target</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abc&quot;,&quot;aaaaa&quot;,&quot;bcdef&quot;], target = &quot;aabcdabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 2 of <code>words[1]</code>, i.e. <code>&quot;aa&quot;</code>.</li> <li>Prefix of length 3 of <code>words[2]</code>, i.e. <code>&quot;bcd&quot;</code>.</li> <li>Prefix of length 3 of <code>words[0]</code>, i.e. <code>&quot;abc&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">words = [&quot;abababab&quot;,&quot;ab&quot;], target = &quot;ababaababa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abcdef&quot;], target = &quot;xyz&quot;</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;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 5 * 10<sup>4</sup></code></li> <li>The input is generated such that <code>sum(words[i].length) &lt;= 10<sup>5</sup></code>.</li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= target.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
Segment Tree; Array; String; Binary Search; Dynamic Programming; String Matching; Hash Function; Rolling Hash
Java
class Hashing { private final long[] p; private final long[] h; private final long mod; public Hashing(String word, long base, int mod) { int n = word.length(); p = new long[n + 1]; h = new long[n + 1]; p[0] = 1; this.mod = mod; for (int i = 1; i <= n; i++) { p[i] = p[i - 1] * base % mod; h[i] = (h[i - 1] * base + word.charAt(i - 1)) % mod; } } public long query(int l, int r) { return (h[r] - h[l - 1] * p[r - l + 1] % mod + mod) % mod; } } class Solution { private Hashing hashing; private Set<Long>[] s; public int minValidStrings(String[] words, String target) { int base = 13331, mod = 998244353; hashing = new Hashing(target, base, mod); int m = Arrays.stream(words).mapToInt(String::length).max().orElse(0); s = new Set[m + 1]; Arrays.setAll(s, k -> new HashSet<>()); for (String w : words) { long h = 0; for (int j = 0; j < w.length(); j++) { h = (h * base + w.charAt(j)) % mod; s[j + 1].add(h); } } int ans = 0; int last = 0; int mx = 0; int n = target.length(); for (int i = 0; i < n; i++) { int dist = f(i, n, m); mx = Math.max(mx, i + dist); if (i == last) { if (i == mx) { return -1; } last = mx; ans++; } } return ans; } private int f(int i, int n, int m) { int l = 0, r = Math.min(n - i, m); while (l < r) { int mid = (l + r + 1) >> 1; long sub = hashing.query(i + 1, i + mid); if (s[mid].contains(sub)) { l = mid; } else { r = mid - 1; } } return l; } }
3,292
Minimum Number of Valid Strings to Form Target II
Hard
<p>You are given an array of strings <code>words</code> and a string <code>target</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> is a <span data-keyword="string-prefix">prefix</span> of <strong>any</strong> string in <code>words</code>.</p> <p>Return the <strong>minimum</strong> number of <strong>valid</strong> strings that can be <em>concatenated</em> to form <code>target</code>. If it is <strong>not</strong> possible to form <code>target</code>, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abc&quot;,&quot;aaaaa&quot;,&quot;bcdef&quot;], target = &quot;aabcdabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 2 of <code>words[1]</code>, i.e. <code>&quot;aa&quot;</code>.</li> <li>Prefix of length 3 of <code>words[2]</code>, i.e. <code>&quot;bcd&quot;</code>.</li> <li>Prefix of length 3 of <code>words[0]</code>, i.e. <code>&quot;abc&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">words = [&quot;abababab&quot;,&quot;ab&quot;], target = &quot;ababaababa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The target string can be formed by concatenating:</p> <ul> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> <li>Prefix of length 5 of <code>words[0]</code>, i.e. <code>&quot;ababa&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;abcdef&quot;], target = &quot;xyz&quot;</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;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 5 * 10<sup>4</sup></code></li> <li>The input is generated such that <code>sum(words[i].length) &lt;= 10<sup>5</sup></code>.</li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= target.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>target</code> consists only of lowercase English letters.</li> </ul>
Segment Tree; Array; String; Binary Search; Dynamic Programming; String Matching; Hash Function; Rolling Hash
Python
class Hashing: __slots__ = ["mod", "h", "p"] def __init__(self, s: List[str], base: int, mod: int): self.mod = mod self.h = [0] * (len(s) + 1) self.p = [1] * (len(s) + 1) for i in range(1, len(s) + 1): self.h[i] = (self.h[i - 1] * base + ord(s[i - 1])) % mod self.p[i] = (self.p[i - 1] * base) % mod def query(self, l: int, r: int) -> int: return (self.h[r] - self.h[l - 1] * self.p[r - l + 1]) % self.mod class Solution: def minValidStrings(self, words: List[str], target: str) -> int: def f(i: int) -> int: l, r = 0, min(n - i, m) while l < r: mid = (l + r + 1) >> 1 sub = hashing.query(i + 1, i + mid) if sub in s[mid]: l = mid else: r = mid - 1 return l base, mod = 13331, 998244353 hashing = Hashing(target, base, mod) m = max(len(w) for w in words) s = [set() for _ in range(m + 1)] for w in words: h = 0 for j, c in enumerate(w, 1): h = (h * base + ord(c)) % mod s[j].add(h) ans = last = mx = 0 n = len(target) for i in range(n): dist = f(i) mx = max(mx, i + dist) if i == last: if i == mx: return -1 last = mx ans += 1 return ans
3,293
Calculate Product Final Price
Medium
<p>Table: <font face="monospace"><code>Products</code></font></p> <pre> +------------+---------+ | Column Name| Type | +------------+---------+ | product_id | int | | category | varchar | | price | decimal | +------------+---------+ product_id is the unique key for this table. Each row includes the product&#39;s ID, its category, and its price. </pre> <p>Table: <font face="monospace"><code>Discounts</code></font></p> <pre> +------------+---------+ | Column Name| Type | +------------+---------+ | category | varchar | | discount | int | +------------+---------+ category is the primary key for this table. Each row contains a product category and the percentage discount applied to that category (values range from 0 to 100). </pre> <p>Write a solution to find the <strong>final price</strong> of each product after applying the <strong>category discount</strong>. If a product&#39;s category has <strong>no</strong> <strong>associated</strong> <strong>discount</strong>, its price remains <strong>unchanged</strong>.</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>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p><code>Products</code> table:</p> <pre class="example-io"> +------------+-------------+-------+ | product_id | category | price | +------------+-------------+-------+ | 1 | Electronics | 1000 | | 2 | Clothing | 50 | | 3 | Electronics | 1200 | | 4 | Home | 500 | +------------+-------------+-------+ </pre> <p><code>Discounts</code> table:</p> <pre class="example-io"> +------------+----------+ | category | discount | +------------+----------+ | Electronics| 10 | | Clothing | 20 | +------------+----------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------+------------+-------------+ | product_id | final_price| category | +------------+------------+-------------+ | 1 | 900 | Electronics | | 2 | 40 | Clothing | | 3 | 1080 | Electronics | | 4 | 500 | Home | +------------+------------+-------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>For product 1, it belongs to the Electronics&nbsp;category which has a 10% discount, so the final price is 1000 - (10% of 1000) = 900.</li> <li>For product 2, it belongs to the Clothing&nbsp;category which has a 20% discount, so the final price is 50 - (20% of 50) = 40.</li> <li>For product 3, it belongs to the Electronics&nbsp;category and receives a 10% discount, so the final price is 1200 - (10% of 1200) = 1080.</li> <li>For product 4, no discount is available for the Home&nbsp;category, so the final price remains 500.</li> </ul> Result table is ordered by product_id in ascending order.</div>
Database
Python
import pandas as pd def calculate_final_prices( products: pd.DataFrame, discounts: pd.DataFrame ) -> pd.DataFrame: # Perform a left join on the 'category' column merged_df = pd.merge(products, discounts, on="category", how="left") # Calculate the final price merged_df["final_price"] = ( merged_df["price"] * (100 - merged_df["discount"].fillna(0)) / 100 ) # Select the necessary columns and sort by 'product_id' result_df = merged_df[["product_id", "final_price", "category"]].sort_values( "product_id" ) return result_df
3,293
Calculate Product Final Price
Medium
<p>Table: <font face="monospace"><code>Products</code></font></p> <pre> +------------+---------+ | Column Name| Type | +------------+---------+ | product_id | int | | category | varchar | | price | decimal | +------------+---------+ product_id is the unique key for this table. Each row includes the product&#39;s ID, its category, and its price. </pre> <p>Table: <font face="monospace"><code>Discounts</code></font></p> <pre> +------------+---------+ | Column Name| Type | +------------+---------+ | category | varchar | | discount | int | +------------+---------+ category is the primary key for this table. Each row contains a product category and the percentage discount applied to that category (values range from 0 to 100). </pre> <p>Write a solution to find the <strong>final price</strong> of each product after applying the <strong>category discount</strong>. If a product&#39;s category has <strong>no</strong> <strong>associated</strong> <strong>discount</strong>, its price remains <strong>unchanged</strong>.</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>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p><code>Products</code> table:</p> <pre class="example-io"> +------------+-------------+-------+ | product_id | category | price | +------------+-------------+-------+ | 1 | Electronics | 1000 | | 2 | Clothing | 50 | | 3 | Electronics | 1200 | | 4 | Home | 500 | +------------+-------------+-------+ </pre> <p><code>Discounts</code> table:</p> <pre class="example-io"> +------------+----------+ | category | discount | +------------+----------+ | Electronics| 10 | | Clothing | 20 | +------------+----------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +------------+------------+-------------+ | product_id | final_price| category | +------------+------------+-------------+ | 1 | 900 | Electronics | | 2 | 40 | Clothing | | 3 | 1080 | Electronics | | 4 | 500 | Home | +------------+------------+-------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li>For product 1, it belongs to the Electronics&nbsp;category which has a 10% discount, so the final price is 1000 - (10% of 1000) = 900.</li> <li>For product 2, it belongs to the Clothing&nbsp;category which has a 20% discount, so the final price is 50 - (20% of 50) = 40.</li> <li>For product 3, it belongs to the Electronics&nbsp;category and receives a 10% discount, so the final price is 1200 - (10% of 1200) = 1080.</li> <li>For product 4, no discount is available for the Home&nbsp;category, so the final price remains 500.</li> </ul> Result table is ordered by product_id in ascending order.</div>
Database
SQL
# Write your MySQL query statement below SELECT product_id, price * (100 - IFNULL(discount, 0)) / 100 final_price, category FROM Products LEFT JOIN Discounts USING (category) ORDER BY 1;
3,294
Convert Doubly Linked List to Array II
Medium
<p>You are given an <strong>arbitrary</strong> <code>node</code> from a <strong>doubly linked list</strong>, which contains nodes that have a next pointer and a previous pointer.</p> <p>Return an integer array which contains the elements of the linked list <strong>in order</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">head = [1,2,3,4,5], node = 5</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,4,5]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [4,5,6,7,8], node = 8</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5,6,7,8]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the given list is in the range <code>[1, 500]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 1000</code></li> <li>All nodes have unique <code>Node.val</code>.</li> </ul>
Array; Linked List; Doubly-Linked List
C++
/** * Definition for doubly-linked list. * class Node { * int val; * Node* prev; * Node* next; * Node() : val(0), next(nullptr), prev(nullptr) {} * Node(int x) : val(x), next(nullptr), prev(nullptr) {} * Node(int x, Node *prev, Node *next) : val(x), next(next), prev(prev) {} * }; */ class Solution { public: vector<int> toArray(Node* node) { while (node && node->prev) { node = node->prev; } vector<int> ans; for (; node; node = node->next) { ans.push_back(node->val); } return ans; } };
3,294
Convert Doubly Linked List to Array II
Medium
<p>You are given an <strong>arbitrary</strong> <code>node</code> from a <strong>doubly linked list</strong>, which contains nodes that have a next pointer and a previous pointer.</p> <p>Return an integer array which contains the elements of the linked list <strong>in order</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">head = [1,2,3,4,5], node = 5</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,4,5]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [4,5,6,7,8], node = 8</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5,6,7,8]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the given list is in the range <code>[1, 500]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 1000</code></li> <li>All nodes have unique <code>Node.val</code>.</li> </ul>
Array; Linked List; Doubly-Linked List
Go
/** * Definition for a Node. * type Node struct { * Val int * Next *Node * Prev *Node * } */ func toArray(node *Node) (ans []int) { for node != nil && node.Prev != nil { node = node.Prev } for ; node != nil; node = node.Next { ans = append(ans, node.Val) } return }
3,294
Convert Doubly Linked List to Array II
Medium
<p>You are given an <strong>arbitrary</strong> <code>node</code> from a <strong>doubly linked list</strong>, which contains nodes that have a next pointer and a previous pointer.</p> <p>Return an integer array which contains the elements of the linked list <strong>in order</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">head = [1,2,3,4,5], node = 5</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,4,5]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [4,5,6,7,8], node = 8</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5,6,7,8]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the given list is in the range <code>[1, 500]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 1000</code></li> <li>All nodes have unique <code>Node.val</code>.</li> </ul>
Array; Linked List; Doubly-Linked List
Java
/* // Definition for a Node. class Node { public int val; public Node prev; public Node next; }; */ class Solution { public int[] toArray(Node node) { while (node != null && node.prev != null) { node = node.prev; } var ans = new ArrayList<Integer>(); for (; node != null; node = node.next) { ans.add(node.val); } return ans.stream().mapToInt(i -> i).toArray(); } }
3,294
Convert Doubly Linked List to Array II
Medium
<p>You are given an <strong>arbitrary</strong> <code>node</code> from a <strong>doubly linked list</strong>, which contains nodes that have a next pointer and a previous pointer.</p> <p>Return an integer array which contains the elements of the linked list <strong>in order</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">head = [1,2,3,4,5], node = 5</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,4,5]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [4,5,6,7,8], node = 8</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5,6,7,8]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the given list is in the range <code>[1, 500]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 1000</code></li> <li>All nodes have unique <code>Node.val</code>.</li> </ul>
Array; Linked List; Doubly-Linked List
Python
""" # Definition for a Node. class Node: def __init__(self, val, prev=None, next=None): self.val = val self.prev = prev self.next = next """ class Solution: def toArray(self, node: "Optional[Node]") -> List[int]: while node.prev: node = node.prev ans = [] while node: ans.append(node.val) node = node.next return ans
3,294
Convert Doubly Linked List to Array II
Medium
<p>You are given an <strong>arbitrary</strong> <code>node</code> from a <strong>doubly linked list</strong>, which contains nodes that have a next pointer and a previous pointer.</p> <p>Return an integer array which contains the elements of the linked list <strong>in order</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">head = [1,2,3,4,5], node = 5</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,4,5]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">head = [4,5,6,7,8], node = 8</span></p> <p><strong>Output:</strong> <span class="example-io">[4,5,6,7,8]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the given list is in the range <code>[1, 500]</code>.</li> <li><code>1 &lt;= Node.val &lt;= 1000</code></li> <li>All nodes have unique <code>Node.val</code>.</li> </ul>
Array; Linked List; Doubly-Linked List
TypeScript
/** * Definition for _Node. * class _Node { * val: number * prev: _Node | null * next: _Node | null * * constructor(val?: number, prev? : _Node, next? : _Node) { * this.val = (val===undefined ? 0 : val); * this.prev = (prev===undefined ? null : prev); * this.next = (next===undefined ? null : next); * } * } */ function toArray(node: _Node | null): number[] { while (node && node.prev) { node = node.prev; } const ans: number[] = []; for (; node; node = node.next) { ans.push(node.val); } return ans; }
3,295
Report Spam Message
Medium
<p>You are given an array of strings <code>message</code> and an array of strings <code>bannedWords</code>.</p> <p>An array of words is considered <strong>spam</strong> if there are <strong>at least</strong> two words in it that <b>exactly</b> match any word in <code>bannedWords</code>.</p> <p>Return <code>true</code> if the array <code>message</code> is spam, 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">message = [&quot;hello&quot;,&quot;world&quot;,&quot;leetcode&quot;], bannedWords = [&quot;world&quot;,&quot;hello&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The words <code>&quot;hello&quot;</code> and <code>&quot;world&quot;</code> from the <code>message</code> array both appear in the <code>bannedWords</code> array.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">message = [&quot;hello&quot;,&quot;programming&quot;,&quot;fun&quot;], bannedWords = [&quot;world&quot;,&quot;programming&quot;,&quot;leetcode&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>Only one word from the <code>message</code> array (<code>&quot;programming&quot;</code>) appears in the <code>bannedWords</code> array.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= message.length, bannedWords.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= message[i].length, bannedWords[i].length &lt;= 15</code></li> <li><code>message[i]</code> and <code>bannedWords[i]</code> consist only of lowercase English letters.</li> </ul>
Array; Hash Table; String
C++
class Solution { public: bool reportSpam(vector<string>& message, vector<string>& bannedWords) { unordered_set<string> s(bannedWords.begin(), bannedWords.end()); int cnt = 0; for (const auto& w : message) { if (s.contains(w) && ++cnt >= 2) { return true; } } return false; } };
3,295
Report Spam Message
Medium
<p>You are given an array of strings <code>message</code> and an array of strings <code>bannedWords</code>.</p> <p>An array of words is considered <strong>spam</strong> if there are <strong>at least</strong> two words in it that <b>exactly</b> match any word in <code>bannedWords</code>.</p> <p>Return <code>true</code> if the array <code>message</code> is spam, 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">message = [&quot;hello&quot;,&quot;world&quot;,&quot;leetcode&quot;], bannedWords = [&quot;world&quot;,&quot;hello&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The words <code>&quot;hello&quot;</code> and <code>&quot;world&quot;</code> from the <code>message</code> array both appear in the <code>bannedWords</code> array.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">message = [&quot;hello&quot;,&quot;programming&quot;,&quot;fun&quot;], bannedWords = [&quot;world&quot;,&quot;programming&quot;,&quot;leetcode&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>Only one word from the <code>message</code> array (<code>&quot;programming&quot;</code>) appears in the <code>bannedWords</code> array.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= message.length, bannedWords.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= message[i].length, bannedWords[i].length &lt;= 15</code></li> <li><code>message[i]</code> and <code>bannedWords[i]</code> consist only of lowercase English letters.</li> </ul>
Array; Hash Table; String
Go
func reportSpam(message []string, bannedWords []string) bool { s := map[string]bool{} for _, w := range bannedWords { s[w] = true } cnt := 0 for _, w := range message { if s[w] { cnt++ if cnt >= 2 { return true } } } return false }
3,295
Report Spam Message
Medium
<p>You are given an array of strings <code>message</code> and an array of strings <code>bannedWords</code>.</p> <p>An array of words is considered <strong>spam</strong> if there are <strong>at least</strong> two words in it that <b>exactly</b> match any word in <code>bannedWords</code>.</p> <p>Return <code>true</code> if the array <code>message</code> is spam, 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">message = [&quot;hello&quot;,&quot;world&quot;,&quot;leetcode&quot;], bannedWords = [&quot;world&quot;,&quot;hello&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The words <code>&quot;hello&quot;</code> and <code>&quot;world&quot;</code> from the <code>message</code> array both appear in the <code>bannedWords</code> array.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">message = [&quot;hello&quot;,&quot;programming&quot;,&quot;fun&quot;], bannedWords = [&quot;world&quot;,&quot;programming&quot;,&quot;leetcode&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>Only one word from the <code>message</code> array (<code>&quot;programming&quot;</code>) appears in the <code>bannedWords</code> array.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= message.length, bannedWords.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= message[i].length, bannedWords[i].length &lt;= 15</code></li> <li><code>message[i]</code> and <code>bannedWords[i]</code> consist only of lowercase English letters.</li> </ul>
Array; Hash Table; String
Java
class Solution { public boolean reportSpam(String[] message, String[] bannedWords) { Set<String> s = new HashSet<>(); for (var w : bannedWords) { s.add(w); } int cnt = 0; for (var w : message) { if (s.contains(w) && ++cnt >= 2) { return true; } } return false; } }
3,295
Report Spam Message
Medium
<p>You are given an array of strings <code>message</code> and an array of strings <code>bannedWords</code>.</p> <p>An array of words is considered <strong>spam</strong> if there are <strong>at least</strong> two words in it that <b>exactly</b> match any word in <code>bannedWords</code>.</p> <p>Return <code>true</code> if the array <code>message</code> is spam, 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">message = [&quot;hello&quot;,&quot;world&quot;,&quot;leetcode&quot;], bannedWords = [&quot;world&quot;,&quot;hello&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The words <code>&quot;hello&quot;</code> and <code>&quot;world&quot;</code> from the <code>message</code> array both appear in the <code>bannedWords</code> array.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">message = [&quot;hello&quot;,&quot;programming&quot;,&quot;fun&quot;], bannedWords = [&quot;world&quot;,&quot;programming&quot;,&quot;leetcode&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>Only one word from the <code>message</code> array (<code>&quot;programming&quot;</code>) appears in the <code>bannedWords</code> array.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= message.length, bannedWords.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= message[i].length, bannedWords[i].length &lt;= 15</code></li> <li><code>message[i]</code> and <code>bannedWords[i]</code> consist only of lowercase English letters.</li> </ul>
Array; Hash Table; String
Python
class Solution: def reportSpam(self, message: List[str], bannedWords: List[str]) -> bool: s = set(bannedWords) return sum(w in s for w in message) >= 2
3,295
Report Spam Message
Medium
<p>You are given an array of strings <code>message</code> and an array of strings <code>bannedWords</code>.</p> <p>An array of words is considered <strong>spam</strong> if there are <strong>at least</strong> two words in it that <b>exactly</b> match any word in <code>bannedWords</code>.</p> <p>Return <code>true</code> if the array <code>message</code> is spam, 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">message = [&quot;hello&quot;,&quot;world&quot;,&quot;leetcode&quot;], bannedWords = [&quot;world&quot;,&quot;hello&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The words <code>&quot;hello&quot;</code> and <code>&quot;world&quot;</code> from the <code>message</code> array both appear in the <code>bannedWords</code> array.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">message = [&quot;hello&quot;,&quot;programming&quot;,&quot;fun&quot;], bannedWords = [&quot;world&quot;,&quot;programming&quot;,&quot;leetcode&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>Only one word from the <code>message</code> array (<code>&quot;programming&quot;</code>) appears in the <code>bannedWords</code> array.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= message.length, bannedWords.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= message[i].length, bannedWords[i].length &lt;= 15</code></li> <li><code>message[i]</code> and <code>bannedWords[i]</code> consist only of lowercase English letters.</li> </ul>
Array; Hash Table; String
TypeScript
function reportSpam(message: string[], bannedWords: string[]): boolean { const s = new Set<string>(bannedWords); let cnt = 0; for (const w of message) { if (s.has(w) && ++cnt >= 2) { return true; } } return false; }
3,296
Minimum Number of Seconds to Make Mountain Height Zero
Medium
<p>You are given an integer <code>mountainHeight</code> denoting the height of a mountain.</p> <p>You are also given an integer array <code>workerTimes</code> representing the work time of workers in <strong>seconds</strong>.</p> <p>The workers work <strong>simultaneously</strong> to <strong>reduce</strong> the height of the mountain. For worker <code>i</code>:</p> <ul> <li>To decrease the mountain&#39;s height by <code>x</code>, it takes <code>workerTimes[i] + workerTimes[i] * 2 + ... + workerTimes[i] * x</code> seconds. For example: <ul> <li>To reduce the height of the mountain by 1, it takes <code>workerTimes[i]</code> seconds.</li> <li>To reduce the height of the mountain by 2, it takes <code>workerTimes[i] + workerTimes[i] * 2</code> seconds, and so on.</li> </ul> </li> </ul> <p>Return an integer representing the <strong>minimum</strong> number of seconds required for the workers to make the height of the mountain 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 4, workerTimes = [2,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>One way the height of the mountain can be reduced to 0 is:</p> <ul> <li>Worker 0 reduces the height by 1, taking <code>workerTimes[0] = 2</code> seconds.</li> <li>Worker 1 reduces the height by 2, taking <code>workerTimes[1] + workerTimes[1] * 2 = 3</code> seconds.</li> <li>Worker 2 reduces the height by 1, taking <code>workerTimes[2] = 1</code> second.</li> </ul> <p>Since they work simultaneously, the minimum time needed is <code>max(2, 3, 1) = 3</code> seconds.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 10, workerTimes = [3,2,2,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 reduces the height by 2, taking <code>workerTimes[0] + workerTimes[0] * 2 = 9</code> seconds.</li> <li>Worker 1 reduces the height by 3, taking <code>workerTimes[1] + workerTimes[1] * 2 + workerTimes[1] * 3 = 12</code> seconds.</li> <li>Worker 2 reduces the height by 3, taking <code>workerTimes[2] + workerTimes[2] * 2 + workerTimes[2] * 3 = 12</code> seconds.</li> <li>Worker 3 reduces the height by 2, taking <code>workerTimes[3] + workerTimes[3] * 2 = 12</code> seconds.</li> </ul> <p>The number of seconds needed is <code>max(9, 12, 12, 12) = 12</code> seconds.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 5, workerTimes = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>There is only one worker in this example, so the answer is <code>workerTimes[0] + workerTimes[0] * 2 + workerTimes[0] * 3 + workerTimes[0] * 4 + workerTimes[0] * 5 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= mountainHeight &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workerTimes.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= workerTimes[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Math; Binary Search; Heap (Priority Queue)
C++
class Solution { public: long long minNumberOfSeconds(int mountainHeight, vector<int>& workerTimes) { using ll = long long; ll l = 1, r = 1e16; auto check = [&](ll t) -> bool { ll h = 0; for (int& wt : workerTimes) { h += (long long) (sqrt(t * 2.0 / wt + 0.25) - 0.5); } return h >= mountainHeight; }; while (l < r) { ll mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } };
3,296
Minimum Number of Seconds to Make Mountain Height Zero
Medium
<p>You are given an integer <code>mountainHeight</code> denoting the height of a mountain.</p> <p>You are also given an integer array <code>workerTimes</code> representing the work time of workers in <strong>seconds</strong>.</p> <p>The workers work <strong>simultaneously</strong> to <strong>reduce</strong> the height of the mountain. For worker <code>i</code>:</p> <ul> <li>To decrease the mountain&#39;s height by <code>x</code>, it takes <code>workerTimes[i] + workerTimes[i] * 2 + ... + workerTimes[i] * x</code> seconds. For example: <ul> <li>To reduce the height of the mountain by 1, it takes <code>workerTimes[i]</code> seconds.</li> <li>To reduce the height of the mountain by 2, it takes <code>workerTimes[i] + workerTimes[i] * 2</code> seconds, and so on.</li> </ul> </li> </ul> <p>Return an integer representing the <strong>minimum</strong> number of seconds required for the workers to make the height of the mountain 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 4, workerTimes = [2,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>One way the height of the mountain can be reduced to 0 is:</p> <ul> <li>Worker 0 reduces the height by 1, taking <code>workerTimes[0] = 2</code> seconds.</li> <li>Worker 1 reduces the height by 2, taking <code>workerTimes[1] + workerTimes[1] * 2 = 3</code> seconds.</li> <li>Worker 2 reduces the height by 1, taking <code>workerTimes[2] = 1</code> second.</li> </ul> <p>Since they work simultaneously, the minimum time needed is <code>max(2, 3, 1) = 3</code> seconds.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 10, workerTimes = [3,2,2,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 reduces the height by 2, taking <code>workerTimes[0] + workerTimes[0] * 2 = 9</code> seconds.</li> <li>Worker 1 reduces the height by 3, taking <code>workerTimes[1] + workerTimes[1] * 2 + workerTimes[1] * 3 = 12</code> seconds.</li> <li>Worker 2 reduces the height by 3, taking <code>workerTimes[2] + workerTimes[2] * 2 + workerTimes[2] * 3 = 12</code> seconds.</li> <li>Worker 3 reduces the height by 2, taking <code>workerTimes[3] + workerTimes[3] * 2 = 12</code> seconds.</li> </ul> <p>The number of seconds needed is <code>max(9, 12, 12, 12) = 12</code> seconds.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 5, workerTimes = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>There is only one worker in this example, so the answer is <code>workerTimes[0] + workerTimes[0] * 2 + workerTimes[0] * 3 + workerTimes[0] * 4 + workerTimes[0] * 5 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= mountainHeight &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workerTimes.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= workerTimes[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Math; Binary Search; Heap (Priority Queue)
Go
func minNumberOfSeconds(mountainHeight int, workerTimes []int) int64 { return int64(sort.Search(1e16, func(t int) bool { var h int64 for _, wt := range workerTimes { h += int64(math.Sqrt(float64(t)*2.0/float64(wt)+0.25) - 0.5) } return h >= int64(mountainHeight) })) }
3,296
Minimum Number of Seconds to Make Mountain Height Zero
Medium
<p>You are given an integer <code>mountainHeight</code> denoting the height of a mountain.</p> <p>You are also given an integer array <code>workerTimes</code> representing the work time of workers in <strong>seconds</strong>.</p> <p>The workers work <strong>simultaneously</strong> to <strong>reduce</strong> the height of the mountain. For worker <code>i</code>:</p> <ul> <li>To decrease the mountain&#39;s height by <code>x</code>, it takes <code>workerTimes[i] + workerTimes[i] * 2 + ... + workerTimes[i] * x</code> seconds. For example: <ul> <li>To reduce the height of the mountain by 1, it takes <code>workerTimes[i]</code> seconds.</li> <li>To reduce the height of the mountain by 2, it takes <code>workerTimes[i] + workerTimes[i] * 2</code> seconds, and so on.</li> </ul> </li> </ul> <p>Return an integer representing the <strong>minimum</strong> number of seconds required for the workers to make the height of the mountain 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 4, workerTimes = [2,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>One way the height of the mountain can be reduced to 0 is:</p> <ul> <li>Worker 0 reduces the height by 1, taking <code>workerTimes[0] = 2</code> seconds.</li> <li>Worker 1 reduces the height by 2, taking <code>workerTimes[1] + workerTimes[1] * 2 = 3</code> seconds.</li> <li>Worker 2 reduces the height by 1, taking <code>workerTimes[2] = 1</code> second.</li> </ul> <p>Since they work simultaneously, the minimum time needed is <code>max(2, 3, 1) = 3</code> seconds.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 10, workerTimes = [3,2,2,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 reduces the height by 2, taking <code>workerTimes[0] + workerTimes[0] * 2 = 9</code> seconds.</li> <li>Worker 1 reduces the height by 3, taking <code>workerTimes[1] + workerTimes[1] * 2 + workerTimes[1] * 3 = 12</code> seconds.</li> <li>Worker 2 reduces the height by 3, taking <code>workerTimes[2] + workerTimes[2] * 2 + workerTimes[2] * 3 = 12</code> seconds.</li> <li>Worker 3 reduces the height by 2, taking <code>workerTimes[3] + workerTimes[3] * 2 = 12</code> seconds.</li> </ul> <p>The number of seconds needed is <code>max(9, 12, 12, 12) = 12</code> seconds.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 5, workerTimes = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>There is only one worker in this example, so the answer is <code>workerTimes[0] + workerTimes[0] * 2 + workerTimes[0] * 3 + workerTimes[0] * 4 + workerTimes[0] * 5 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= mountainHeight &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workerTimes.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= workerTimes[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Math; Binary Search; Heap (Priority Queue)
Java
class Solution { private int mountainHeight; private int[] workerTimes; public long minNumberOfSeconds(int mountainHeight, int[] workerTimes) { this.mountainHeight = mountainHeight; this.workerTimes = workerTimes; long l = 1, r = (long) 1e16; while (l < r) { long mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } private boolean check(long t) { long h = 0; for (int wt : workerTimes) { h += (long) (Math.sqrt(t * 2.0 / wt + 0.25) - 0.5); } return h >= mountainHeight; } }
3,296
Minimum Number of Seconds to Make Mountain Height Zero
Medium
<p>You are given an integer <code>mountainHeight</code> denoting the height of a mountain.</p> <p>You are also given an integer array <code>workerTimes</code> representing the work time of workers in <strong>seconds</strong>.</p> <p>The workers work <strong>simultaneously</strong> to <strong>reduce</strong> the height of the mountain. For worker <code>i</code>:</p> <ul> <li>To decrease the mountain&#39;s height by <code>x</code>, it takes <code>workerTimes[i] + workerTimes[i] * 2 + ... + workerTimes[i] * x</code> seconds. For example: <ul> <li>To reduce the height of the mountain by 1, it takes <code>workerTimes[i]</code> seconds.</li> <li>To reduce the height of the mountain by 2, it takes <code>workerTimes[i] + workerTimes[i] * 2</code> seconds, and so on.</li> </ul> </li> </ul> <p>Return an integer representing the <strong>minimum</strong> number of seconds required for the workers to make the height of the mountain 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 4, workerTimes = [2,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>One way the height of the mountain can be reduced to 0 is:</p> <ul> <li>Worker 0 reduces the height by 1, taking <code>workerTimes[0] = 2</code> seconds.</li> <li>Worker 1 reduces the height by 2, taking <code>workerTimes[1] + workerTimes[1] * 2 = 3</code> seconds.</li> <li>Worker 2 reduces the height by 1, taking <code>workerTimes[2] = 1</code> second.</li> </ul> <p>Since they work simultaneously, the minimum time needed is <code>max(2, 3, 1) = 3</code> seconds.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 10, workerTimes = [3,2,2,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 reduces the height by 2, taking <code>workerTimes[0] + workerTimes[0] * 2 = 9</code> seconds.</li> <li>Worker 1 reduces the height by 3, taking <code>workerTimes[1] + workerTimes[1] * 2 + workerTimes[1] * 3 = 12</code> seconds.</li> <li>Worker 2 reduces the height by 3, taking <code>workerTimes[2] + workerTimes[2] * 2 + workerTimes[2] * 3 = 12</code> seconds.</li> <li>Worker 3 reduces the height by 2, taking <code>workerTimes[3] + workerTimes[3] * 2 = 12</code> seconds.</li> </ul> <p>The number of seconds needed is <code>max(9, 12, 12, 12) = 12</code> seconds.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 5, workerTimes = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>There is only one worker in this example, so the answer is <code>workerTimes[0] + workerTimes[0] * 2 + workerTimes[0] * 3 + workerTimes[0] * 4 + workerTimes[0] * 5 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= mountainHeight &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workerTimes.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= workerTimes[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Math; Binary Search; Heap (Priority Queue)
Python
class Solution: def minNumberOfSeconds(self, mountainHeight: int, workerTimes: List[int]) -> int: def check(t: int) -> bool: h = 0 for wt in workerTimes: h += int(sqrt(2 * t / wt + 1 / 4) - 1 / 2) return h >= mountainHeight return bisect_left(range(10**16), True, key=check)
3,296
Minimum Number of Seconds to Make Mountain Height Zero
Medium
<p>You are given an integer <code>mountainHeight</code> denoting the height of a mountain.</p> <p>You are also given an integer array <code>workerTimes</code> representing the work time of workers in <strong>seconds</strong>.</p> <p>The workers work <strong>simultaneously</strong> to <strong>reduce</strong> the height of the mountain. For worker <code>i</code>:</p> <ul> <li>To decrease the mountain&#39;s height by <code>x</code>, it takes <code>workerTimes[i] + workerTimes[i] * 2 + ... + workerTimes[i] * x</code> seconds. For example: <ul> <li>To reduce the height of the mountain by 1, it takes <code>workerTimes[i]</code> seconds.</li> <li>To reduce the height of the mountain by 2, it takes <code>workerTimes[i] + workerTimes[i] * 2</code> seconds, and so on.</li> </ul> </li> </ul> <p>Return an integer representing the <strong>minimum</strong> number of seconds required for the workers to make the height of the mountain 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 4, workerTimes = [2,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>One way the height of the mountain can be reduced to 0 is:</p> <ul> <li>Worker 0 reduces the height by 1, taking <code>workerTimes[0] = 2</code> seconds.</li> <li>Worker 1 reduces the height by 2, taking <code>workerTimes[1] + workerTimes[1] * 2 = 3</code> seconds.</li> <li>Worker 2 reduces the height by 1, taking <code>workerTimes[2] = 1</code> second.</li> </ul> <p>Since they work simultaneously, the minimum time needed is <code>max(2, 3, 1) = 3</code> seconds.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 10, workerTimes = [3,2,2,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Worker 0 reduces the height by 2, taking <code>workerTimes[0] + workerTimes[0] * 2 = 9</code> seconds.</li> <li>Worker 1 reduces the height by 3, taking <code>workerTimes[1] + workerTimes[1] * 2 + workerTimes[1] * 3 = 12</code> seconds.</li> <li>Worker 2 reduces the height by 3, taking <code>workerTimes[2] + workerTimes[2] * 2 + workerTimes[2] * 3 = 12</code> seconds.</li> <li>Worker 3 reduces the height by 2, taking <code>workerTimes[3] + workerTimes[3] * 2 = 12</code> seconds.</li> </ul> <p>The number of seconds needed is <code>max(9, 12, 12, 12) = 12</code> seconds.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mountainHeight = 5, workerTimes = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>There is only one worker in this example, so the answer is <code>workerTimes[0] + workerTimes[0] * 2 + workerTimes[0] * 3 + workerTimes[0] * 4 + workerTimes[0] * 5 = 15</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= mountainHeight &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= workerTimes.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= workerTimes[i] &lt;= 10<sup>6</sup></code></li> </ul>
Greedy; Array; Math; Binary Search; Heap (Priority Queue)
TypeScript
function minNumberOfSeconds(mountainHeight: number, workerTimes: number[]): number { const check = (t: bigint): boolean => { let h = BigInt(0); for (const wt of workerTimes) { h += BigInt(Math.floor(Math.sqrt((Number(t) * 2.0) / wt + 0.25) - 0.5)); } return h >= BigInt(mountainHeight); }; let l = BigInt(1); let r = BigInt(1e16); while (l < r) { const mid = (l + r) >> BigInt(1); if (check(mid)) { r = mid; } else { l = mid + 1n; } } return Number(l); }
3,297
Count Substrings That Can Be Rearranged to Contain a String I
Medium
<p>You are given two strings <code>word1</code> and <code>word2</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> can be rearranged to have <code>word2</code> as a <span data-keyword="string-prefix">prefix</span>.</p> <p>Return the total number of <strong>valid</strong> <span data-keyword="substring-nonempty">substrings</span> of <code>word1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;bcca&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only valid substring is <code>&quot;bcca&quot;</code> which can be rearranged to <code>&quot;abcc&quot;</code> having <code>&quot;abc&quot;</code> as a prefix.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>All the substrings except substrings of size 1 and size 2 are valid.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= word2.length &lt;= 10<sup>4</sup></code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
C++
class Solution { public: long long validSubstringCount(string word1, string word2) { if (word1.size() < word2.size()) { return 0; } int cnt[26]{}; int need = 0; for (char& c : word2) { if (++cnt[c - 'a'] == 1) { ++need; } } long long ans = 0; int win[26]{}; int l = 0; for (char& c : word1) { int i = c - 'a'; if (++win[i] == cnt[i]) { --need; } while (need == 0) { i = word1[l] - 'a'; if (win[i] == cnt[i]) { ++need; } --win[i]; ++l; } ans += l; } return ans; } };
3,297
Count Substrings That Can Be Rearranged to Contain a String I
Medium
<p>You are given two strings <code>word1</code> and <code>word2</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> can be rearranged to have <code>word2</code> as a <span data-keyword="string-prefix">prefix</span>.</p> <p>Return the total number of <strong>valid</strong> <span data-keyword="substring-nonempty">substrings</span> of <code>word1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;bcca&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only valid substring is <code>&quot;bcca&quot;</code> which can be rearranged to <code>&quot;abcc&quot;</code> having <code>&quot;abc&quot;</code> as a prefix.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>All the substrings except substrings of size 1 and size 2 are valid.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= word2.length &lt;= 10<sup>4</sup></code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Go
func validSubstringCount(word1 string, word2 string) int64 { }
3,297
Count Substrings That Can Be Rearranged to Contain a String I
Medium
<p>You are given two strings <code>word1</code> and <code>word2</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> can be rearranged to have <code>word2</code> as a <span data-keyword="string-prefix">prefix</span>.</p> <p>Return the total number of <strong>valid</strong> <span data-keyword="substring-nonempty">substrings</span> of <code>word1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;bcca&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only valid substring is <code>&quot;bcca&quot;</code> which can be rearranged to <code>&quot;abcc&quot;</code> having <code>&quot;abc&quot;</code> as a prefix.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>All the substrings except substrings of size 1 and size 2 are valid.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= word2.length &lt;= 10<sup>4</sup></code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Java
class Solution { public long validSubstringCount(String word1, String word2) { if (word1.length() < word2.length()) { return 0; } int[] cnt = new int[26]; int need = 0; for (int i = 0; i < word2.length(); ++i) { if (++cnt[word2.charAt(i) - 'a'] == 1) { ++need; } } long ans = 0; int[] win = new int[26]; for (int l = 0, r = 0; r < word1.length(); ++r) { int c = word1.charAt(r) - 'a'; if (++win[c] == cnt[c]) { --need; } while (need == 0) { c = word1.charAt(l) - 'a'; if (win[c] == cnt[c]) { ++need; } --win[c]; ++l; } ans += l; } return ans; } }
3,297
Count Substrings That Can Be Rearranged to Contain a String I
Medium
<p>You are given two strings <code>word1</code> and <code>word2</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> can be rearranged to have <code>word2</code> as a <span data-keyword="string-prefix">prefix</span>.</p> <p>Return the total number of <strong>valid</strong> <span data-keyword="substring-nonempty">substrings</span> of <code>word1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;bcca&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only valid substring is <code>&quot;bcca&quot;</code> which can be rearranged to <code>&quot;abcc&quot;</code> having <code>&quot;abc&quot;</code> as a prefix.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>All the substrings except substrings of size 1 and size 2 are valid.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= word2.length &lt;= 10<sup>4</sup></code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Python
class Solution: def validSubstringCount(self, word1: str, word2: str) -> int: if len(word1) < len(word2): return 0 cnt = Counter(word2) need = len(cnt) ans = l = 0 win = Counter() for c in word1: win[c] += 1 if win[c] == cnt[c]: need -= 1 while need == 0: if win[word1[l]] == cnt[word1[l]]: need += 1 win[word1[l]] -= 1 l += 1 ans += l return ans
3,297
Count Substrings That Can Be Rearranged to Contain a String I
Medium
<p>You are given two strings <code>word1</code> and <code>word2</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> can be rearranged to have <code>word2</code> as a <span data-keyword="string-prefix">prefix</span>.</p> <p>Return the total number of <strong>valid</strong> <span data-keyword="substring-nonempty">substrings</span> of <code>word1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;bcca&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only valid substring is <code>&quot;bcca&quot;</code> which can be rearranged to <code>&quot;abcc&quot;</code> having <code>&quot;abc&quot;</code> as a prefix.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>All the substrings except substrings of size 1 and size 2 are valid.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= word2.length &lt;= 10<sup>4</sup></code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
TypeScript
function validSubstringCount(word1: string, word2: string): number {}
3,298
Count Substrings That Can Be Rearranged to Contain a String II
Hard
<p>You are given two strings <code>word1</code> and <code>word2</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> can be rearranged to have <code>word2</code> as a <span data-keyword="string-prefix">prefix</span>.</p> <p>Return the total number of <strong>valid</strong> <span data-keyword="substring-nonempty">substrings</span> of <code>word1</code>.</p> <p><strong>Note</strong> that the memory limits in this problem are <strong>smaller</strong> than usual, so you <strong>must</strong> implement a solution with a <em>linear</em> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;bcca&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only valid substring is <code>&quot;bcca&quot;</code> which can be rearranged to <code>&quot;abcc&quot;</code> having <code>&quot;abc&quot;</code> as a prefix.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>All the substrings except substrings of size 1 and size 2 are valid.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= word2.length &lt;= 10<sup>4</sup></code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
C++
class Solution { public: long long validSubstringCount(string word1, string word2) { if (word1.size() < word2.size()) { return 0; } int cnt[26]{}; int need = 0; for (char& c : word2) { if (++cnt[c - 'a'] == 1) { ++need; } } long long ans = 0; int win[26]{}; int l = 0; for (char& c : word1) { int i = c - 'a'; if (++win[i] == cnt[i]) { --need; } while (need == 0) { i = word1[l] - 'a'; if (win[i] == cnt[i]) { ++need; } --win[i]; ++l; } ans += l; } return ans; } };
3,298
Count Substrings That Can Be Rearranged to Contain a String II
Hard
<p>You are given two strings <code>word1</code> and <code>word2</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> can be rearranged to have <code>word2</code> as a <span data-keyword="string-prefix">prefix</span>.</p> <p>Return the total number of <strong>valid</strong> <span data-keyword="substring-nonempty">substrings</span> of <code>word1</code>.</p> <p><strong>Note</strong> that the memory limits in this problem are <strong>smaller</strong> than usual, so you <strong>must</strong> implement a solution with a <em>linear</em> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;bcca&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only valid substring is <code>&quot;bcca&quot;</code> which can be rearranged to <code>&quot;abcc&quot;</code> having <code>&quot;abc&quot;</code> as a prefix.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>All the substrings except substrings of size 1 and size 2 are valid.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= word2.length &lt;= 10<sup>4</sup></code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Go
func validSubstringCount(word1 string, word2 string) (ans int64) { if len(word1) < len(word2) { return 0 } cnt := [26]int{} need := 0 for _, c := range word2 { cnt[c-'a']++ if cnt[c-'a'] == 1 { need++ } } win := [26]int{} l := 0 for _, c := range word1 { i := int(c - 'a') win[i]++ if win[i] == cnt[i] { need-- } for need == 0 { i = int(word1[l] - 'a') if win[i] == cnt[i] { need++ } win[i]-- l++ } ans += int64(l) } return }
3,298
Count Substrings That Can Be Rearranged to Contain a String II
Hard
<p>You are given two strings <code>word1</code> and <code>word2</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> can be rearranged to have <code>word2</code> as a <span data-keyword="string-prefix">prefix</span>.</p> <p>Return the total number of <strong>valid</strong> <span data-keyword="substring-nonempty">substrings</span> of <code>word1</code>.</p> <p><strong>Note</strong> that the memory limits in this problem are <strong>smaller</strong> than usual, so you <strong>must</strong> implement a solution with a <em>linear</em> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;bcca&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only valid substring is <code>&quot;bcca&quot;</code> which can be rearranged to <code>&quot;abcc&quot;</code> having <code>&quot;abc&quot;</code> as a prefix.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>All the substrings except substrings of size 1 and size 2 are valid.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= word2.length &lt;= 10<sup>4</sup></code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Java
class Solution { public long validSubstringCount(String word1, String word2) { if (word1.length() < word2.length()) { return 0; } int[] cnt = new int[26]; int need = 0; for (int i = 0; i < word2.length(); ++i) { if (++cnt[word2.charAt(i) - 'a'] == 1) { ++need; } } long ans = 0; int[] win = new int[26]; for (int l = 0, r = 0; r < word1.length(); ++r) { int c = word1.charAt(r) - 'a'; if (++win[c] == cnt[c]) { --need; } while (need == 0) { c = word1.charAt(l) - 'a'; if (win[c] == cnt[c]) { ++need; } --win[c]; ++l; } ans += l; } return ans; } }
3,298
Count Substrings That Can Be Rearranged to Contain a String II
Hard
<p>You are given two strings <code>word1</code> and <code>word2</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> can be rearranged to have <code>word2</code> as a <span data-keyword="string-prefix">prefix</span>.</p> <p>Return the total number of <strong>valid</strong> <span data-keyword="substring-nonempty">substrings</span> of <code>word1</code>.</p> <p><strong>Note</strong> that the memory limits in this problem are <strong>smaller</strong> than usual, so you <strong>must</strong> implement a solution with a <em>linear</em> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;bcca&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only valid substring is <code>&quot;bcca&quot;</code> which can be rearranged to <code>&quot;abcc&quot;</code> having <code>&quot;abc&quot;</code> as a prefix.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>All the substrings except substrings of size 1 and size 2 are valid.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= word2.length &lt;= 10<sup>4</sup></code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
Python
class Solution: def validSubstringCount(self, word1: str, word2: str) -> int: if len(word1) < len(word2): return 0 cnt = Counter(word2) need = len(cnt) ans = l = 0 win = Counter() for c in word1: win[c] += 1 if win[c] == cnt[c]: need -= 1 while need == 0: if win[word1[l]] == cnt[word1[l]]: need += 1 win[word1[l]] -= 1 l += 1 ans += l return ans
3,298
Count Substrings That Can Be Rearranged to Contain a String II
Hard
<p>You are given two strings <code>word1</code> and <code>word2</code>.</p> <p>A string <code>x</code> is called <strong>valid</strong> if <code>x</code> can be rearranged to have <code>word2</code> as a <span data-keyword="string-prefix">prefix</span>.</p> <p>Return the total number of <strong>valid</strong> <span data-keyword="substring-nonempty">substrings</span> of <code>word1</code>.</p> <p><strong>Note</strong> that the memory limits in this problem are <strong>smaller</strong> than usual, so you <strong>must</strong> implement a solution with a <em>linear</em> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;bcca&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only valid substring is <code>&quot;bcca&quot;</code> which can be rearranged to <code>&quot;abcc&quot;</code> having <code>&quot;abc&quot;</code> as a prefix.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>All the substrings except substrings of size 1 and size 2 are valid.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">word1 = &quot;abcabc&quot;, word2 = &quot;aaabc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word1.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= word2.length &lt;= 10<sup>4</sup></code></li> <li><code>word1</code> and <code>word2</code> consist only of lowercase English letters.</li> </ul>
Hash Table; String; Sliding Window
TypeScript
function validSubstringCount(word1: string, word2: string): number { if (word1.length < word2.length) { return 0; } const cnt: number[] = Array(26).fill(0); let need: number = 0; for (const c of word2) { if (++cnt[c.charCodeAt(0) - 97] === 1) { ++need; } } const win: number[] = Array(26).fill(0); let [ans, l] = [0, 0]; for (const c of word1) { const i = c.charCodeAt(0) - 97; if (++win[i] === cnt[i]) { --need; } while (need === 0) { const j = word1[l].charCodeAt(0) - 97; if (win[j] === cnt[j]) { ++need; } --win[j]; ++l; } ans += l; } return ans; }
3,299
Sum of Consecutive Subsequences
Hard
<p>We call an array <code>arr</code> of length <code>n</code> <strong>consecutive</strong> if one of the following holds:</p> <ul> <li><code>arr[i] - arr[i - 1] == 1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> <li><code>arr[i] - arr[i - 1] == -1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> </ul> <p>The <strong>value</strong> of an array is the sum of its elements.</p> <p>For example, <code>[3, 4, 5]</code> is a consecutive array of value 12 and <code>[9, 8]</code> is another of value 17. While <code>[3, 4, 3]</code> and <code>[8, 6]</code> are not consecutive.</p> <p>Given an array of integers <code>nums</code>, return the <em>sum</em> of the <strong>values</strong> of all <strong>consecutive </strong><em>non-empty</em> <span data-keyword="subsequence-array">subsequences</span>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7.</code></p> <p><strong>Note</strong> that an array of length 1 is also considered consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subsequences are: <code>[1]</code>, <code>[2]</code>, <code>[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 = [1,4,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">31</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subsequences are: <code>[1]</code>, <code>[4]</code>, <code>[2]</code>, <code>[3]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[4, 3]</code>, <code>[1, 2, 3]</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>5</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming
C++
class Solution { public: int getSum(vector<int>& nums) { using ll = long long; const int mod = 1e9 + 7; auto calc = [&](const vector<int>& nums) -> ll { int n = nums.size(); vector<ll> left(n), right(n); unordered_map<int, ll> cnt; for (int i = 1; i < n; ++i) { cnt[nums[i - 1]] += 1 + cnt[nums[i - 1] - 1]; left[i] = cnt[nums[i] - 1]; } cnt.clear(); for (int i = n - 2; i >= 0; --i) { cnt[nums[i + 1]] += 1 + cnt[nums[i + 1] + 1]; right[i] = cnt[nums[i] + 1]; } ll ans = 0; for (int i = 0; i < n; ++i) { ans = (ans + (left[i] + right[i] + left[i] * right[i] % mod) * nums[i] % mod) % mod; } return ans; }; ll x = calc(nums); reverse(nums.begin(), nums.end()); ll y = calc(nums); ll s = accumulate(nums.begin(), nums.end(), 0LL); return static_cast<int>((x + y + s) % mod); } };
3,299
Sum of Consecutive Subsequences
Hard
<p>We call an array <code>arr</code> of length <code>n</code> <strong>consecutive</strong> if one of the following holds:</p> <ul> <li><code>arr[i] - arr[i - 1] == 1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> <li><code>arr[i] - arr[i - 1] == -1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> </ul> <p>The <strong>value</strong> of an array is the sum of its elements.</p> <p>For example, <code>[3, 4, 5]</code> is a consecutive array of value 12 and <code>[9, 8]</code> is another of value 17. While <code>[3, 4, 3]</code> and <code>[8, 6]</code> are not consecutive.</p> <p>Given an array of integers <code>nums</code>, return the <em>sum</em> of the <strong>values</strong> of all <strong>consecutive </strong><em>non-empty</em> <span data-keyword="subsequence-array">subsequences</span>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7.</code></p> <p><strong>Note</strong> that an array of length 1 is also considered consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subsequences are: <code>[1]</code>, <code>[2]</code>, <code>[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 = [1,4,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">31</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subsequences are: <code>[1]</code>, <code>[4]</code>, <code>[2]</code>, <code>[3]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[4, 3]</code>, <code>[1, 2, 3]</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>5</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming
Go
func getSum(nums []int) int { const mod = 1e9 + 7 calc := func(nums []int) int64 { n := len(nums) left := make([]int64, n) right := make([]int64, n) cnt := make(map[int]int64) for i := 1; i < n; i++ { cnt[nums[i-1]] += 1 + cnt[nums[i-1]-1] left[i] = cnt[nums[i]-1] } cnt = make(map[int]int64) for i := n - 2; i >= 0; i-- { cnt[nums[i+1]] += 1 + cnt[nums[i+1]+1] right[i] = cnt[nums[i]+1] } var ans int64 for i, x := range nums { ans = (ans + (left[i]+right[i]+(left[i]*right[i]%mod))*int64(x)%mod) % mod } return ans } x := calc(nums) for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 { nums[i], nums[j] = nums[j], nums[i] } y := calc(nums) s := int64(0) for _, num := range nums { s += int64(num) } return int((x + y + s) % mod) }
3,299
Sum of Consecutive Subsequences
Hard
<p>We call an array <code>arr</code> of length <code>n</code> <strong>consecutive</strong> if one of the following holds:</p> <ul> <li><code>arr[i] - arr[i - 1] == 1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> <li><code>arr[i] - arr[i - 1] == -1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> </ul> <p>The <strong>value</strong> of an array is the sum of its elements.</p> <p>For example, <code>[3, 4, 5]</code> is a consecutive array of value 12 and <code>[9, 8]</code> is another of value 17. While <code>[3, 4, 3]</code> and <code>[8, 6]</code> are not consecutive.</p> <p>Given an array of integers <code>nums</code>, return the <em>sum</em> of the <strong>values</strong> of all <strong>consecutive </strong><em>non-empty</em> <span data-keyword="subsequence-array">subsequences</span>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7.</code></p> <p><strong>Note</strong> that an array of length 1 is also considered consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subsequences are: <code>[1]</code>, <code>[2]</code>, <code>[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 = [1,4,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">31</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subsequences are: <code>[1]</code>, <code>[4]</code>, <code>[2]</code>, <code>[3]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[4, 3]</code>, <code>[1, 2, 3]</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>5</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming
Java
class Solution { private final int mod = (int) 1e9 + 7; public int getSum(int[] nums) { long x = calc(nums); for (int i = 0, j = nums.length - 1; i < j; ++i, --j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } long y = calc(nums); long s = Arrays.stream(nums).asLongStream().sum(); return (int) ((x + y + s) % mod); } private long calc(int[] nums) { int n = nums.length; long[] left = new long[n]; long[] right = new long[n]; Map<Integer, Long> cnt = new HashMap<>(); for (int i = 1; i < n; ++i) { cnt.merge(nums[i - 1], 1 + cnt.getOrDefault(nums[i - 1] - 1, 0L), Long::sum); left[i] = cnt.getOrDefault(nums[i] - 1, 0L); } cnt.clear(); for (int i = n - 2; i >= 0; --i) { cnt.merge(nums[i + 1], 1 + cnt.getOrDefault(nums[i + 1] + 1, 0L), Long::sum); right[i] = cnt.getOrDefault(nums[i] + 1, 0L); } long ans = 0; for (int i = 0; i < n; ++i) { ans = (ans + (left[i] + right[i] + left[i] * right[i] % mod) * nums[i] % mod) % mod; } return ans; } }
3,299
Sum of Consecutive Subsequences
Hard
<p>We call an array <code>arr</code> of length <code>n</code> <strong>consecutive</strong> if one of the following holds:</p> <ul> <li><code>arr[i] - arr[i - 1] == 1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> <li><code>arr[i] - arr[i - 1] == -1</code> for <em>all</em> <code>1 &lt;= i &lt; n</code>.</li> </ul> <p>The <strong>value</strong> of an array is the sum of its elements.</p> <p>For example, <code>[3, 4, 5]</code> is a consecutive array of value 12 and <code>[9, 8]</code> is another of value 17. While <code>[3, 4, 3]</code> and <code>[8, 6]</code> are not consecutive.</p> <p>Given an array of integers <code>nums</code>, return the <em>sum</em> of the <strong>values</strong> of all <strong>consecutive </strong><em>non-empty</em> <span data-keyword="subsequence-array">subsequences</span>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7.</code></p> <p><strong>Note</strong> that an array of length 1 is also considered consecutive.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subsequences are: <code>[1]</code>, <code>[2]</code>, <code>[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 = [1,4,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">31</span></p> <p><strong>Explanation:</strong></p> <p>The consecutive subsequences are: <code>[1]</code>, <code>[4]</code>, <code>[2]</code>, <code>[3]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[4, 3]</code>, <code>[1, 2, 3]</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>5</sup></code></li> </ul>
Array; Hash Table; Dynamic Programming
Python
class Solution: def getSum(self, nums: List[int]) -> int: def calc(nums: List[int]) -> int: n = len(nums) left = [0] * n right = [0] * n cnt = Counter() for i in range(1, n): cnt[nums[i - 1]] += 1 + cnt[nums[i - 1] - 1] left[i] = cnt[nums[i] - 1] cnt = Counter() for i in range(n - 2, -1, -1): cnt[nums[i + 1]] += 1 + cnt[nums[i + 1] + 1] right[i] = cnt[nums[i] + 1] return sum((l + r + l * r) * x for l, r, x in zip(left, right, nums)) % mod mod = 10**9 + 7 x = calc(nums) nums.reverse() y = calc(nums) return (x + y + sum(nums)) % mod