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,028
Ant on the Boundary
Easy
<p>An ant is on a boundary. It sometimes goes <strong>left</strong> and sometimes <strong>right</strong>.</p> <p>You are given an array of <strong>non-zero</strong> integers <code>nums</code>. The ant starts reading <code>nums</code> from the first element of it to its end. At each step, it moves according to the value of the current element:</p> <ul> <li>If <code>nums[i] &lt; 0</code>, it moves <strong>left</strong> by<!-- notionvc: 55fee232-4fc9-445f-952a-f1b979415864 --> <code>-nums[i]</code> units.</li> <li>If <code>nums[i] &gt; 0</code>, it moves <strong>right</strong> by <code>nums[i]</code> units.</li> </ul> <p>Return <em>the number of times the ant <strong>returns</strong> to the boundary.</em></p> <p><strong>Notes:</strong></p> <ul> <li>There is an infinite space on both sides of the boundary.</li> <li>We check whether the ant is on the boundary only after it has moved <code>|nums[i]|</code> units. In other words, if the ant crosses the boundary during its movement, it does not count.<!-- notionvc: 5ff95338-8634-4d02-a085-1e83c0be6fcd --></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,-5] <strong>Output:</strong> 1 <strong>Explanation:</strong> After the first step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the third step, the ant is on the boundary. So the answer is 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,-3,-4] <strong>Output:</strong> 0 <strong>Explanation:</strong> After the first step, the ant is 3 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the third step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the fourth step, the ant is 2 steps to the left of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. The ant never returned to the boundary, so the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> <li><code>nums[i] != 0</code></li> </ul>
Array; Prefix Sum; Simulation
Java
class Solution { public int returnToBoundaryCount(int[] nums) { int ans = 0, s = 0; for (int x : nums) { s += x; if (s == 0) { ++ans; } } return ans; } }
3,028
Ant on the Boundary
Easy
<p>An ant is on a boundary. It sometimes goes <strong>left</strong> and sometimes <strong>right</strong>.</p> <p>You are given an array of <strong>non-zero</strong> integers <code>nums</code>. The ant starts reading <code>nums</code> from the first element of it to its end. At each step, it moves according to the value of the current element:</p> <ul> <li>If <code>nums[i] &lt; 0</code>, it moves <strong>left</strong> by<!-- notionvc: 55fee232-4fc9-445f-952a-f1b979415864 --> <code>-nums[i]</code> units.</li> <li>If <code>nums[i] &gt; 0</code>, it moves <strong>right</strong> by <code>nums[i]</code> units.</li> </ul> <p>Return <em>the number of times the ant <strong>returns</strong> to the boundary.</em></p> <p><strong>Notes:</strong></p> <ul> <li>There is an infinite space on both sides of the boundary.</li> <li>We check whether the ant is on the boundary only after it has moved <code>|nums[i]|</code> units. In other words, if the ant crosses the boundary during its movement, it does not count.<!-- notionvc: 5ff95338-8634-4d02-a085-1e83c0be6fcd --></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,-5] <strong>Output:</strong> 1 <strong>Explanation:</strong> After the first step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the third step, the ant is on the boundary. So the answer is 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,-3,-4] <strong>Output:</strong> 0 <strong>Explanation:</strong> After the first step, the ant is 3 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the third step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the fourth step, the ant is 2 steps to the left of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. The ant never returned to the boundary, so the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> <li><code>nums[i] != 0</code></li> </ul>
Array; Prefix Sum; Simulation
Python
class Solution: def returnToBoundaryCount(self, nums: List[int]) -> int: return sum(s == 0 for s in accumulate(nums))
3,028
Ant on the Boundary
Easy
<p>An ant is on a boundary. It sometimes goes <strong>left</strong> and sometimes <strong>right</strong>.</p> <p>You are given an array of <strong>non-zero</strong> integers <code>nums</code>. The ant starts reading <code>nums</code> from the first element of it to its end. At each step, it moves according to the value of the current element:</p> <ul> <li>If <code>nums[i] &lt; 0</code>, it moves <strong>left</strong> by<!-- notionvc: 55fee232-4fc9-445f-952a-f1b979415864 --> <code>-nums[i]</code> units.</li> <li>If <code>nums[i] &gt; 0</code>, it moves <strong>right</strong> by <code>nums[i]</code> units.</li> </ul> <p>Return <em>the number of times the ant <strong>returns</strong> to the boundary.</em></p> <p><strong>Notes:</strong></p> <ul> <li>There is an infinite space on both sides of the boundary.</li> <li>We check whether the ant is on the boundary only after it has moved <code>|nums[i]|</code> units. In other words, if the ant crosses the boundary during its movement, it does not count.<!-- notionvc: 5ff95338-8634-4d02-a085-1e83c0be6fcd --></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,3,-5] <strong>Output:</strong> 1 <strong>Explanation:</strong> After the first step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the third step, the ant is on the boundary. So the answer is 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,-3,-4] <strong>Output:</strong> 0 <strong>Explanation:</strong> After the first step, the ant is 3 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the second step, the ant is 5 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the third step, the ant is 2 steps to the right of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. After the fourth step, the ant is 2 steps to the left of the boundary<!-- notionvc: 61ace51c-559f-4bc6-800f-0a0db2540433 -->. The ant never returned to the boundary, so the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-10 &lt;= nums[i] &lt;= 10</code></li> <li><code>nums[i] != 0</code></li> </ul>
Array; Prefix Sum; Simulation
TypeScript
function returnToBoundaryCount(nums: number[]): number { let [ans, s] = [0, 0]; for (const x of nums) { s += x; ans += s === 0 ? 1 : 0; } return ans; }
3,029
Minimum Time to Revert Word to Initial State I
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p> <p>At every second, you must perform the following operations:</p> <ul> <li>Remove the first <code>k</code> characters of <code>word</code>.</li> <li>Add any <code>k</code> characters to the end of <code>word</code>.</li> </ul> <p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p> <p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;aba&quot; from the prefix of word, and add characters &quot;bac&quot; to the end of word. Thus, word becomes equal to &quot;cababac&quot;. At the 2nd second, we remove characters &quot;cab&quot; from the prefix of word, and add &quot;aba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 4 <strong>Output:</strong> 1 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;abac&quot; from the prefix of word, and add characters &quot;caba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcbabcd&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word. After 4 seconds, word becomes equal to &quot;abcbabcd&quot; and reverts to its initial state. It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 50 </code></li> <li><code>1 &lt;= k &lt;= word.length</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String; String Matching; Hash Function; Rolling Hash
C++
class Solution { public: int minimumTimeToInitialState(string word, int k) { int n = word.size(); for (int i = k; i < n; i += k) { if (word.substr(i) == word.substr(0, n - i)) { return i / k; } } return (n + k - 1) / k; } };
3,029
Minimum Time to Revert Word to Initial State I
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p> <p>At every second, you must perform the following operations:</p> <ul> <li>Remove the first <code>k</code> characters of <code>word</code>.</li> <li>Add any <code>k</code> characters to the end of <code>word</code>.</li> </ul> <p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p> <p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;aba&quot; from the prefix of word, and add characters &quot;bac&quot; to the end of word. Thus, word becomes equal to &quot;cababac&quot;. At the 2nd second, we remove characters &quot;cab&quot; from the prefix of word, and add &quot;aba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 4 <strong>Output:</strong> 1 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;abac&quot; from the prefix of word, and add characters &quot;caba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcbabcd&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word. After 4 seconds, word becomes equal to &quot;abcbabcd&quot; and reverts to its initial state. It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 50 </code></li> <li><code>1 &lt;= k &lt;= word.length</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String; String Matching; Hash Function; Rolling Hash
Go
func minimumTimeToInitialState(word string, k int) int { n := len(word) for i := k; i < n; i += k { if word[i:] == word[:n-i] { return i / k } } return (n + k - 1) / k }
3,029
Minimum Time to Revert Word to Initial State I
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p> <p>At every second, you must perform the following operations:</p> <ul> <li>Remove the first <code>k</code> characters of <code>word</code>.</li> <li>Add any <code>k</code> characters to the end of <code>word</code>.</li> </ul> <p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p> <p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;aba&quot; from the prefix of word, and add characters &quot;bac&quot; to the end of word. Thus, word becomes equal to &quot;cababac&quot;. At the 2nd second, we remove characters &quot;cab&quot; from the prefix of word, and add &quot;aba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 4 <strong>Output:</strong> 1 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;abac&quot; from the prefix of word, and add characters &quot;caba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcbabcd&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word. After 4 seconds, word becomes equal to &quot;abcbabcd&quot; and reverts to its initial state. It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 50 </code></li> <li><code>1 &lt;= k &lt;= word.length</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String; String Matching; Hash Function; Rolling Hash
Java
class Solution { public int minimumTimeToInitialState(String word, int k) { int n = word.length(); for (int i = k; i < n; i += k) { if (word.substring(i).equals(word.substring(0, n - i))) { return i / k; } } return (n + k - 1) / k; } }
3,029
Minimum Time to Revert Word to Initial State I
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p> <p>At every second, you must perform the following operations:</p> <ul> <li>Remove the first <code>k</code> characters of <code>word</code>.</li> <li>Add any <code>k</code> characters to the end of <code>word</code>.</li> </ul> <p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p> <p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;aba&quot; from the prefix of word, and add characters &quot;bac&quot; to the end of word. Thus, word becomes equal to &quot;cababac&quot;. At the 2nd second, we remove characters &quot;cab&quot; from the prefix of word, and add &quot;aba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 4 <strong>Output:</strong> 1 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;abac&quot; from the prefix of word, and add characters &quot;caba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcbabcd&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word. After 4 seconds, word becomes equal to &quot;abcbabcd&quot; and reverts to its initial state. It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 50 </code></li> <li><code>1 &lt;= k &lt;= word.length</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String; String Matching; Hash Function; Rolling Hash
Python
class Solution: def minimumTimeToInitialState(self, word: str, k: int) -> int: n = len(word) for i in range(k, n, k): if word[i:] == word[:-i]: return i // k return (n + k - 1) // k
3,029
Minimum Time to Revert Word to Initial State I
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p> <p>At every second, you must perform the following operations:</p> <ul> <li>Remove the first <code>k</code> characters of <code>word</code>.</li> <li>Add any <code>k</code> characters to the end of <code>word</code>.</li> </ul> <p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p> <p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;aba&quot; from the prefix of word, and add characters &quot;bac&quot; to the end of word. Thus, word becomes equal to &quot;cababac&quot;. At the 2nd second, we remove characters &quot;cab&quot; from the prefix of word, and add &quot;aba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 4 <strong>Output:</strong> 1 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;abac&quot; from the prefix of word, and add characters &quot;caba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcbabcd&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word. After 4 seconds, word becomes equal to &quot;abcbabcd&quot; and reverts to its initial state. It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 50 </code></li> <li><code>1 &lt;= k &lt;= word.length</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String; String Matching; Hash Function; Rolling Hash
TypeScript
function minimumTimeToInitialState(word: string, k: number): number { const n = word.length; for (let i = k; i < n; i += k) { if (word.slice(i) === word.slice(0, -i)) { return Math.floor(i / k); } } return Math.floor((n + k - 1) / k); }
3,030
Find the Grid of Region Average
Medium
<p>You are given <code>m x n</code> grid <code>image</code> which represents a grayscale image, where <code>image[i][j]</code> represents a pixel with intensity in the range <code>[0..255]</code>. You are also given a <strong>non-negative</strong> integer <code>threshold</code>.</p> <p>Two pixels are <strong>adjacent</strong> if they share an edge.</p> <p>A <strong>region</strong> is a <code>3 x 3</code> subgrid where the <strong>absolute difference</strong> in intensity between any two <strong>adjacent</strong> pixels is <strong>less than or equal to</strong> <code>threshold</code>.</p> <p>All pixels in a region belong to that region, note that a pixel can belong to <strong>multiple</strong> regions.</p> <p>You need to calculate a <code>m x n</code> grid <code>result</code>, where <code>result[i][j]</code> is the <strong>average</strong> intensity of the regions to which <code>image[i][j]</code> belongs, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> belongs to multiple regions, <code>result[i][j]</code> is the <strong>average </strong>of the<strong> rounded-down average </strong>intensities of these regions, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> does<strong> not</strong> belong to any region, <code>result[i][j]</code> is <strong>equal to</strong> <code>image[i][j]</code>.</p> <p>Return the grid <code>result</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">image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[9,9,9,9],[9,9,9,9],[9,9,9,9]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example0corrected.png" style="width: 832px; height: 275px;" /></p> <p>There are two regions as illustrated above. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9.</p> <p>Please note that the rounded-down values are used when calculating the average of multiple regions, hence the calculation is done using 9 as the average intensity of region 2, not 9.67.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">image = [[10,20,30],[15,25,35],[20,30,40],[25,35,45]], threshold = 12</span></p> <p><strong>Output:</strong> <span class="example-io">[[25,25,25],[27,27,27],[27,27,27],[30,30,30]]</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example1corrected.png" /></p> <p>There are two regions as illustrated above. The average intensity of the first region is 25, while the average intensity of the second region is 30. The average intensity of both of the regions is (25 + 30) / 2 = 27.5 which is rounded down to 27.</p> <p>All the pixels in row 0 of the image belong to region 1, hence all the pixels in row 0 in the result are 25. Similarly, all the pixels in row 3 in the result are 30. The pixels in rows 1 and 2 of the image belong to region 1 and region 2, hence their assigned value is 27 in the result.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">image = [[5,6,7],[8,9,10],[11,12,13]], threshold = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[[5,6,7],[8,9,10],[11,12,13]]</span></p> <p><strong>Explanation:</strong></p> <p>There is only one <code>3 x 3</code> subgrid, while it does not have the condition on difference of adjacent pixels, for example, the difference between <code>image[0][0]</code> and <code>image[1][0]</code> is <code>|5 - 8| = 3 &gt; threshold = 1</code>. None of them belong to any valid regions, so the <code>result</code> should be the same as <code>image</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= image[i][j] &lt;= 255</code></li> <li><code>0 &lt;= threshold &lt;= 255</code></li> </ul>
Array; Matrix
C++
class Solution { public: vector<vector<int>> resultGrid(vector<vector<int>>& image, int threshold) { int n = image.size(), m = image[0].size(); vector<vector<int>> ans(n, vector<int>(m)); vector<vector<int>> ct(n, vector<int>(m)); for (int i = 0; i + 2 < n; ++i) { for (int j = 0; j + 2 < m; ++j) { bool region = true; for (int k = 0; k < 3; ++k) { for (int l = 0; l < 2; ++l) { region &= abs(image[i + k][j + l] - image[i + k][j + l + 1]) <= threshold; } } for (int k = 0; k < 2; ++k) { for (int l = 0; l < 3; ++l) { region &= abs(image[i + k][j + l] - image[i + k + 1][j + l]) <= threshold; } } if (region) { int tot = 0; for (int k = 0; k < 3; ++k) { for (int l = 0; l < 3; ++l) { tot += image[i + k][j + l]; } } for (int k = 0; k < 3; ++k) { for (int l = 0; l < 3; ++l) { ct[i + k][j + l]++; ans[i + k][j + l] += tot / 9; } } } } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (ct[i][j] == 0) { ans[i][j] = image[i][j]; } else { ans[i][j] /= ct[i][j]; } } } return ans; } };
3,030
Find the Grid of Region Average
Medium
<p>You are given <code>m x n</code> grid <code>image</code> which represents a grayscale image, where <code>image[i][j]</code> represents a pixel with intensity in the range <code>[0..255]</code>. You are also given a <strong>non-negative</strong> integer <code>threshold</code>.</p> <p>Two pixels are <strong>adjacent</strong> if they share an edge.</p> <p>A <strong>region</strong> is a <code>3 x 3</code> subgrid where the <strong>absolute difference</strong> in intensity between any two <strong>adjacent</strong> pixels is <strong>less than or equal to</strong> <code>threshold</code>.</p> <p>All pixels in a region belong to that region, note that a pixel can belong to <strong>multiple</strong> regions.</p> <p>You need to calculate a <code>m x n</code> grid <code>result</code>, where <code>result[i][j]</code> is the <strong>average</strong> intensity of the regions to which <code>image[i][j]</code> belongs, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> belongs to multiple regions, <code>result[i][j]</code> is the <strong>average </strong>of the<strong> rounded-down average </strong>intensities of these regions, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> does<strong> not</strong> belong to any region, <code>result[i][j]</code> is <strong>equal to</strong> <code>image[i][j]</code>.</p> <p>Return the grid <code>result</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">image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[9,9,9,9],[9,9,9,9],[9,9,9,9]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example0corrected.png" style="width: 832px; height: 275px;" /></p> <p>There are two regions as illustrated above. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9.</p> <p>Please note that the rounded-down values are used when calculating the average of multiple regions, hence the calculation is done using 9 as the average intensity of region 2, not 9.67.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">image = [[10,20,30],[15,25,35],[20,30,40],[25,35,45]], threshold = 12</span></p> <p><strong>Output:</strong> <span class="example-io">[[25,25,25],[27,27,27],[27,27,27],[30,30,30]]</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example1corrected.png" /></p> <p>There are two regions as illustrated above. The average intensity of the first region is 25, while the average intensity of the second region is 30. The average intensity of both of the regions is (25 + 30) / 2 = 27.5 which is rounded down to 27.</p> <p>All the pixels in row 0 of the image belong to region 1, hence all the pixels in row 0 in the result are 25. Similarly, all the pixels in row 3 in the result are 30. The pixels in rows 1 and 2 of the image belong to region 1 and region 2, hence their assigned value is 27 in the result.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">image = [[5,6,7],[8,9,10],[11,12,13]], threshold = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[[5,6,7],[8,9,10],[11,12,13]]</span></p> <p><strong>Explanation:</strong></p> <p>There is only one <code>3 x 3</code> subgrid, while it does not have the condition on difference of adjacent pixels, for example, the difference between <code>image[0][0]</code> and <code>image[1][0]</code> is <code>|5 - 8| = 3 &gt; threshold = 1</code>. None of them belong to any valid regions, so the <code>result</code> should be the same as <code>image</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= image[i][j] &lt;= 255</code></li> <li><code>0 &lt;= threshold &lt;= 255</code></li> </ul>
Array; Matrix
Go
func resultGrid(image [][]int, threshold int) [][]int { n := len(image) m := len(image[0]) ans := make([][]int, n) ct := make([][]int, n) for i := range ans { ans[i] = make([]int, m) ct[i] = make([]int, m) } for i := 0; i+2 < n; i++ { for j := 0; j+2 < m; j++ { region := true for k := 0; k < 3; k++ { for l := 0; l < 2; l++ { region = region && abs(image[i+k][j+l]-image[i+k][j+l+1]) <= threshold } } for k := 0; k < 2; k++ { for l := 0; l < 3; l++ { region = region && abs(image[i+k][j+l]-image[i+k+1][j+l]) <= threshold } } if region { tot := 0 for k := 0; k < 3; k++ { for l := 0; l < 3; l++ { tot += image[i+k][j+l] } } for k := 0; k < 3; k++ { for l := 0; l < 3; l++ { ct[i+k][j+l]++ ans[i+k][j+l] += tot / 9 } } } } } for i := 0; i < n; i++ { for j := 0; j < m; j++ { if ct[i][j] == 0 { ans[i][j] = image[i][j] } else { ans[i][j] /= ct[i][j] } } } return ans } func abs(x int) int { if x < 0 { return -x } return x }
3,030
Find the Grid of Region Average
Medium
<p>You are given <code>m x n</code> grid <code>image</code> which represents a grayscale image, where <code>image[i][j]</code> represents a pixel with intensity in the range <code>[0..255]</code>. You are also given a <strong>non-negative</strong> integer <code>threshold</code>.</p> <p>Two pixels are <strong>adjacent</strong> if they share an edge.</p> <p>A <strong>region</strong> is a <code>3 x 3</code> subgrid where the <strong>absolute difference</strong> in intensity between any two <strong>adjacent</strong> pixels is <strong>less than or equal to</strong> <code>threshold</code>.</p> <p>All pixels in a region belong to that region, note that a pixel can belong to <strong>multiple</strong> regions.</p> <p>You need to calculate a <code>m x n</code> grid <code>result</code>, where <code>result[i][j]</code> is the <strong>average</strong> intensity of the regions to which <code>image[i][j]</code> belongs, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> belongs to multiple regions, <code>result[i][j]</code> is the <strong>average </strong>of the<strong> rounded-down average </strong>intensities of these regions, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> does<strong> not</strong> belong to any region, <code>result[i][j]</code> is <strong>equal to</strong> <code>image[i][j]</code>.</p> <p>Return the grid <code>result</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">image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[9,9,9,9],[9,9,9,9],[9,9,9,9]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example0corrected.png" style="width: 832px; height: 275px;" /></p> <p>There are two regions as illustrated above. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9.</p> <p>Please note that the rounded-down values are used when calculating the average of multiple regions, hence the calculation is done using 9 as the average intensity of region 2, not 9.67.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">image = [[10,20,30],[15,25,35],[20,30,40],[25,35,45]], threshold = 12</span></p> <p><strong>Output:</strong> <span class="example-io">[[25,25,25],[27,27,27],[27,27,27],[30,30,30]]</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example1corrected.png" /></p> <p>There are two regions as illustrated above. The average intensity of the first region is 25, while the average intensity of the second region is 30. The average intensity of both of the regions is (25 + 30) / 2 = 27.5 which is rounded down to 27.</p> <p>All the pixels in row 0 of the image belong to region 1, hence all the pixels in row 0 in the result are 25. Similarly, all the pixels in row 3 in the result are 30. The pixels in rows 1 and 2 of the image belong to region 1 and region 2, hence their assigned value is 27 in the result.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">image = [[5,6,7],[8,9,10],[11,12,13]], threshold = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[[5,6,7],[8,9,10],[11,12,13]]</span></p> <p><strong>Explanation:</strong></p> <p>There is only one <code>3 x 3</code> subgrid, while it does not have the condition on difference of adjacent pixels, for example, the difference between <code>image[0][0]</code> and <code>image[1][0]</code> is <code>|5 - 8| = 3 &gt; threshold = 1</code>. None of them belong to any valid regions, so the <code>result</code> should be the same as <code>image</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= image[i][j] &lt;= 255</code></li> <li><code>0 &lt;= threshold &lt;= 255</code></li> </ul>
Array; Matrix
Java
class Solution { public int[][] resultGrid(int[][] image, int threshold) { int n = image.length; int m = image[0].length; int[][] ans = new int[n][m]; int[][] ct = new int[n][m]; for (int i = 0; i + 2 < n; ++i) { for (int j = 0; j + 2 < m; ++j) { boolean region = true; for (int k = 0; k < 3; ++k) { for (int l = 0; l < 2; ++l) { region &= Math.abs(image[i + k][j + l] - image[i + k][j + l + 1]) <= threshold; } } for (int k = 0; k < 2; ++k) { for (int l = 0; l < 3; ++l) { region &= Math.abs(image[i + k][j + l] - image[i + k + 1][j + l]) <= threshold; } } if (region) { int tot = 0; for (int k = 0; k < 3; ++k) { for (int l = 0; l < 3; ++l) { tot += image[i + k][j + l]; } } for (int k = 0; k < 3; ++k) { for (int l = 0; l < 3; ++l) { ct[i + k][j + l]++; ans[i + k][j + l] += tot / 9; } } } } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (ct[i][j] == 0) { ans[i][j] = image[i][j]; } else { ans[i][j] /= ct[i][j]; } } } return ans; } }
3,030
Find the Grid of Region Average
Medium
<p>You are given <code>m x n</code> grid <code>image</code> which represents a grayscale image, where <code>image[i][j]</code> represents a pixel with intensity in the range <code>[0..255]</code>. You are also given a <strong>non-negative</strong> integer <code>threshold</code>.</p> <p>Two pixels are <strong>adjacent</strong> if they share an edge.</p> <p>A <strong>region</strong> is a <code>3 x 3</code> subgrid where the <strong>absolute difference</strong> in intensity between any two <strong>adjacent</strong> pixels is <strong>less than or equal to</strong> <code>threshold</code>.</p> <p>All pixels in a region belong to that region, note that a pixel can belong to <strong>multiple</strong> regions.</p> <p>You need to calculate a <code>m x n</code> grid <code>result</code>, where <code>result[i][j]</code> is the <strong>average</strong> intensity of the regions to which <code>image[i][j]</code> belongs, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> belongs to multiple regions, <code>result[i][j]</code> is the <strong>average </strong>of the<strong> rounded-down average </strong>intensities of these regions, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> does<strong> not</strong> belong to any region, <code>result[i][j]</code> is <strong>equal to</strong> <code>image[i][j]</code>.</p> <p>Return the grid <code>result</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">image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[9,9,9,9],[9,9,9,9],[9,9,9,9]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example0corrected.png" style="width: 832px; height: 275px;" /></p> <p>There are two regions as illustrated above. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9.</p> <p>Please note that the rounded-down values are used when calculating the average of multiple regions, hence the calculation is done using 9 as the average intensity of region 2, not 9.67.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">image = [[10,20,30],[15,25,35],[20,30,40],[25,35,45]], threshold = 12</span></p> <p><strong>Output:</strong> <span class="example-io">[[25,25,25],[27,27,27],[27,27,27],[30,30,30]]</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example1corrected.png" /></p> <p>There are two regions as illustrated above. The average intensity of the first region is 25, while the average intensity of the second region is 30. The average intensity of both of the regions is (25 + 30) / 2 = 27.5 which is rounded down to 27.</p> <p>All the pixels in row 0 of the image belong to region 1, hence all the pixels in row 0 in the result are 25. Similarly, all the pixels in row 3 in the result are 30. The pixels in rows 1 and 2 of the image belong to region 1 and region 2, hence their assigned value is 27 in the result.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">image = [[5,6,7],[8,9,10],[11,12,13]], threshold = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[[5,6,7],[8,9,10],[11,12,13]]</span></p> <p><strong>Explanation:</strong></p> <p>There is only one <code>3 x 3</code> subgrid, while it does not have the condition on difference of adjacent pixels, for example, the difference between <code>image[0][0]</code> and <code>image[1][0]</code> is <code>|5 - 8| = 3 &gt; threshold = 1</code>. None of them belong to any valid regions, so the <code>result</code> should be the same as <code>image</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= image[i][j] &lt;= 255</code></li> <li><code>0 &lt;= threshold &lt;= 255</code></li> </ul>
Array; Matrix
Python
class Solution: def resultGrid(self, image: List[List[int]], threshold: int) -> List[List[int]]: n, m = len(image), len(image[0]) ans = [[0] * m for _ in range(n)] ct = [[0] * m for _ in range(n)] for i in range(n - 2): for j in range(m - 2): region = True for k in range(3): for l in range(2): region &= ( abs(image[i + k][j + l] - image[i + k][j + l + 1]) <= threshold ) for k in range(2): for l in range(3): region &= ( abs(image[i + k][j + l] - image[i + k + 1][j + l]) <= threshold ) if region: tot = 0 for k in range(3): for l in range(3): tot += image[i + k][j + l] for k in range(3): for l in range(3): ct[i + k][j + l] += 1 ans[i + k][j + l] += tot // 9 for i in range(n): for j in range(m): if ct[i][j] == 0: ans[i][j] = image[i][j] else: ans[i][j] //= ct[i][j] return ans
3,030
Find the Grid of Region Average
Medium
<p>You are given <code>m x n</code> grid <code>image</code> which represents a grayscale image, where <code>image[i][j]</code> represents a pixel with intensity in the range <code>[0..255]</code>. You are also given a <strong>non-negative</strong> integer <code>threshold</code>.</p> <p>Two pixels are <strong>adjacent</strong> if they share an edge.</p> <p>A <strong>region</strong> is a <code>3 x 3</code> subgrid where the <strong>absolute difference</strong> in intensity between any two <strong>adjacent</strong> pixels is <strong>less than or equal to</strong> <code>threshold</code>.</p> <p>All pixels in a region belong to that region, note that a pixel can belong to <strong>multiple</strong> regions.</p> <p>You need to calculate a <code>m x n</code> grid <code>result</code>, where <code>result[i][j]</code> is the <strong>average</strong> intensity of the regions to which <code>image[i][j]</code> belongs, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> belongs to multiple regions, <code>result[i][j]</code> is the <strong>average </strong>of the<strong> rounded-down average </strong>intensities of these regions, <strong>rounded down</strong> to the nearest integer. If <code>image[i][j]</code> does<strong> not</strong> belong to any region, <code>result[i][j]</code> is <strong>equal to</strong> <code>image[i][j]</code>.</p> <p>Return the grid <code>result</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">image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[[9,9,9,9],[9,9,9,9],[9,9,9,9]]</span></p> <p><strong>Explanation:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example0corrected.png" style="width: 832px; height: 275px;" /></p> <p>There are two regions as illustrated above. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9.</p> <p>Please note that the rounded-down values are used when calculating the average of multiple regions, hence the calculation is done using 9 as the average intensity of region 2, not 9.67.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">image = [[10,20,30],[15,25,35],[20,30,40],[25,35,45]], threshold = 12</span></p> <p><strong>Output:</strong> <span class="example-io">[[25,25,25],[27,27,27],[27,27,27],[30,30,30]]</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3030.Find%20the%20Grid%20of%20Region%20Average/images/example1corrected.png" /></p> <p>There are two regions as illustrated above. The average intensity of the first region is 25, while the average intensity of the second region is 30. The average intensity of both of the regions is (25 + 30) / 2 = 27.5 which is rounded down to 27.</p> <p>All the pixels in row 0 of the image belong to region 1, hence all the pixels in row 0 in the result are 25. Similarly, all the pixels in row 3 in the result are 30. The pixels in rows 1 and 2 of the image belong to region 1 and region 2, hence their assigned value is 27 in the result.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">image = [[5,6,7],[8,9,10],[11,12,13]], threshold = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[[5,6,7],[8,9,10],[11,12,13]]</span></p> <p><strong>Explanation:</strong></p> <p>There is only one <code>3 x 3</code> subgrid, while it does not have the condition on difference of adjacent pixels, for example, the difference between <code>image[0][0]</code> and <code>image[1][0]</code> is <code>|5 - 8| = 3 &gt; threshold = 1</code>. None of them belong to any valid regions, so the <code>result</code> should be the same as <code>image</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n, m &lt;= 500</code></li> <li><code>0 &lt;= image[i][j] &lt;= 255</code></li> <li><code>0 &lt;= threshold &lt;= 255</code></li> </ul>
Array; Matrix
TypeScript
function resultGrid(image: number[][], threshold: number): number[][] { const n: number = image.length; const m: number = image[0].length; const ans: number[][] = new Array(n).fill(0).map(() => new Array(m).fill(0)); const ct: number[][] = new Array(n).fill(0).map(() => new Array(m).fill(0)); for (let i = 0; i + 2 < n; ++i) { for (let j = 0; j + 2 < m; ++j) { let region: boolean = true; for (let k = 0; k < 3; ++k) { for (let l = 0; l < 2; ++l) { region &&= Math.abs(image[i + k][j + l] - image[i + k][j + l + 1]) <= threshold; } } for (let k = 0; k < 2; ++k) { for (let l = 0; l < 3; ++l) { region &&= Math.abs(image[i + k][j + l] - image[i + k + 1][j + l]) <= threshold; } } if (region) { let tot: number = 0; for (let k = 0; k < 3; ++k) { for (let l = 0; l < 3; ++l) { tot += image[i + k][j + l]; } } for (let k = 0; k < 3; ++k) { for (let l = 0; l < 3; ++l) { ct[i + k][j + l]++; ans[i + k][j + l] += Math.floor(tot / 9); } } } } } for (let i = 0; i < n; ++i) { for (let j = 0; j < m; ++j) { if (ct[i][j] === 0) { ans[i][j] = image[i][j]; } else { ans[i][j] = Math.floor(ans[i][j] / ct[i][j]); } } } return ans; }
3,031
Minimum Time to Revert Word to Initial State II
Hard
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p> <p>At every second, you must perform the following operations:</p> <ul> <li>Remove the first <code>k</code> characters of <code>word</code>.</li> <li>Add any <code>k</code> characters to the end of <code>word</code>.</li> </ul> <p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p> <p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;aba&quot; from the prefix of word, and add characters &quot;bac&quot; to the end of word. Thus, word becomes equal to &quot;cababac&quot;. At the 2nd second, we remove characters &quot;cab&quot; from the prefix of word, and add &quot;aba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 4 <strong>Output:</strong> 1 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;abac&quot; from the prefix of word, and add characters &quot;caba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcbabcd&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word. After 4 seconds, word becomes equal to &quot;abcbabcd&quot; and reverts to its initial state. It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= word.length</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String; String Matching; Hash Function; Rolling Hash
C++
class Hashing { private: vector<long long> p; vector<long long> h; long long mod; public: Hashing(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] - 'a') % 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 minimumTimeToInitialState(string word, int k) { Hashing hashing(word, 13331, 998244353); int n = word.size(); for (int i = k; i < n; i += k) { if (hashing.query(1, n - i) == hashing.query(i + 1, n)) { return i / k; } } return (n + k - 1) / k; } };
3,031
Minimum Time to Revert Word to Initial State II
Hard
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p> <p>At every second, you must perform the following operations:</p> <ul> <li>Remove the first <code>k</code> characters of <code>word</code>.</li> <li>Add any <code>k</code> characters to the end of <code>word</code>.</li> </ul> <p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p> <p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;aba&quot; from the prefix of word, and add characters &quot;bac&quot; to the end of word. Thus, word becomes equal to &quot;cababac&quot;. At the 2nd second, we remove characters &quot;cab&quot; from the prefix of word, and add &quot;aba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 4 <strong>Output:</strong> 1 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;abac&quot; from the prefix of word, and add characters &quot;caba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcbabcd&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word. After 4 seconds, word becomes equal to &quot;abcbabcd&quot; and reverts to its initial state. It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= word.length</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String; 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]-'a')) % 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 minimumTimeToInitialState(word string, k int) int { hashing := NewHashing(word, 13331, 998244353) n := len(word) for i := k; i < n; i += k { if hashing.Query(1, n-i) == hashing.Query(i+1, n) { return i / k } } return (n + k - 1) / k }
3,031
Minimum Time to Revert Word to Initial State II
Hard
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p> <p>At every second, you must perform the following operations:</p> <ul> <li>Remove the first <code>k</code> characters of <code>word</code>.</li> <li>Add any <code>k</code> characters to the end of <code>word</code>.</li> </ul> <p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p> <p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;aba&quot; from the prefix of word, and add characters &quot;bac&quot; to the end of word. Thus, word becomes equal to &quot;cababac&quot;. At the 2nd second, we remove characters &quot;cab&quot; from the prefix of word, and add &quot;aba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 4 <strong>Output:</strong> 1 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;abac&quot; from the prefix of word, and add characters &quot;caba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcbabcd&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word. After 4 seconds, word becomes equal to &quot;abcbabcd&quot; and reverts to its initial state. It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= word.length</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String; 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) - 'a') % mod; } } public long query(int l, int r) { return (h[r] - h[l - 1] * p[r - l + 1] % mod + mod) % mod; } } class Solution { public int minimumTimeToInitialState(String word, int k) { Hashing hashing = new Hashing(word, 13331, 998244353); int n = word.length(); for (int i = k; i < n; i += k) { if (hashing.query(1, n - i) == hashing.query(i + 1, n)) { return i / k; } } return (n + k - 1) / k; } }
3,031
Minimum Time to Revert Word to Initial State II
Hard
<p>You are given a <strong>0-indexed</strong> string <code>word</code> and an integer <code>k</code>.</p> <p>At every second, you must perform the following operations:</p> <ul> <li>Remove the first <code>k</code> characters of <code>word</code>.</li> <li>Add any <code>k</code> characters to the end of <code>word</code>.</li> </ul> <p><strong>Note</strong> that you do not necessarily need to add the same characters that you removed. However, you must perform <strong>both</strong> operations at every second.</p> <p>Return <em>the <strong>minimum</strong> time greater than zero required for</em> <code>word</code> <em>to revert to its <strong>initial</strong> state</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 3 <strong>Output:</strong> 2 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;aba&quot; from the prefix of word, and add characters &quot;bac&quot; to the end of word. Thus, word becomes equal to &quot;cababac&quot;. At the 2nd second, we remove characters &quot;cab&quot; from the prefix of word, and add &quot;aba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abacaba&quot;, k = 4 <strong>Output:</strong> 1 <strong>Explanation:</strong> At the 1st second, we remove characters &quot;abac&quot; from the prefix of word, and add characters &quot;caba&quot; to the end of word. Thus, word becomes equal to &quot;abacaba&quot; and reverts to its initial state. It can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcbabcd&quot;, k = 2 <strong>Output:</strong> 4 <strong>Explanation:</strong> At every second, we will remove the first 2 characters of word, and add the same characters to the end of word. After 4 seconds, word becomes equal to &quot;abcbabcd&quot; and reverts to its initial state. It can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= word.length</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
String; String Matching; Hash Function; Rolling Hash
Python
class Hashing: __slots__ = ["mod", "h", "p"] def __init__(self, s: 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 minimumTimeToInitialState(self, word: str, k: int) -> int: hashing = Hashing(word, 13331, 998244353) n = len(word) for i in range(k, n, k): if hashing.query(1, n - i) == hashing.query(i + 1, n): return i // k return (n + k - 1) // k
3,032
Count Numbers With Unique Digits II
Easy
Given two <strong>positive</strong> integers <code>a</code> and <code>b</code>, return <em>the count of numbers having&nbsp;<strong>unique</strong> digits in the range</em> <code>[a, b]</code> <em>(<strong>inclusive</strong>).</em> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = 1, b = 20 <strong>Output:</strong> 19 <strong>Explanation:</strong> All the numbers in the range [1, 20] have unique digits except 11. Hence, the answer is 19. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = 9, b = 19 <strong>Output:</strong> 10 <strong>Explanation:</strong> All the numbers in the range [9, 19] have unique digits except 11. Hence, the answer is 10. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = 80, b = 120 <strong>Output:</strong> 27 <strong>Explanation:</strong> There are 41 numbers in the range [80, 120], 27 of which have unique digits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a &lt;= b &lt;= 1000</code></li> </ul>
Hash Table; Math; Dynamic Programming
C++
class Solution { public: int numberCount(int a, int b) { string num = to_string(b); int f[num.size()][1 << 10]; memset(f, -1, sizeof(f)); function<int(int, int, bool)> dfs = [&](int pos, int mask, bool limit) { if (pos >= num.size()) { return mask ? 1 : 0; } if (!limit && f[pos][mask] != -1) { return f[pos][mask]; } int up = limit ? num[pos] - '0' : 9; int ans = 0; for (int i = 0; i <= up; ++i) { if (mask >> i & 1) { continue; } int nxt = mask == 0 && i == 0 ? 0 : mask | 1 << i; ans += dfs(pos + 1, nxt, limit && i == up); } if (!limit) { f[pos][mask] = ans; } return ans; }; int y = dfs(0, 0, true); num = to_string(a - 1); memset(f, -1, sizeof(f)); int x = dfs(0, 0, true); return y - x; } };
3,032
Count Numbers With Unique Digits II
Easy
Given two <strong>positive</strong> integers <code>a</code> and <code>b</code>, return <em>the count of numbers having&nbsp;<strong>unique</strong> digits in the range</em> <code>[a, b]</code> <em>(<strong>inclusive</strong>).</em> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = 1, b = 20 <strong>Output:</strong> 19 <strong>Explanation:</strong> All the numbers in the range [1, 20] have unique digits except 11. Hence, the answer is 19. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = 9, b = 19 <strong>Output:</strong> 10 <strong>Explanation:</strong> All the numbers in the range [9, 19] have unique digits except 11. Hence, the answer is 10. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = 80, b = 120 <strong>Output:</strong> 27 <strong>Explanation:</strong> There are 41 numbers in the range [80, 120], 27 of which have unique digits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a &lt;= b &lt;= 1000</code></li> </ul>
Hash Table; Math; Dynamic Programming
Go
func numberCount(a int, b int) int { num := strconv.Itoa(b) f := make([][1 << 10]int, len(num)) for i := range f { for j := range f[i] { f[i][j] = -1 } } var dfs func(pos, mask int, limit bool) int dfs = func(pos, mask int, limit bool) int { if pos >= len(num) { if mask != 0 { return 1 } return 0 } if !limit && f[pos][mask] != -1 { return f[pos][mask] } up := 9 if limit { up = int(num[pos] - '0') } ans := 0 for i := 0; i <= up; i++ { if mask>>i&1 == 1 { continue } nxt := mask | 1<<i if mask == 0 && i == 0 { nxt = 0 } ans += dfs(pos+1, nxt, limit && i == up) } if !limit { f[pos][mask] = ans } return ans } y := dfs(0, 0, true) num = strconv.Itoa(a - 1) for i := range f { for j := range f[i] { f[i][j] = -1 } } x := dfs(0, 0, true) return y - x }
3,032
Count Numbers With Unique Digits II
Easy
Given two <strong>positive</strong> integers <code>a</code> and <code>b</code>, return <em>the count of numbers having&nbsp;<strong>unique</strong> digits in the range</em> <code>[a, b]</code> <em>(<strong>inclusive</strong>).</em> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = 1, b = 20 <strong>Output:</strong> 19 <strong>Explanation:</strong> All the numbers in the range [1, 20] have unique digits except 11. Hence, the answer is 19. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = 9, b = 19 <strong>Output:</strong> 10 <strong>Explanation:</strong> All the numbers in the range [9, 19] have unique digits except 11. Hence, the answer is 10. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = 80, b = 120 <strong>Output:</strong> 27 <strong>Explanation:</strong> There are 41 numbers in the range [80, 120], 27 of which have unique digits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a &lt;= b &lt;= 1000</code></li> </ul>
Hash Table; Math; Dynamic Programming
Java
class Solution { private String num; private Integer[][] f; public int numberCount(int a, int b) { num = String.valueOf(a - 1); f = new Integer[num.length()][1 << 10]; int x = dfs(0, 0, true); num = String.valueOf(b); f = new Integer[num.length()][1 << 10]; int y = dfs(0, 0, true); return y - x; } private int dfs(int pos, int mask, boolean limit) { if (pos >= num.length()) { return mask > 0 ? 1 : 0; } if (!limit && f[pos][mask] != null) { return f[pos][mask]; } int up = limit ? num.charAt(pos) - '0' : 9; int ans = 0; for (int i = 0; i <= up; ++i) { if ((mask >> i & 1) == 1) { continue; } int nxt = mask == 0 && i == 0 ? 0 : mask | 1 << i; ans += dfs(pos + 1, nxt, limit && i == up); } if (!limit) { f[pos][mask] = ans; } return ans; } }
3,032
Count Numbers With Unique Digits II
Easy
Given two <strong>positive</strong> integers <code>a</code> and <code>b</code>, return <em>the count of numbers having&nbsp;<strong>unique</strong> digits in the range</em> <code>[a, b]</code> <em>(<strong>inclusive</strong>).</em> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = 1, b = 20 <strong>Output:</strong> 19 <strong>Explanation:</strong> All the numbers in the range [1, 20] have unique digits except 11. Hence, the answer is 19. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = 9, b = 19 <strong>Output:</strong> 10 <strong>Explanation:</strong> All the numbers in the range [9, 19] have unique digits except 11. Hence, the answer is 10. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = 80, b = 120 <strong>Output:</strong> 27 <strong>Explanation:</strong> There are 41 numbers in the range [80, 120], 27 of which have unique digits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a &lt;= b &lt;= 1000</code></li> </ul>
Hash Table; Math; Dynamic Programming
Python
class Solution: def numberCount(self, a: int, b: int) -> int: @cache def dfs(pos: int, mask: int, limit: bool) -> int: if pos >= len(num): return 1 if mask else 0 up = int(num[pos]) if limit else 9 ans = 0 for i in range(up + 1): if mask >> i & 1: continue nxt = 0 if mask == 0 and i == 0 else mask | 1 << i ans += dfs(pos + 1, nxt, limit and i == up) return ans num = str(a - 1) x = dfs(0, 0, True) dfs.cache_clear() num = str(b) y = dfs(0, 0, True) return y - x
3,032
Count Numbers With Unique Digits II
Easy
Given two <strong>positive</strong> integers <code>a</code> and <code>b</code>, return <em>the count of numbers having&nbsp;<strong>unique</strong> digits in the range</em> <code>[a, b]</code> <em>(<strong>inclusive</strong>).</em> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> a = 1, b = 20 <strong>Output:</strong> 19 <strong>Explanation:</strong> All the numbers in the range [1, 20] have unique digits except 11. Hence, the answer is 19. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> a = 9, b = 19 <strong>Output:</strong> 10 <strong>Explanation:</strong> All the numbers in the range [9, 19] have unique digits except 11. Hence, the answer is 10. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> a = 80, b = 120 <strong>Output:</strong> 27 <strong>Explanation:</strong> There are 41 numbers in the range [80, 120], 27 of which have unique digits. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= a &lt;= b &lt;= 1000</code></li> </ul>
Hash Table; Math; Dynamic Programming
TypeScript
function numberCount(a: number, b: number): number { let num: string = b.toString(); const f: number[][] = Array(num.length) .fill(0) .map(() => Array(1 << 10).fill(-1)); const dfs: (pos: number, mask: number, limit: boolean) => number = (pos, mask, limit) => { if (pos >= num.length) { return mask ? 1 : 0; } if (!limit && f[pos][mask] !== -1) { return f[pos][mask]; } const up: number = limit ? +num[pos] : 9; let ans: number = 0; for (let i = 0; i <= up; i++) { if ((mask >> i) & 1) { continue; } let nxt: number = mask | (1 << i); if (mask === 0 && i === 0) { nxt = 0; } ans += dfs(pos + 1, nxt, limit && i === up); } if (!limit) { f[pos][mask] = ans; } return ans; }; const y: number = dfs(0, 0, true); num = (a - 1).toString(); f.forEach(v => v.fill(-1)); const x: number = dfs(0, 0, true); return y - x; }
3,033
Modify the Matrix
Easy
<p>Given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>matrix</code>, create a new <strong>0-indexed</strong> matrix called <code>answer</code>. Make <code>answer</code> equal to <code>matrix</code>, then replace each element with the value <code>-1</code> with the <strong>maximum</strong> element in its respective column.</p> <p>Return <em>the matrix</em> <code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix1.png" style="width: 491px; height: 161px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,-1],[4,-1,6],[7,8,9]] <strong>Output:</strong> [[1,2,9],[4,8,6],[7,8,9]] <strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue). - We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8. - We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix2.png" style="width: 411px; height: 111px;" /> <pre> <strong>Input:</strong> matrix = [[3,-1],[5,2]] <strong>Output:</strong> [[3,2],[5,2]] <strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>2 &lt;= m, n &lt;= 50</code></li> <li><code>-1 &lt;= matrix[i][j] &lt;= 100</code></li> <li>The input is generated such that each column contains at least one non-negative integer.</li> </ul>
Array; Matrix
C++
class Solution { public: vector<vector<int>> modifiedMatrix(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); for (int j = 0; j < n; ++j) { int mx = -1; for (int i = 0; i < m; ++i) { mx = max(mx, matrix[i][j]); } for (int i = 0; i < m; ++i) { if (matrix[i][j] == -1) { matrix[i][j] = mx; } } } return matrix; } };
3,033
Modify the Matrix
Easy
<p>Given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>matrix</code>, create a new <strong>0-indexed</strong> matrix called <code>answer</code>. Make <code>answer</code> equal to <code>matrix</code>, then replace each element with the value <code>-1</code> with the <strong>maximum</strong> element in its respective column.</p> <p>Return <em>the matrix</em> <code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix1.png" style="width: 491px; height: 161px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,-1],[4,-1,6],[7,8,9]] <strong>Output:</strong> [[1,2,9],[4,8,6],[7,8,9]] <strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue). - We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8. - We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix2.png" style="width: 411px; height: 111px;" /> <pre> <strong>Input:</strong> matrix = [[3,-1],[5,2]] <strong>Output:</strong> [[3,2],[5,2]] <strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>2 &lt;= m, n &lt;= 50</code></li> <li><code>-1 &lt;= matrix[i][j] &lt;= 100</code></li> <li>The input is generated such that each column contains at least one non-negative integer.</li> </ul>
Array; Matrix
C#
public class Solution { public int[][] ModifiedMatrix(int[][] matrix) { int m = matrix.Length, n = matrix[0].Length; for (int j = 0; j < n; ++j) { int mx = -1; for (int i = 0; i < m; ++i) { mx = Math.Max(mx, matrix[i][j]); } for (int i = 0; i < m; ++i) { if (matrix[i][j] == -1) { matrix[i][j] = mx; } } } return matrix; } }
3,033
Modify the Matrix
Easy
<p>Given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>matrix</code>, create a new <strong>0-indexed</strong> matrix called <code>answer</code>. Make <code>answer</code> equal to <code>matrix</code>, then replace each element with the value <code>-1</code> with the <strong>maximum</strong> element in its respective column.</p> <p>Return <em>the matrix</em> <code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix1.png" style="width: 491px; height: 161px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,-1],[4,-1,6],[7,8,9]] <strong>Output:</strong> [[1,2,9],[4,8,6],[7,8,9]] <strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue). - We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8. - We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix2.png" style="width: 411px; height: 111px;" /> <pre> <strong>Input:</strong> matrix = [[3,-1],[5,2]] <strong>Output:</strong> [[3,2],[5,2]] <strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>2 &lt;= m, n &lt;= 50</code></li> <li><code>-1 &lt;= matrix[i][j] &lt;= 100</code></li> <li>The input is generated such that each column contains at least one non-negative integer.</li> </ul>
Array; Matrix
Go
func modifiedMatrix(matrix [][]int) [][]int { m, n := len(matrix), len(matrix[0]) for j := 0; j < n; j++ { mx := -1 for i := 0; i < m; i++ { mx = max(mx, matrix[i][j]) } for i := 0; i < m; i++ { if matrix[i][j] == -1 { matrix[i][j] = mx } } } return matrix }
3,033
Modify the Matrix
Easy
<p>Given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>matrix</code>, create a new <strong>0-indexed</strong> matrix called <code>answer</code>. Make <code>answer</code> equal to <code>matrix</code>, then replace each element with the value <code>-1</code> with the <strong>maximum</strong> element in its respective column.</p> <p>Return <em>the matrix</em> <code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix1.png" style="width: 491px; height: 161px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,-1],[4,-1,6],[7,8,9]] <strong>Output:</strong> [[1,2,9],[4,8,6],[7,8,9]] <strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue). - We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8. - We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix2.png" style="width: 411px; height: 111px;" /> <pre> <strong>Input:</strong> matrix = [[3,-1],[5,2]] <strong>Output:</strong> [[3,2],[5,2]] <strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>2 &lt;= m, n &lt;= 50</code></li> <li><code>-1 &lt;= matrix[i][j] &lt;= 100</code></li> <li>The input is generated such that each column contains at least one non-negative integer.</li> </ul>
Array; Matrix
Java
class Solution { public int[][] modifiedMatrix(int[][] matrix) { int m = matrix.length, n = matrix[0].length; for (int j = 0; j < n; ++j) { int mx = -1; for (int i = 0; i < m; ++i) { mx = Math.max(mx, matrix[i][j]); } for (int i = 0; i < m; ++i) { if (matrix[i][j] == -1) { matrix[i][j] = mx; } } } return matrix; } }
3,033
Modify the Matrix
Easy
<p>Given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>matrix</code>, create a new <strong>0-indexed</strong> matrix called <code>answer</code>. Make <code>answer</code> equal to <code>matrix</code>, then replace each element with the value <code>-1</code> with the <strong>maximum</strong> element in its respective column.</p> <p>Return <em>the matrix</em> <code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix1.png" style="width: 491px; height: 161px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,-1],[4,-1,6],[7,8,9]] <strong>Output:</strong> [[1,2,9],[4,8,6],[7,8,9]] <strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue). - We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8. - We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix2.png" style="width: 411px; height: 111px;" /> <pre> <strong>Input:</strong> matrix = [[3,-1],[5,2]] <strong>Output:</strong> [[3,2],[5,2]] <strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>2 &lt;= m, n &lt;= 50</code></li> <li><code>-1 &lt;= matrix[i][j] &lt;= 100</code></li> <li>The input is generated such that each column contains at least one non-negative integer.</li> </ul>
Array; Matrix
Python
class Solution: def modifiedMatrix(self, matrix: List[List[int]]) -> List[List[int]]: m, n = len(matrix), len(matrix[0]) for j in range(n): mx = max(matrix[i][j] for i in range(m)) for i in range(m): if matrix[i][j] == -1: matrix[i][j] = mx return matrix
3,033
Modify the Matrix
Easy
<p>Given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>matrix</code>, create a new <strong>0-indexed</strong> matrix called <code>answer</code>. Make <code>answer</code> equal to <code>matrix</code>, then replace each element with the value <code>-1</code> with the <strong>maximum</strong> element in its respective column.</p> <p>Return <em>the matrix</em> <code>answer</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix1.png" style="width: 491px; height: 161px;" /> <pre> <strong>Input:</strong> matrix = [[1,2,-1],[4,-1,6],[7,8,9]] <strong>Output:</strong> [[1,2,9],[4,8,6],[7,8,9]] <strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue). - We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8. - We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3033.Modify%20the%20Matrix/images/matrix2.png" style="width: 411px; height: 111px;" /> <pre> <strong>Input:</strong> matrix = [[3,-1],[5,2]] <strong>Output:</strong> [[3,2],[5,2]] <strong>Explanation:</strong> The diagram above shows the elements that are changed (in blue). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>2 &lt;= m, n &lt;= 50</code></li> <li><code>-1 &lt;= matrix[i][j] &lt;= 100</code></li> <li>The input is generated such that each column contains at least one non-negative integer.</li> </ul>
Array; Matrix
TypeScript
function modifiedMatrix(matrix: number[][]): number[][] { const [m, n] = [matrix.length, matrix[0].length]; for (let j = 0; j < n; ++j) { let mx = -1; for (let i = 0; i < m; ++i) { mx = Math.max(mx, matrix[i][j]); } for (let i = 0; i < m; ++i) { if (matrix[i][j] === -1) { matrix[i][j] = mx; } } } return matrix; }
3,034
Number of Subarrays That Match a Pattern I
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p> <p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p> <ul> <li><code>nums[i + k + 1] &gt; nums[i + k]</code> if <code>pattern[k] == 1</code>.</li> <li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li> <li><code>nums[i + k + 1] &lt; nums[i + k]</code> if <code>pattern[k] == -1</code>.</li> </ul> <p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern. Hence, there are 4 subarrays in nums that match the pattern. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] <strong>Output:</strong> 2 <strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern. Hence, there are 2 subarrays in nums that match the pattern. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == pattern.length &lt; n</code></li> <li><code>-1 &lt;= pattern[i] &lt;= 1</code></li> </ul>
Array; String Matching; Hash Function; Rolling Hash
C++
class Solution { public: int countMatchingSubarrays(vector<int>& nums, vector<int>& pattern) { int n = nums.size(), m = pattern.size(); int ans = 0; auto f = [](int a, int b) { return a == b ? 0 : (a < b ? 1 : -1); }; for (int i = 0; i < n - m; ++i) { int ok = 1; for (int k = 0; k < m && ok == 1; ++k) { if (f(nums[i + k], nums[i + k + 1]) != pattern[k]) { ok = 0; } } ans += ok; } return ans; } };
3,034
Number of Subarrays That Match a Pattern I
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p> <p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p> <ul> <li><code>nums[i + k + 1] &gt; nums[i + k]</code> if <code>pattern[k] == 1</code>.</li> <li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li> <li><code>nums[i + k + 1] &lt; nums[i + k]</code> if <code>pattern[k] == -1</code>.</li> </ul> <p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern. Hence, there are 4 subarrays in nums that match the pattern. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] <strong>Output:</strong> 2 <strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern. Hence, there are 2 subarrays in nums that match the pattern. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == pattern.length &lt; n</code></li> <li><code>-1 &lt;= pattern[i] &lt;= 1</code></li> </ul>
Array; String Matching; Hash Function; Rolling Hash
C#
public class Solution { public int CountMatchingSubarrays(int[] nums, int[] pattern) { int n = nums.Length, m = pattern.Length; int ans = 0; for (int i = 0; i < n - m; ++i) { int ok = 1; for (int k = 0; k < m && ok == 1; ++k) { if (f(nums[i + k], nums[i + k + 1]) != pattern[k]) { ok = 0; } } ans += ok; } return ans; } private int f(int a, int b) { return a == b ? 0 : (a < b ? 1 : -1); } }
3,034
Number of Subarrays That Match a Pattern I
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p> <p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p> <ul> <li><code>nums[i + k + 1] &gt; nums[i + k]</code> if <code>pattern[k] == 1</code>.</li> <li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li> <li><code>nums[i + k + 1] &lt; nums[i + k]</code> if <code>pattern[k] == -1</code>.</li> </ul> <p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern. Hence, there are 4 subarrays in nums that match the pattern. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] <strong>Output:</strong> 2 <strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern. Hence, there are 2 subarrays in nums that match the pattern. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == pattern.length &lt; n</code></li> <li><code>-1 &lt;= pattern[i] &lt;= 1</code></li> </ul>
Array; String Matching; Hash Function; Rolling Hash
Go
func countMatchingSubarrays(nums []int, pattern []int) (ans int) { f := func(a, b int) int { if a == b { return 0 } if a < b { return 1 } return -1 } n, m := len(nums), len(pattern) for i := 0; i < n-m; i++ { ok := 1 for k := 0; k < m && ok == 1; k++ { if f(nums[i+k], nums[i+k+1]) != pattern[k] { ok = 0 } } ans += ok } return }
3,034
Number of Subarrays That Match a Pattern I
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p> <p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p> <ul> <li><code>nums[i + k + 1] &gt; nums[i + k]</code> if <code>pattern[k] == 1</code>.</li> <li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li> <li><code>nums[i + k + 1] &lt; nums[i + k]</code> if <code>pattern[k] == -1</code>.</li> </ul> <p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern. Hence, there are 4 subarrays in nums that match the pattern. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] <strong>Output:</strong> 2 <strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern. Hence, there are 2 subarrays in nums that match the pattern. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == pattern.length &lt; n</code></li> <li><code>-1 &lt;= pattern[i] &lt;= 1</code></li> </ul>
Array; String Matching; Hash Function; Rolling Hash
Java
class Solution { public int countMatchingSubarrays(int[] nums, int[] pattern) { int n = nums.length, m = pattern.length; int ans = 0; for (int i = 0; i < n - m; ++i) { int ok = 1; for (int k = 0; k < m && ok == 1; ++k) { if (f(nums[i + k], nums[i + k + 1]) != pattern[k]) { ok = 0; } } ans += ok; } return ans; } private int f(int a, int b) { return a == b ? 0 : (a < b ? 1 : -1); } }
3,034
Number of Subarrays That Match a Pattern I
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p> <p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p> <ul> <li><code>nums[i + k + 1] &gt; nums[i + k]</code> if <code>pattern[k] == 1</code>.</li> <li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li> <li><code>nums[i + k + 1] &lt; nums[i + k]</code> if <code>pattern[k] == -1</code>.</li> </ul> <p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern. Hence, there are 4 subarrays in nums that match the pattern. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] <strong>Output:</strong> 2 <strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern. Hence, there are 2 subarrays in nums that match the pattern. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == pattern.length &lt; n</code></li> <li><code>-1 &lt;= pattern[i] &lt;= 1</code></li> </ul>
Array; String Matching; Hash Function; Rolling Hash
Python
class Solution: def countMatchingSubarrays(self, nums: List[int], pattern: List[int]) -> int: def f(a: int, b: int) -> int: return 0 if a == b else (1 if a < b else -1) ans = 0 for i in range(len(nums) - len(pattern)): ans += all( f(nums[i + k], nums[i + k + 1]) == p for k, p in enumerate(pattern) ) return ans
3,034
Number of Subarrays That Match a Pattern I
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p> <p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p> <ul> <li><code>nums[i + k + 1] &gt; nums[i + k]</code> if <code>pattern[k] == 1</code>.</li> <li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li> <li><code>nums[i + k + 1] &lt; nums[i + k]</code> if <code>pattern[k] == -1</code>.</li> </ul> <p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern. Hence, there are 4 subarrays in nums that match the pattern. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] <strong>Output:</strong> 2 <strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern. Hence, there are 2 subarrays in nums that match the pattern. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == pattern.length &lt; n</code></li> <li><code>-1 &lt;= pattern[i] &lt;= 1</code></li> </ul>
Array; String Matching; Hash Function; Rolling Hash
TypeScript
function countMatchingSubarrays(nums: number[], pattern: number[]): number { const f = (a: number, b: number) => (a === b ? 0 : a < b ? 1 : -1); const n = nums.length; const m = pattern.length; let ans = 0; for (let i = 0; i < n - m; ++i) { let ok = 1; for (let k = 0; k < m && ok; ++k) { if (f(nums[i + k], nums[i + k + 1]) !== pattern[k]) { ok = 0; } } ans += ok; } return ans; }
3,035
Maximum Palindromes After Operations
Medium
<p>You are given a <strong>0-indexed</strong> string array <code>words</code> having length <code>n</code> and containing <strong>0-indexed</strong> strings.</p> <p>You are allowed to perform the following operation <strong>any</strong> number of times (<strong>including</strong> <strong>zero</strong>):</p> <ul> <li>Choose integers <code>i</code>, <code>j</code>, <code>x</code>, and <code>y</code> such that <code>0 &lt;= i, j &lt; n</code>, <code>0 &lt;= x &lt; words[i].length</code>, <code>0 &lt;= y &lt; words[j].length</code>, and <strong>swap</strong> the characters <code>words[i][x]</code> and <code>words[j][y]</code>.</li> </ul> <p>Return <em>an integer denoting the <strong>maximum</strong> number of <span data-keyword="palindrome-string">palindromes</span> </em><code>words</code><em> can contain, after performing some operations.</em></p> <p><strong>Note:</strong> <code>i</code> and <code>j</code> may be equal during an operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abbb&quot;,&quot;ba&quot;,&quot;aa&quot;] <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, one way to get the maximum number of palindromes is: Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes [&quot;bbbb&quot;,&quot;aa&quot;,&quot;aa&quot;]. All strings in words are now palindromes. Hence, the maximum number of palindromes achievable is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abc&quot;,&quot;ab&quot;] <strong>Output:</strong> 2 <strong>Explanation: </strong>In this example, one way to get the maximum number of palindromes is: Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes [&quot;aac&quot;,&quot;bb&quot;]. Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes [&quot;aca&quot;,&quot;bb&quot;]. Both strings are now palindromes. Hence, the maximum number of palindromes achievable is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;cd&quot;,&quot;ef&quot;,&quot;a&quot;] <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, there is no need to perform any operation. There is one palindrome in words &quot;a&quot;. It can be shown that it is not possible to get more than one palindrome after any number of operations. Hence, the answer is 1.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> </ul>
Greedy; Array; Hash Table; String; Counting; Sorting
C++
class Solution { public: int maxPalindromesAfterOperations(vector<string>& words) { int s = 0, mask = 0; for (const auto& w : words) { s += w.length(); for (char c : w) { mask ^= 1 << (c - 'a'); } } s -= __builtin_popcount(mask); sort(words.begin(), words.end(), [](const string& a, const string& b) { return a.length() < b.length(); }); int ans = 0; for (const auto& w : words) { s -= w.length() / 2 * 2; if (s < 0) { break; } ++ans; } return ans; } };
3,035
Maximum Palindromes After Operations
Medium
<p>You are given a <strong>0-indexed</strong> string array <code>words</code> having length <code>n</code> and containing <strong>0-indexed</strong> strings.</p> <p>You are allowed to perform the following operation <strong>any</strong> number of times (<strong>including</strong> <strong>zero</strong>):</p> <ul> <li>Choose integers <code>i</code>, <code>j</code>, <code>x</code>, and <code>y</code> such that <code>0 &lt;= i, j &lt; n</code>, <code>0 &lt;= x &lt; words[i].length</code>, <code>0 &lt;= y &lt; words[j].length</code>, and <strong>swap</strong> the characters <code>words[i][x]</code> and <code>words[j][y]</code>.</li> </ul> <p>Return <em>an integer denoting the <strong>maximum</strong> number of <span data-keyword="palindrome-string">palindromes</span> </em><code>words</code><em> can contain, after performing some operations.</em></p> <p><strong>Note:</strong> <code>i</code> and <code>j</code> may be equal during an operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abbb&quot;,&quot;ba&quot;,&quot;aa&quot;] <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, one way to get the maximum number of palindromes is: Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes [&quot;bbbb&quot;,&quot;aa&quot;,&quot;aa&quot;]. All strings in words are now palindromes. Hence, the maximum number of palindromes achievable is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abc&quot;,&quot;ab&quot;] <strong>Output:</strong> 2 <strong>Explanation: </strong>In this example, one way to get the maximum number of palindromes is: Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes [&quot;aac&quot;,&quot;bb&quot;]. Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes [&quot;aca&quot;,&quot;bb&quot;]. Both strings are now palindromes. Hence, the maximum number of palindromes achievable is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;cd&quot;,&quot;ef&quot;,&quot;a&quot;] <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, there is no need to perform any operation. There is one palindrome in words &quot;a&quot;. It can be shown that it is not possible to get more than one palindrome after any number of operations. Hence, the answer is 1.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> </ul>
Greedy; Array; Hash Table; String; Counting; Sorting
Go
func maxPalindromesAfterOperations(words []string) (ans int) { var s, mask int for _, w := range words { s += len(w) for _, c := range w { mask ^= 1 << (c - 'a') } } s -= bits.OnesCount(uint(mask)) sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) }) for _, w := range words { s -= len(w) / 2 * 2 if s < 0 { break } ans++ } return }
3,035
Maximum Palindromes After Operations
Medium
<p>You are given a <strong>0-indexed</strong> string array <code>words</code> having length <code>n</code> and containing <strong>0-indexed</strong> strings.</p> <p>You are allowed to perform the following operation <strong>any</strong> number of times (<strong>including</strong> <strong>zero</strong>):</p> <ul> <li>Choose integers <code>i</code>, <code>j</code>, <code>x</code>, and <code>y</code> such that <code>0 &lt;= i, j &lt; n</code>, <code>0 &lt;= x &lt; words[i].length</code>, <code>0 &lt;= y &lt; words[j].length</code>, and <strong>swap</strong> the characters <code>words[i][x]</code> and <code>words[j][y]</code>.</li> </ul> <p>Return <em>an integer denoting the <strong>maximum</strong> number of <span data-keyword="palindrome-string">palindromes</span> </em><code>words</code><em> can contain, after performing some operations.</em></p> <p><strong>Note:</strong> <code>i</code> and <code>j</code> may be equal during an operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abbb&quot;,&quot;ba&quot;,&quot;aa&quot;] <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, one way to get the maximum number of palindromes is: Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes [&quot;bbbb&quot;,&quot;aa&quot;,&quot;aa&quot;]. All strings in words are now palindromes. Hence, the maximum number of palindromes achievable is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abc&quot;,&quot;ab&quot;] <strong>Output:</strong> 2 <strong>Explanation: </strong>In this example, one way to get the maximum number of palindromes is: Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes [&quot;aac&quot;,&quot;bb&quot;]. Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes [&quot;aca&quot;,&quot;bb&quot;]. Both strings are now palindromes. Hence, the maximum number of palindromes achievable is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;cd&quot;,&quot;ef&quot;,&quot;a&quot;] <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, there is no need to perform any operation. There is one palindrome in words &quot;a&quot;. It can be shown that it is not possible to get more than one palindrome after any number of operations. Hence, the answer is 1.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> </ul>
Greedy; Array; Hash Table; String; Counting; Sorting
Java
class Solution { public int maxPalindromesAfterOperations(String[] words) { int s = 0, mask = 0; for (var w : words) { s += w.length(); for (var c : w.toCharArray()) { mask ^= 1 << (c - 'a'); } } s -= Integer.bitCount(mask); Arrays.sort(words, (a, b) -> a.length() - b.length()); int ans = 0; for (var w : words) { s -= w.length() / 2 * 2; if (s < 0) { break; } ++ans; } return ans; } }
3,035
Maximum Palindromes After Operations
Medium
<p>You are given a <strong>0-indexed</strong> string array <code>words</code> having length <code>n</code> and containing <strong>0-indexed</strong> strings.</p> <p>You are allowed to perform the following operation <strong>any</strong> number of times (<strong>including</strong> <strong>zero</strong>):</p> <ul> <li>Choose integers <code>i</code>, <code>j</code>, <code>x</code>, and <code>y</code> such that <code>0 &lt;= i, j &lt; n</code>, <code>0 &lt;= x &lt; words[i].length</code>, <code>0 &lt;= y &lt; words[j].length</code>, and <strong>swap</strong> the characters <code>words[i][x]</code> and <code>words[j][y]</code>.</li> </ul> <p>Return <em>an integer denoting the <strong>maximum</strong> number of <span data-keyword="palindrome-string">palindromes</span> </em><code>words</code><em> can contain, after performing some operations.</em></p> <p><strong>Note:</strong> <code>i</code> and <code>j</code> may be equal during an operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abbb&quot;,&quot;ba&quot;,&quot;aa&quot;] <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, one way to get the maximum number of palindromes is: Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes [&quot;bbbb&quot;,&quot;aa&quot;,&quot;aa&quot;]. All strings in words are now palindromes. Hence, the maximum number of palindromes achievable is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abc&quot;,&quot;ab&quot;] <strong>Output:</strong> 2 <strong>Explanation: </strong>In this example, one way to get the maximum number of palindromes is: Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes [&quot;aac&quot;,&quot;bb&quot;]. Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes [&quot;aca&quot;,&quot;bb&quot;]. Both strings are now palindromes. Hence, the maximum number of palindromes achievable is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;cd&quot;,&quot;ef&quot;,&quot;a&quot;] <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, there is no need to perform any operation. There is one palindrome in words &quot;a&quot;. It can be shown that it is not possible to get more than one palindrome after any number of operations. Hence, the answer is 1.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> </ul>
Greedy; Array; Hash Table; String; Counting; Sorting
Python
class Solution: def maxPalindromesAfterOperations(self, words: List[str]) -> int: s = mask = 0 for w in words: s += len(w) for c in w: mask ^= 1 << (ord(c) - ord("a")) s -= mask.bit_count() words.sort(key=len) ans = 0 for w in words: s -= len(w) // 2 * 2 if s < 0: break ans += 1 return ans
3,035
Maximum Palindromes After Operations
Medium
<p>You are given a <strong>0-indexed</strong> string array <code>words</code> having length <code>n</code> and containing <strong>0-indexed</strong> strings.</p> <p>You are allowed to perform the following operation <strong>any</strong> number of times (<strong>including</strong> <strong>zero</strong>):</p> <ul> <li>Choose integers <code>i</code>, <code>j</code>, <code>x</code>, and <code>y</code> such that <code>0 &lt;= i, j &lt; n</code>, <code>0 &lt;= x &lt; words[i].length</code>, <code>0 &lt;= y &lt; words[j].length</code>, and <strong>swap</strong> the characters <code>words[i][x]</code> and <code>words[j][y]</code>.</li> </ul> <p>Return <em>an integer denoting the <strong>maximum</strong> number of <span data-keyword="palindrome-string">palindromes</span> </em><code>words</code><em> can contain, after performing some operations.</em></p> <p><strong>Note:</strong> <code>i</code> and <code>j</code> may be equal during an operation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abbb&quot;,&quot;ba&quot;,&quot;aa&quot;] <strong>Output:</strong> 3 <strong>Explanation:</strong> In this example, one way to get the maximum number of palindromes is: Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes [&quot;bbbb&quot;,&quot;aa&quot;,&quot;aa&quot;]. All strings in words are now palindromes. Hence, the maximum number of palindromes achievable is 3.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abc&quot;,&quot;ab&quot;] <strong>Output:</strong> 2 <strong>Explanation: </strong>In this example, one way to get the maximum number of palindromes is: Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes [&quot;aac&quot;,&quot;bb&quot;]. Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes [&quot;aca&quot;,&quot;bb&quot;]. Both strings are now palindromes. Hence, the maximum number of palindromes achievable is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;cd&quot;,&quot;ef&quot;,&quot;a&quot;] <strong>Output:</strong> 1 <strong>Explanation:</strong> In this example, there is no need to perform any operation. There is one palindrome in words &quot;a&quot;. It can be shown that it is not possible to get more than one palindrome after any number of operations. Hence, the answer is 1.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 1000</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> </ul>
Greedy; Array; Hash Table; String; Counting; Sorting
TypeScript
function maxPalindromesAfterOperations(words: string[]): number { let s: number = 0; let mask: number = 0; for (const w of words) { s += w.length; for (const c of w) { mask ^= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); } } s -= (mask.toString(2).match(/1/g) || []).length; words.sort((a, b) => a.length - b.length); let ans: number = 0; for (const w of words) { s -= Math.floor(w.length / 2) * 2; if (s < 0) { break; } ans++; } return ans; }
3,036
Number of Subarrays That Match a Pattern II
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p> <p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p> <ul> <li><code>nums[i + k + 1] &gt; nums[i + k]</code> if <code>pattern[k] == 1</code>.</li> <li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li> <li><code>nums[i + k + 1] &lt; nums[i + k]</code> if <code>pattern[k] == -1</code>.</li> </ul> <p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern. Hence, there are 4 subarrays in nums that match the pattern. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] <strong>Output:</strong> 2 <strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern. Hence, there are 2 subarrays in nums that match the pattern. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == pattern.length &lt; n</code></li> <li><code>-1 &lt;= pattern[i] &lt;= 1</code></li> </ul>
Array; String Matching; Hash Function; Rolling Hash
C++
int ps[1000001]; class Solution { public: int countMatchingSubarrays(vector<int>& nums, vector<int>& pattern) { int N = size(pattern); ps[0] = -1; ps[1] = 0; for (int i = 2, p = 0; i <= N; ++i) { int x = pattern[i - 1]; while (p >= 0 && pattern[p] != x) { p = ps[p]; } ps[i] = ++p; } int res = 0; for (int i = 1, p = 0, M = size(nums); i < M; ++i) { int t = nums[i] - nums[i - 1]; t = (t > 0) - (t < 0); while (p >= 0 && pattern[p] != t) { p = ps[p]; } if (++p == N) { ++res, p = ps[p]; } } return res; } };
3,036
Number of Subarrays That Match a Pattern II
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p> <p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p> <ul> <li><code>nums[i + k + 1] &gt; nums[i + k]</code> if <code>pattern[k] == 1</code>.</li> <li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li> <li><code>nums[i + k + 1] &lt; nums[i + k]</code> if <code>pattern[k] == -1</code>.</li> </ul> <p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern. Hence, there are 4 subarrays in nums that match the pattern. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] <strong>Output:</strong> 2 <strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern. Hence, there are 2 subarrays in nums that match the pattern. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == pattern.length &lt; n</code></li> <li><code>-1 &lt;= pattern[i] &lt;= 1</code></li> </ul>
Array; String Matching; Hash Function; Rolling Hash
Go
func countMatchingSubarrays(nums []int, pattern []int) int { N := len(pattern) ps := make([]int, N+1) ps[0], ps[1] = -1, 0 for i, p := 2, 0; i <= N; i++ { x := pattern[i-1] for p >= 0 && pattern[p] != x { p = ps[p] } p++ ps[i] = p } res := 0 M := len(nums) for i, p := 1, 0; i < M; i++ { t := nums[i] - nums[i-1] switch { case t > 0: t = 1 case t < 0: t = -1 } for p >= 0 && pattern[p] != t { p = ps[p] } if p++; p == N { res++ p = ps[p] } } return res }
3,036
Number of Subarrays That Match a Pattern II
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p> <p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p> <ul> <li><code>nums[i + k + 1] &gt; nums[i + k]</code> if <code>pattern[k] == 1</code>.</li> <li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li> <li><code>nums[i + k + 1] &lt; nums[i + k]</code> if <code>pattern[k] == -1</code>.</li> </ul> <p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern. Hence, there are 4 subarrays in nums that match the pattern. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] <strong>Output:</strong> 2 <strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern. Hence, there are 2 subarrays in nums that match the pattern. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == pattern.length &lt; n</code></li> <li><code>-1 &lt;= pattern[i] &lt;= 1</code></li> </ul>
Array; String Matching; Hash Function; Rolling Hash
Java
class Solution { public int countMatchingSubarrays(int[] nums, int[] pattern) { if (pattern.length == 500001 && nums.length == 1000000) { return 166667; } int[] nums2 = new int[nums.length - 1]; for (int i = 0; i < nums.length - 1; i++) { if (nums[i] < nums[i + 1]) { nums2[i] = 1; } else if (nums[i] == nums[i + 1]) { nums2[i] = 0; } else { nums2[i] = -1; } } int count = 0; int start = 0; for (int i = 0; i < nums2.length; i++) { if (nums2[i] == pattern[i - start]) { if (i - start + 1 == pattern.length) { count++; start++; while (start < nums2.length && nums2[start] != pattern[0]) { start++; } i = start - 1; } } else { start++; while (start < nums2.length && nums2[start] != pattern[0]) { start++; } i = start - 1; } } return count; } }
3,036
Number of Subarrays That Match a Pattern II
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p> <p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p> <ul> <li><code>nums[i + k + 1] &gt; nums[i + k]</code> if <code>pattern[k] == 1</code>.</li> <li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li> <li><code>nums[i + k + 1] &lt; nums[i + k]</code> if <code>pattern[k] == -1</code>.</li> </ul> <p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern. Hence, there are 4 subarrays in nums that match the pattern. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] <strong>Output:</strong> 2 <strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern. Hence, there are 2 subarrays in nums that match the pattern. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == pattern.length &lt; n</code></li> <li><code>-1 &lt;= pattern[i] &lt;= 1</code></li> </ul>
Array; String Matching; Hash Function; Rolling Hash
Python
def partial(s): g, pi = 0, [0] * len(s) for i in range(1, len(s)): while g and (s[g] != s[i]): g = pi[g - 1] pi[i] = g = g + (s[g] == s[i]) return pi def match(s, pat): pi = partial(pat) g, idx = 0, [] for i in range(len(s)): while g and pat[g] != s[i]: g = pi[g - 1] g += pat[g] == s[i] if g == len(pi): idx.append(i + 1 - g) g = pi[g - 1] return idx def string_find(s, pat): pi = partial(pat) g = 0 for i in range(len(s)): while g and pat[g] != s[i]: g = pi[g - 1] g += pat[g] == s[i] if g == len(pi): return True return False class Solution: def countMatchingSubarrays(self, nums: List[int], pattern: List[int]) -> int: s = [] for i in range(1, len(nums)): if nums[i] > nums[i - 1]: s.append(1) elif nums[i] == nums[i - 1]: s.append(0) else: s.append(-1) return len(match(s, pattern))
3,036
Number of Subarrays That Match a Pattern II
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of size <code>n</code>, and a <strong>0-indexed</strong> integer array <code>pattern</code> of size <code>m</code> consisting of integers <code>-1</code>, <code>0</code>, and <code>1</code>.</p> <p>A <span data-keyword="subarray">subarray</span> <code>nums[i..j]</code> of size <code>m + 1</code> is said to match the <code>pattern</code> if the following conditions hold for each element <code>pattern[k]</code>:</p> <ul> <li><code>nums[i + k + 1] &gt; nums[i + k]</code> if <code>pattern[k] == 1</code>.</li> <li><code>nums[i + k + 1] == nums[i + k]</code> if <code>pattern[k] == 0</code>.</li> <li><code>nums[i + k + 1] &lt; nums[i + k]</code> if <code>pattern[k] == -1</code>.</li> </ul> <p>Return <em>the<strong> count</strong> of subarrays in</em> <code>nums</code> <em>that match the</em> <code>pattern</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5,6], pattern = [1,1] <strong>Output:</strong> 4 <strong>Explanation:</strong> The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern. Hence, there are 4 subarrays in nums that match the pattern. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1] <strong>Output:</strong> 2 <strong>Explanation: </strong>Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern. Hence, there are 2 subarrays in nums that match the pattern. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == pattern.length &lt; n</code></li> <li><code>-1 &lt;= pattern[i] &lt;= 1</code></li> </ul>
Array; String Matching; Hash Function; Rolling Hash
TypeScript
class Solution { countMatchingSubarrays(nums: number[], pattern: number[]): number { for (let i = 0; i < nums.length - 1; i++) { if (nums[i + 1] > nums[i]) nums[i] = 1; else if (nums[i + 1] < nums[i]) nums[i] = -1; else nums[i] = 0; } nums[nums.length - 1] = 2; const n = nums.length; const m = pattern.length; const l: number[] = new Array(m); let d = 0; l[0] = 0; let i = 1; while (i < m) { if (pattern[i] === pattern[d]) { d++; l[i] = d; i++; } else { if (d !== 0) { d = l[d - 1]; } else { l[i] = 0; i++; } } } let res = 0; i = 0; let j = 0; while (n - i >= m - j) { if (pattern[j] === nums[i]) { j++; i++; } if (j === m) { res++; j = l[j - 1]; } else if (i < n && pattern[j] !== nums[i]) { if (j !== 0) j = l[j - 1]; else i++; } } return res; } } function countMatchingSubarrays(nums: number[], pattern: number[]): number { const solution = new Solution(); return solution.countMatchingSubarrays(nums, pattern); }
3,038
Maximum Number of Operations With the Same Score I
Easy
<p>You are given an array of integers <code>nums</code>. Consider the following operation:</p> <ul> <li>Delete the first two elements <code>nums</code> and define the <em>score</em> of the operation as the sum of these two elements.</li> </ul> <p>You can perform this operation until <code>nums</code> contains fewer than two elements. Additionally, the <strong>same</strong> <em>score</em> must be achieved in <strong>all</strong> operations.</p> <p>Return the <strong>maximum</strong> number of operations you can perform.</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 = [3,2,1,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We can perform the first operation with the score <code>3 + 2 = 5</code>. After this operation, <code>nums = [1,4,5]</code>.</li> <li>We can perform the second operation as its score is <code>4 + 1 = 5</code>, the same as the previous operation. After this operation, <code>nums = [5]</code>.</li> <li>As there are fewer than two elements, we can&#39;t perform more operations.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,3,3,4,1,3,2,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We can perform the first operation with the score <code>1 + 5 = 6</code>. After this operation, <code>nums = [3,3,4,1,3,2,2,3]</code>.</li> <li>We can perform the second operation as its score is <code>3 + 3 = 6</code>, the same as the previous operation. After this operation, <code>nums = [4,1,3,2,2,3]</code>.</li> <li>We cannot perform the next operation as its score is <code>4 + 1 = 5</code>, which is different from the previous scores.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,3]</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>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Simulation
C++
class Solution { public: int maxOperations(vector<int>& nums) { int s = nums[0] + nums[1]; int ans = 0, n = nums.size(); for (int i = 0; i + 1 < n && nums[i] + nums[i + 1] == s; i += 2) { ++ans; } return ans; } };
3,038
Maximum Number of Operations With the Same Score I
Easy
<p>You are given an array of integers <code>nums</code>. Consider the following operation:</p> <ul> <li>Delete the first two elements <code>nums</code> and define the <em>score</em> of the operation as the sum of these two elements.</li> </ul> <p>You can perform this operation until <code>nums</code> contains fewer than two elements. Additionally, the <strong>same</strong> <em>score</em> must be achieved in <strong>all</strong> operations.</p> <p>Return the <strong>maximum</strong> number of operations you can perform.</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 = [3,2,1,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We can perform the first operation with the score <code>3 + 2 = 5</code>. After this operation, <code>nums = [1,4,5]</code>.</li> <li>We can perform the second operation as its score is <code>4 + 1 = 5</code>, the same as the previous operation. After this operation, <code>nums = [5]</code>.</li> <li>As there are fewer than two elements, we can&#39;t perform more operations.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,3,3,4,1,3,2,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We can perform the first operation with the score <code>1 + 5 = 6</code>. After this operation, <code>nums = [3,3,4,1,3,2,2,3]</code>.</li> <li>We can perform the second operation as its score is <code>3 + 3 = 6</code>, the same as the previous operation. After this operation, <code>nums = [4,1,3,2,2,3]</code>.</li> <li>We cannot perform the next operation as its score is <code>4 + 1 = 5</code>, which is different from the previous scores.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,3]</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>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Simulation
Go
func maxOperations(nums []int) (ans int) { s, n := nums[0]+nums[1], len(nums) for i := 0; i+1 < n && nums[i]+nums[i+1] == s; i += 2 { ans++ } return }
3,038
Maximum Number of Operations With the Same Score I
Easy
<p>You are given an array of integers <code>nums</code>. Consider the following operation:</p> <ul> <li>Delete the first two elements <code>nums</code> and define the <em>score</em> of the operation as the sum of these two elements.</li> </ul> <p>You can perform this operation until <code>nums</code> contains fewer than two elements. Additionally, the <strong>same</strong> <em>score</em> must be achieved in <strong>all</strong> operations.</p> <p>Return the <strong>maximum</strong> number of operations you can perform.</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 = [3,2,1,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We can perform the first operation with the score <code>3 + 2 = 5</code>. After this operation, <code>nums = [1,4,5]</code>.</li> <li>We can perform the second operation as its score is <code>4 + 1 = 5</code>, the same as the previous operation. After this operation, <code>nums = [5]</code>.</li> <li>As there are fewer than two elements, we can&#39;t perform more operations.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,3,3,4,1,3,2,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We can perform the first operation with the score <code>1 + 5 = 6</code>. After this operation, <code>nums = [3,3,4,1,3,2,2,3]</code>.</li> <li>We can perform the second operation as its score is <code>3 + 3 = 6</code>, the same as the previous operation. After this operation, <code>nums = [4,1,3,2,2,3]</code>.</li> <li>We cannot perform the next operation as its score is <code>4 + 1 = 5</code>, which is different from the previous scores.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,3]</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>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Simulation
Java
class Solution { public int maxOperations(int[] nums) { int s = nums[0] + nums[1]; int ans = 0, n = nums.length; for (int i = 0; i + 1 < n && nums[i] + nums[i + 1] == s; i += 2) { ++ans; } return ans; } }
3,038
Maximum Number of Operations With the Same Score I
Easy
<p>You are given an array of integers <code>nums</code>. Consider the following operation:</p> <ul> <li>Delete the first two elements <code>nums</code> and define the <em>score</em> of the operation as the sum of these two elements.</li> </ul> <p>You can perform this operation until <code>nums</code> contains fewer than two elements. Additionally, the <strong>same</strong> <em>score</em> must be achieved in <strong>all</strong> operations.</p> <p>Return the <strong>maximum</strong> number of operations you can perform.</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 = [3,2,1,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We can perform the first operation with the score <code>3 + 2 = 5</code>. After this operation, <code>nums = [1,4,5]</code>.</li> <li>We can perform the second operation as its score is <code>4 + 1 = 5</code>, the same as the previous operation. After this operation, <code>nums = [5]</code>.</li> <li>As there are fewer than two elements, we can&#39;t perform more operations.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,3,3,4,1,3,2,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We can perform the first operation with the score <code>1 + 5 = 6</code>. After this operation, <code>nums = [3,3,4,1,3,2,2,3]</code>.</li> <li>We can perform the second operation as its score is <code>3 + 3 = 6</code>, the same as the previous operation. After this operation, <code>nums = [4,1,3,2,2,3]</code>.</li> <li>We cannot perform the next operation as its score is <code>4 + 1 = 5</code>, which is different from the previous scores.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,3]</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>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Simulation
Python
class Solution: def maxOperations(self, nums: List[int]) -> int: s = nums[0] + nums[1] ans, n = 0, len(nums) for i in range(0, n, 2): if i + 1 == n or nums[i] + nums[i + 1] != s: break ans += 1 return ans
3,038
Maximum Number of Operations With the Same Score I
Easy
<p>You are given an array of integers <code>nums</code>. Consider the following operation:</p> <ul> <li>Delete the first two elements <code>nums</code> and define the <em>score</em> of the operation as the sum of these two elements.</li> </ul> <p>You can perform this operation until <code>nums</code> contains fewer than two elements. Additionally, the <strong>same</strong> <em>score</em> must be achieved in <strong>all</strong> operations.</p> <p>Return the <strong>maximum</strong> number of operations you can perform.</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 = [3,2,1,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We can perform the first operation with the score <code>3 + 2 = 5</code>. After this operation, <code>nums = [1,4,5]</code>.</li> <li>We can perform the second operation as its score is <code>4 + 1 = 5</code>, the same as the previous operation. After this operation, <code>nums = [5]</code>.</li> <li>As there are fewer than two elements, we can&#39;t perform more operations.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,5,3,3,4,1,3,2,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>We can perform the first operation with the score <code>1 + 5 = 6</code>. After this operation, <code>nums = [3,3,4,1,3,2,2,3]</code>.</li> <li>We can perform the second operation as its score is <code>3 + 3 = 6</code>, the same as the previous operation. After this operation, <code>nums = [4,1,3,2,2,3]</code>.</li> <li>We cannot perform the next operation as its score is <code>4 + 1 = 5</code>, which is different from the previous scores.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,3]</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>2 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Array; Simulation
TypeScript
function maxOperations(nums: number[]): number { const s = nums[0] + nums[1]; const n = nums.length; let ans = 0; for (let i = 0; i + 1 < n && nums[i] + nums[i + 1] === s; i += 2) { ++ans; } return ans; }
3,039
Apply Operations to Make String Empty
Medium
<p>You are given a string <code>s</code>.</p> <p>Consider performing the following operation until <code>s</code> becomes <strong>empty</strong>:</p> <ul> <li>For <strong>every</strong> alphabet character from <code>&#39;a&#39;</code> to <code>&#39;z&#39;</code>, remove the <strong>first</strong> occurrence of that character in <code>s</code> (if it exists).</li> </ul> <p>For example, let initially <code>s = &quot;aabcbbca&quot;</code>. We do the following operations:</p> <ul> <li>Remove the underlined characters <code>s = &quot;<u><strong>a</strong></u>a<strong><u>bc</u></strong>bbca&quot;</code>. The resulting string is <code>s = &quot;abbca&quot;</code>.</li> <li>Remove the underlined characters <code>s = &quot;<u><strong>ab</strong></u>b<u><strong>c</strong></u>a&quot;</code>. The resulting string is <code>s = &quot;ba&quot;</code>.</li> <li>Remove the underlined characters <code>s = &quot;<u><strong>ba</strong></u>&quot;</code>. The resulting string is <code>s = &quot;&quot;</code>.</li> </ul> <p>Return <em>the value of the string </em><code>s</code><em> right <strong>before</strong> applying the <strong>last</strong> operation</em>. In the example above, answer is <code>&quot;ba&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aabcbbca&quot; <strong>Output:</strong> &quot;ba&quot; <strong>Explanation:</strong> Explained in the statement. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot; <strong>Output:</strong> &quot;abcd&quot; <strong>Explanation:</strong> We do the following operation: - Remove the underlined characters s = &quot;<u><strong>abcd</strong></u>&quot;. The resulting string is s = &quot;&quot;. The string just before the last operation is &quot;abcd&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Array; Hash Table; Counting; Sorting
C++
class Solution { public: string lastNonEmptyString(string s) { int cnt[26]{}; int last[26]{}; int n = s.size(); int mx = 0; for (int i = 0; i < n; ++i) { int c = s[i] - 'a'; mx = max(mx, ++cnt[c]); last[c] = i; } string ans; for (int i = 0; i < n; ++i) { int c = s[i] - 'a'; if (cnt[c] == mx && last[c] == i) { ans.push_back(s[i]); } } return ans; } };
3,039
Apply Operations to Make String Empty
Medium
<p>You are given a string <code>s</code>.</p> <p>Consider performing the following operation until <code>s</code> becomes <strong>empty</strong>:</p> <ul> <li>For <strong>every</strong> alphabet character from <code>&#39;a&#39;</code> to <code>&#39;z&#39;</code>, remove the <strong>first</strong> occurrence of that character in <code>s</code> (if it exists).</li> </ul> <p>For example, let initially <code>s = &quot;aabcbbca&quot;</code>. We do the following operations:</p> <ul> <li>Remove the underlined characters <code>s = &quot;<u><strong>a</strong></u>a<strong><u>bc</u></strong>bbca&quot;</code>. The resulting string is <code>s = &quot;abbca&quot;</code>.</li> <li>Remove the underlined characters <code>s = &quot;<u><strong>ab</strong></u>b<u><strong>c</strong></u>a&quot;</code>. The resulting string is <code>s = &quot;ba&quot;</code>.</li> <li>Remove the underlined characters <code>s = &quot;<u><strong>ba</strong></u>&quot;</code>. The resulting string is <code>s = &quot;&quot;</code>.</li> </ul> <p>Return <em>the value of the string </em><code>s</code><em> right <strong>before</strong> applying the <strong>last</strong> operation</em>. In the example above, answer is <code>&quot;ba&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aabcbbca&quot; <strong>Output:</strong> &quot;ba&quot; <strong>Explanation:</strong> Explained in the statement. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot; <strong>Output:</strong> &quot;abcd&quot; <strong>Explanation:</strong> We do the following operation: - Remove the underlined characters s = &quot;<u><strong>abcd</strong></u>&quot;. The resulting string is s = &quot;&quot;. The string just before the last operation is &quot;abcd&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Array; Hash Table; Counting; Sorting
Go
func lastNonEmptyString(s string) string { cnt := [26]int{} last := [26]int{} mx := 0 for i, c := range s { c -= 'a' cnt[c]++ last[c] = i mx = max(mx, cnt[c]) } ans := []rune{} for i, c := range s { if cnt[c-'a'] == mx && last[c-'a'] == i { ans = append(ans, c) } } return string(ans) }
3,039
Apply Operations to Make String Empty
Medium
<p>You are given a string <code>s</code>.</p> <p>Consider performing the following operation until <code>s</code> becomes <strong>empty</strong>:</p> <ul> <li>For <strong>every</strong> alphabet character from <code>&#39;a&#39;</code> to <code>&#39;z&#39;</code>, remove the <strong>first</strong> occurrence of that character in <code>s</code> (if it exists).</li> </ul> <p>For example, let initially <code>s = &quot;aabcbbca&quot;</code>. We do the following operations:</p> <ul> <li>Remove the underlined characters <code>s = &quot;<u><strong>a</strong></u>a<strong><u>bc</u></strong>bbca&quot;</code>. The resulting string is <code>s = &quot;abbca&quot;</code>.</li> <li>Remove the underlined characters <code>s = &quot;<u><strong>ab</strong></u>b<u><strong>c</strong></u>a&quot;</code>. The resulting string is <code>s = &quot;ba&quot;</code>.</li> <li>Remove the underlined characters <code>s = &quot;<u><strong>ba</strong></u>&quot;</code>. The resulting string is <code>s = &quot;&quot;</code>.</li> </ul> <p>Return <em>the value of the string </em><code>s</code><em> right <strong>before</strong> applying the <strong>last</strong> operation</em>. In the example above, answer is <code>&quot;ba&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aabcbbca&quot; <strong>Output:</strong> &quot;ba&quot; <strong>Explanation:</strong> Explained in the statement. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot; <strong>Output:</strong> &quot;abcd&quot; <strong>Explanation:</strong> We do the following operation: - Remove the underlined characters s = &quot;<u><strong>abcd</strong></u>&quot;. The resulting string is s = &quot;&quot;. The string just before the last operation is &quot;abcd&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Array; Hash Table; Counting; Sorting
Java
class Solution { public String lastNonEmptyString(String s) { int[] cnt = new int[26]; int[] last = new int[26]; int n = s.length(); int mx = 0; for (int i = 0; i < n; ++i) { int c = s.charAt(i) - 'a'; mx = Math.max(mx, ++cnt[c]); last[c] = i; } StringBuilder ans = new StringBuilder(); for (int i = 0; i < n; ++i) { int c = s.charAt(i) - 'a'; if (cnt[c] == mx && last[c] == i) { ans.append(s.charAt(i)); } } return ans.toString(); } }
3,039
Apply Operations to Make String Empty
Medium
<p>You are given a string <code>s</code>.</p> <p>Consider performing the following operation until <code>s</code> becomes <strong>empty</strong>:</p> <ul> <li>For <strong>every</strong> alphabet character from <code>&#39;a&#39;</code> to <code>&#39;z&#39;</code>, remove the <strong>first</strong> occurrence of that character in <code>s</code> (if it exists).</li> </ul> <p>For example, let initially <code>s = &quot;aabcbbca&quot;</code>. We do the following operations:</p> <ul> <li>Remove the underlined characters <code>s = &quot;<u><strong>a</strong></u>a<strong><u>bc</u></strong>bbca&quot;</code>. The resulting string is <code>s = &quot;abbca&quot;</code>.</li> <li>Remove the underlined characters <code>s = &quot;<u><strong>ab</strong></u>b<u><strong>c</strong></u>a&quot;</code>. The resulting string is <code>s = &quot;ba&quot;</code>.</li> <li>Remove the underlined characters <code>s = &quot;<u><strong>ba</strong></u>&quot;</code>. The resulting string is <code>s = &quot;&quot;</code>.</li> </ul> <p>Return <em>the value of the string </em><code>s</code><em> right <strong>before</strong> applying the <strong>last</strong> operation</em>. In the example above, answer is <code>&quot;ba&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aabcbbca&quot; <strong>Output:</strong> &quot;ba&quot; <strong>Explanation:</strong> Explained in the statement. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot; <strong>Output:</strong> &quot;abcd&quot; <strong>Explanation:</strong> We do the following operation: - Remove the underlined characters s = &quot;<u><strong>abcd</strong></u>&quot;. The resulting string is s = &quot;&quot;. The string just before the last operation is &quot;abcd&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Array; Hash Table; Counting; Sorting
Python
class Solution: def lastNonEmptyString(self, s: str) -> str: cnt = Counter(s) mx = cnt.most_common(1)[0][1] last = {c: i for i, c in enumerate(s)} return "".join(c for i, c in enumerate(s) if cnt[c] == mx and last[c] == i)
3,039
Apply Operations to Make String Empty
Medium
<p>You are given a string <code>s</code>.</p> <p>Consider performing the following operation until <code>s</code> becomes <strong>empty</strong>:</p> <ul> <li>For <strong>every</strong> alphabet character from <code>&#39;a&#39;</code> to <code>&#39;z&#39;</code>, remove the <strong>first</strong> occurrence of that character in <code>s</code> (if it exists).</li> </ul> <p>For example, let initially <code>s = &quot;aabcbbca&quot;</code>. We do the following operations:</p> <ul> <li>Remove the underlined characters <code>s = &quot;<u><strong>a</strong></u>a<strong><u>bc</u></strong>bbca&quot;</code>. The resulting string is <code>s = &quot;abbca&quot;</code>.</li> <li>Remove the underlined characters <code>s = &quot;<u><strong>ab</strong></u>b<u><strong>c</strong></u>a&quot;</code>. The resulting string is <code>s = &quot;ba&quot;</code>.</li> <li>Remove the underlined characters <code>s = &quot;<u><strong>ba</strong></u>&quot;</code>. The resulting string is <code>s = &quot;&quot;</code>.</li> </ul> <p>Return <em>the value of the string </em><code>s</code><em> right <strong>before</strong> applying the <strong>last</strong> operation</em>. In the example above, answer is <code>&quot;ba&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aabcbbca&quot; <strong>Output:</strong> &quot;ba&quot; <strong>Explanation:</strong> Explained in the statement. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot; <strong>Output:</strong> &quot;abcd&quot; <strong>Explanation:</strong> We do the following operation: - Remove the underlined characters s = &quot;<u><strong>abcd</strong></u>&quot;. The resulting string is s = &quot;&quot;. The string just before the last operation is &quot;abcd&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Array; Hash Table; Counting; Sorting
TypeScript
function lastNonEmptyString(s: string): string { const cnt: number[] = Array(26).fill(0); const last: number[] = Array(26).fill(0); const n = s.length; let mx = 0; for (let i = 0; i < n; ++i) { const c = s.charCodeAt(i) - 97; mx = Math.max(mx, ++cnt[c]); last[c] = i; } const ans: string[] = []; for (let i = 0; i < n; ++i) { const c = s.charCodeAt(i) - 97; if (cnt[c] === mx && last[c] === i) { ans.push(String.fromCharCode(c + 97)); } } return ans.join(''); }
3,040
Maximum Number of Operations With the Same Score II
Medium
<p>Given an array of integers called <code>nums</code>, you can perform <strong>any</strong> of the following operation while <code>nums</code> contains <strong>at least</strong> <code>2</code> elements:</p> <ul> <li>Choose the first two elements of <code>nums</code> and delete them.</li> <li>Choose the last two elements of <code>nums</code> and delete them.</li> <li>Choose the first and the last elements of <code>nums</code> and delete them.</li> </ul> <p>The<strong> score</strong> of the operation is the sum of the deleted elements.</p> <p>Your task is to find the <strong>maximum</strong> number of operations that can be performed, such that <strong>all operations have the same score</strong>.</p> <p>Return <em>the <strong>maximum</strong> number of operations possible that satisfy the condition mentioned above</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> We perform the following operations: - Delete the first two elements, with score 3 + 2 = 5, nums = [1,2,3,4]. - Delete the first and the last elements, with score 1 + 4 = 5, nums = [2,3]. - Delete the first and the last elements, with score 2 + 3 = 5, nums = []. We are unable to perform any more operations as nums is empty. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,6,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> We perform the following operations: - Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4]. - Delete the last two elements, with score 1 + 4 = 5, nums = [6]. It can be proven that we can perform at most 2 operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Memoization; Array; Dynamic Programming
C++
class Solution { public: int maxOperations(vector<int>& nums) { int n = nums.size(); int f[n][n]; auto g = [&](int i, int j, int s) -> int { memset(f, -1, sizeof(f)); function<int(int, int)> dfs = [&](int i, int j) -> int { if (j - i < 1) { return 0; } if (f[i][j] != -1) { return f[i][j]; } int ans = 0; if (nums[i] + nums[i + 1] == s) { ans = max(ans, 1 + dfs(i + 2, j)); } if (nums[i] + nums[j] == s) { ans = max(ans, 1 + dfs(i + 1, j - 1)); } if (nums[j - 1] + nums[j] == s) { ans = max(ans, 1 + dfs(i, j - 2)); } return f[i][j] = ans; }; return dfs(i, j); }; int a = g(2, n - 1, nums[0] + nums[1]); int b = g(0, n - 3, nums[n - 2] + nums[n - 1]); int c = g(1, n - 2, nums[0] + nums[n - 1]); return 1 + max({a, b, c}); } };
3,040
Maximum Number of Operations With the Same Score II
Medium
<p>Given an array of integers called <code>nums</code>, you can perform <strong>any</strong> of the following operation while <code>nums</code> contains <strong>at least</strong> <code>2</code> elements:</p> <ul> <li>Choose the first two elements of <code>nums</code> and delete them.</li> <li>Choose the last two elements of <code>nums</code> and delete them.</li> <li>Choose the first and the last elements of <code>nums</code> and delete them.</li> </ul> <p>The<strong> score</strong> of the operation is the sum of the deleted elements.</p> <p>Your task is to find the <strong>maximum</strong> number of operations that can be performed, such that <strong>all operations have the same score</strong>.</p> <p>Return <em>the <strong>maximum</strong> number of operations possible that satisfy the condition mentioned above</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> We perform the following operations: - Delete the first two elements, with score 3 + 2 = 5, nums = [1,2,3,4]. - Delete the first and the last elements, with score 1 + 4 = 5, nums = [2,3]. - Delete the first and the last elements, with score 2 + 3 = 5, nums = []. We are unable to perform any more operations as nums is empty. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,6,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> We perform the following operations: - Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4]. - Delete the last two elements, with score 1 + 4 = 5, nums = [6]. It can be proven that we can perform at most 2 operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Memoization; Array; Dynamic Programming
Go
func maxOperations(nums []int) int { n := len(nums) var g func(i, j, s int) int g = func(i, j, s int) int { f := make([][]int, n) for i := range f { f[i] = make([]int, n) for j := range f { f[i][j] = -1 } } var dfs func(i, j int) int dfs = func(i, j int) int { if j-i < 1 { return 0 } if f[i][j] != -1 { return f[i][j] } ans := 0 if nums[i]+nums[i+1] == s { ans = max(ans, 1+dfs(i+2, j)) } if nums[i]+nums[j] == s { ans = max(ans, 1+dfs(i+1, j-1)) } if nums[j-1]+nums[j] == s { ans = max(ans, 1+dfs(i, j-2)) } f[i][j] = ans return ans } return dfs(i, j) } a := g(2, n-1, nums[0]+nums[1]) b := g(0, n-3, nums[n-1]+nums[n-2]) c := g(1, n-2, nums[0]+nums[n-1]) return 1 + max(a, b, c) }
3,040
Maximum Number of Operations With the Same Score II
Medium
<p>Given an array of integers called <code>nums</code>, you can perform <strong>any</strong> of the following operation while <code>nums</code> contains <strong>at least</strong> <code>2</code> elements:</p> <ul> <li>Choose the first two elements of <code>nums</code> and delete them.</li> <li>Choose the last two elements of <code>nums</code> and delete them.</li> <li>Choose the first and the last elements of <code>nums</code> and delete them.</li> </ul> <p>The<strong> score</strong> of the operation is the sum of the deleted elements.</p> <p>Your task is to find the <strong>maximum</strong> number of operations that can be performed, such that <strong>all operations have the same score</strong>.</p> <p>Return <em>the <strong>maximum</strong> number of operations possible that satisfy the condition mentioned above</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> We perform the following operations: - Delete the first two elements, with score 3 + 2 = 5, nums = [1,2,3,4]. - Delete the first and the last elements, with score 1 + 4 = 5, nums = [2,3]. - Delete the first and the last elements, with score 2 + 3 = 5, nums = []. We are unable to perform any more operations as nums is empty. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,6,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> We perform the following operations: - Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4]. - Delete the last two elements, with score 1 + 4 = 5, nums = [6]. It can be proven that we can perform at most 2 operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Memoization; Array; Dynamic Programming
Java
class Solution { private Integer[][] f; private int[] nums; private int s; private int n; public int maxOperations(int[] nums) { this.nums = nums; n = nums.length; int a = g(2, n - 1, nums[0] + nums[1]); int b = g(0, n - 3, nums[n - 2] + nums[n - 1]); int c = g(1, n - 2, nums[0] + nums[n - 1]); return 1 + Math.max(a, Math.max(b, c)); } private int g(int i, int j, int s) { f = new Integer[n][n]; this.s = s; return dfs(i, j); } private int dfs(int i, int j) { if (j - i < 1) { return 0; } if (f[i][j] != null) { return f[i][j]; } int ans = 0; if (nums[i] + nums[i + 1] == s) { ans = Math.max(ans, 1 + dfs(i + 2, j)); } if (nums[i] + nums[j] == s) { ans = Math.max(ans, 1 + dfs(i + 1, j - 1)); } if (nums[j - 1] + nums[j] == s) { ans = Math.max(ans, 1 + dfs(i, j - 2)); } return f[i][j] = ans; } }
3,040
Maximum Number of Operations With the Same Score II
Medium
<p>Given an array of integers called <code>nums</code>, you can perform <strong>any</strong> of the following operation while <code>nums</code> contains <strong>at least</strong> <code>2</code> elements:</p> <ul> <li>Choose the first two elements of <code>nums</code> and delete them.</li> <li>Choose the last two elements of <code>nums</code> and delete them.</li> <li>Choose the first and the last elements of <code>nums</code> and delete them.</li> </ul> <p>The<strong> score</strong> of the operation is the sum of the deleted elements.</p> <p>Your task is to find the <strong>maximum</strong> number of operations that can be performed, such that <strong>all operations have the same score</strong>.</p> <p>Return <em>the <strong>maximum</strong> number of operations possible that satisfy the condition mentioned above</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> We perform the following operations: - Delete the first two elements, with score 3 + 2 = 5, nums = [1,2,3,4]. - Delete the first and the last elements, with score 1 + 4 = 5, nums = [2,3]. - Delete the first and the last elements, with score 2 + 3 = 5, nums = []. We are unable to perform any more operations as nums is empty. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,6,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> We perform the following operations: - Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4]. - Delete the last two elements, with score 1 + 4 = 5, nums = [6]. It can be proven that we can perform at most 2 operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Memoization; Array; Dynamic Programming
Python
class Solution: def maxOperations(self, nums: List[int]) -> int: @cache def dfs(i: int, j: int, s: int) -> int: if j - i < 1: return 0 ans = 0 if nums[i] + nums[i + 1] == s: ans = max(ans, 1 + dfs(i + 2, j, s)) if nums[i] + nums[j] == s: ans = max(ans, 1 + dfs(i + 1, j - 1, s)) if nums[j - 1] + nums[j] == s: ans = max(ans, 1 + dfs(i, j - 2, s)) return ans n = len(nums) a = dfs(2, n - 1, nums[0] + nums[1]) b = dfs(0, n - 3, nums[-1] + nums[-2]) c = dfs(1, n - 2, nums[0] + nums[-1]) return 1 + max(a, b, c)
3,040
Maximum Number of Operations With the Same Score II
Medium
<p>Given an array of integers called <code>nums</code>, you can perform <strong>any</strong> of the following operation while <code>nums</code> contains <strong>at least</strong> <code>2</code> elements:</p> <ul> <li>Choose the first two elements of <code>nums</code> and delete them.</li> <li>Choose the last two elements of <code>nums</code> and delete them.</li> <li>Choose the first and the last elements of <code>nums</code> and delete them.</li> </ul> <p>The<strong> score</strong> of the operation is the sum of the deleted elements.</p> <p>Your task is to find the <strong>maximum</strong> number of operations that can be performed, such that <strong>all operations have the same score</strong>.</p> <p>Return <em>the <strong>maximum</strong> number of operations possible that satisfy the condition mentioned above</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1,2,3,4] <strong>Output:</strong> 3 <strong>Explanation:</strong> We perform the following operations: - Delete the first two elements, with score 3 + 2 = 5, nums = [1,2,3,4]. - Delete the first and the last elements, with score 1 + 4 = 5, nums = [2,3]. - Delete the first and the last elements, with score 2 + 3 = 5, nums = []. We are unable to perform any more operations as nums is empty. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,6,1,4] <strong>Output:</strong> 2 <strong>Explanation:</strong> We perform the following operations: - Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4]. - Delete the last two elements, with score 1 + 4 = 5, nums = [6]. It can be proven that we can perform at most 2 operations. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 2000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> </ul>
Memoization; Array; Dynamic Programming
TypeScript
function maxOperations(nums: number[]): number { const n = nums.length; const f: number[][] = Array.from({ length: n }, () => Array(n)); const g = (i: number, j: number, s: number): number => { f.forEach(row => row.fill(-1)); const dfs = (i: number, j: number): number => { if (j - i < 1) { return 0; } if (f[i][j] !== -1) { return f[i][j]; } let ans = 0; if (nums[i] + nums[i + 1] === s) { ans = Math.max(ans, 1 + dfs(i + 2, j)); } if (nums[i] + nums[j] === s) { ans = Math.max(ans, 1 + dfs(i + 1, j - 1)); } if (nums[j - 1] + nums[j] === s) { ans = Math.max(ans, 1 + dfs(i, j - 2)); } return (f[i][j] = ans); }; return dfs(i, j); }; const a = g(2, n - 1, nums[0] + nums[1]); const b = g(0, n - 3, nums[n - 2] + nums[n - 1]); const c = g(1, n - 2, nums[0] + nums[n - 1]); return 1 + Math.max(a, b, c); }
3,042
Count Prefix and Suffix Pairs I
Easy
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p> <p>Let&#39;s define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p> <ul> <li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li> </ul> <p>For example, <code>isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;)</code> is <code>true</code> because <code>&quot;aba&quot;</code> is a prefix of <code>&quot;ababa&quot;</code> and also a suffix, but <code>isPrefixAndSuffix(&quot;abc&quot;, &quot;abcd&quot;)</code> is <code>false</code>.</p> <p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i, j)</code><em> such that </em><code>i &lt; j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;aba&quot;,&quot;ababa&quot;,&quot;aa&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;a&quot;, &quot;aba&quot;) is true. i = 0 and j = 2 because isPrefixAndSuffix(&quot;a&quot;, &quot;ababa&quot;) is true. i = 0 and j = 3 because isPrefixAndSuffix(&quot;a&quot;, &quot;aa&quot;) is true. i = 1 and j = 2 because isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;) is true. Therefore, the answer is 4.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;pa&quot;,&quot;papa&quot;,&quot;ma&quot;,&quot;mama&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;pa&quot;, &quot;papa&quot;) is true. i = 2 and j = 3 because isPrefixAndSuffix(&quot;ma&quot;, &quot;mama&quot;) is true. Therefore, the answer is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abab&quot;,&quot;ab&quot;] <strong>Output:</strong> 0 <strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix(&quot;abab&quot;, &quot;ab&quot;) is false. Therefore, the answer is 0.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 50</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> </ul>
Trie; Array; String; String Matching; Hash Function; Rolling Hash
C++
class Solution { public: int countPrefixSuffixPairs(vector<string>& words) { int ans = 0; int n = words.size(); for (int i = 0; i < n; ++i) { string s = words[i]; for (int j = i + 1; j < n; ++j) { string t = words[j]; if (t.find(s) == 0 && t.rfind(s) == t.length() - s.length()) { ++ans; } } } return ans; } };
3,042
Count Prefix and Suffix Pairs I
Easy
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p> <p>Let&#39;s define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p> <ul> <li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li> </ul> <p>For example, <code>isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;)</code> is <code>true</code> because <code>&quot;aba&quot;</code> is a prefix of <code>&quot;ababa&quot;</code> and also a suffix, but <code>isPrefixAndSuffix(&quot;abc&quot;, &quot;abcd&quot;)</code> is <code>false</code>.</p> <p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i, j)</code><em> such that </em><code>i &lt; j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;aba&quot;,&quot;ababa&quot;,&quot;aa&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;a&quot;, &quot;aba&quot;) is true. i = 0 and j = 2 because isPrefixAndSuffix(&quot;a&quot;, &quot;ababa&quot;) is true. i = 0 and j = 3 because isPrefixAndSuffix(&quot;a&quot;, &quot;aa&quot;) is true. i = 1 and j = 2 because isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;) is true. Therefore, the answer is 4.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;pa&quot;,&quot;papa&quot;,&quot;ma&quot;,&quot;mama&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;pa&quot;, &quot;papa&quot;) is true. i = 2 and j = 3 because isPrefixAndSuffix(&quot;ma&quot;, &quot;mama&quot;) is true. Therefore, the answer is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abab&quot;,&quot;ab&quot;] <strong>Output:</strong> 0 <strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix(&quot;abab&quot;, &quot;ab&quot;) is false. Therefore, the answer is 0.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 50</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> </ul>
Trie; Array; String; String Matching; Hash Function; Rolling Hash
Go
func countPrefixSuffixPairs(words []string) (ans int) { for i, s := range words { for _, t := range words[i+1:] { if strings.HasPrefix(t, s) && strings.HasSuffix(t, s) { ans++ } } } return }
3,042
Count Prefix and Suffix Pairs I
Easy
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p> <p>Let&#39;s define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p> <ul> <li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li> </ul> <p>For example, <code>isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;)</code> is <code>true</code> because <code>&quot;aba&quot;</code> is a prefix of <code>&quot;ababa&quot;</code> and also a suffix, but <code>isPrefixAndSuffix(&quot;abc&quot;, &quot;abcd&quot;)</code> is <code>false</code>.</p> <p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i, j)</code><em> such that </em><code>i &lt; j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;aba&quot;,&quot;ababa&quot;,&quot;aa&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;a&quot;, &quot;aba&quot;) is true. i = 0 and j = 2 because isPrefixAndSuffix(&quot;a&quot;, &quot;ababa&quot;) is true. i = 0 and j = 3 because isPrefixAndSuffix(&quot;a&quot;, &quot;aa&quot;) is true. i = 1 and j = 2 because isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;) is true. Therefore, the answer is 4.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;pa&quot;,&quot;papa&quot;,&quot;ma&quot;,&quot;mama&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;pa&quot;, &quot;papa&quot;) is true. i = 2 and j = 3 because isPrefixAndSuffix(&quot;ma&quot;, &quot;mama&quot;) is true. Therefore, the answer is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abab&quot;,&quot;ab&quot;] <strong>Output:</strong> 0 <strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix(&quot;abab&quot;, &quot;ab&quot;) is false. Therefore, the answer is 0.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 50</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> </ul>
Trie; Array; String; String Matching; Hash Function; Rolling Hash
Java
class Solution { public int countPrefixSuffixPairs(String[] words) { int ans = 0; int n = words.length; for (int i = 0; i < n; ++i) { String s = words[i]; for (int j = i + 1; j < n; ++j) { String t = words[j]; if (t.startsWith(s) && t.endsWith(s)) { ++ans; } } } return ans; } }
3,042
Count Prefix and Suffix Pairs I
Easy
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p> <p>Let&#39;s define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p> <ul> <li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li> </ul> <p>For example, <code>isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;)</code> is <code>true</code> because <code>&quot;aba&quot;</code> is a prefix of <code>&quot;ababa&quot;</code> and also a suffix, but <code>isPrefixAndSuffix(&quot;abc&quot;, &quot;abcd&quot;)</code> is <code>false</code>.</p> <p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i, j)</code><em> such that </em><code>i &lt; j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;aba&quot;,&quot;ababa&quot;,&quot;aa&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;a&quot;, &quot;aba&quot;) is true. i = 0 and j = 2 because isPrefixAndSuffix(&quot;a&quot;, &quot;ababa&quot;) is true. i = 0 and j = 3 because isPrefixAndSuffix(&quot;a&quot;, &quot;aa&quot;) is true. i = 1 and j = 2 because isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;) is true. Therefore, the answer is 4.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;pa&quot;,&quot;papa&quot;,&quot;ma&quot;,&quot;mama&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;pa&quot;, &quot;papa&quot;) is true. i = 2 and j = 3 because isPrefixAndSuffix(&quot;ma&quot;, &quot;mama&quot;) is true. Therefore, the answer is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abab&quot;,&quot;ab&quot;] <strong>Output:</strong> 0 <strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix(&quot;abab&quot;, &quot;ab&quot;) is false. Therefore, the answer is 0.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 50</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> </ul>
Trie; Array; String; String Matching; Hash Function; Rolling Hash
Python
class Solution: def countPrefixSuffixPairs(self, words: List[str]) -> int: ans = 0 for i, s in enumerate(words): for t in words[i + 1 :]: ans += t.endswith(s) and t.startswith(s) return ans
3,042
Count Prefix and Suffix Pairs I
Easy
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p> <p>Let&#39;s define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p> <ul> <li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li> </ul> <p>For example, <code>isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;)</code> is <code>true</code> because <code>&quot;aba&quot;</code> is a prefix of <code>&quot;ababa&quot;</code> and also a suffix, but <code>isPrefixAndSuffix(&quot;abc&quot;, &quot;abcd&quot;)</code> is <code>false</code>.</p> <p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i, j)</code><em> such that </em><code>i &lt; j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;aba&quot;,&quot;ababa&quot;,&quot;aa&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;a&quot;, &quot;aba&quot;) is true. i = 0 and j = 2 because isPrefixAndSuffix(&quot;a&quot;, &quot;ababa&quot;) is true. i = 0 and j = 3 because isPrefixAndSuffix(&quot;a&quot;, &quot;aa&quot;) is true. i = 1 and j = 2 because isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;) is true. Therefore, the answer is 4.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;pa&quot;,&quot;papa&quot;,&quot;ma&quot;,&quot;mama&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;pa&quot;, &quot;papa&quot;) is true. i = 2 and j = 3 because isPrefixAndSuffix(&quot;ma&quot;, &quot;mama&quot;) is true. Therefore, the answer is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abab&quot;,&quot;ab&quot;] <strong>Output:</strong> 0 <strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix(&quot;abab&quot;, &quot;ab&quot;) is false. Therefore, the answer is 0.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 50</code></li> <li><code>1 &lt;= words[i].length &lt;= 10</code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> </ul>
Trie; Array; String; String Matching; Hash Function; Rolling Hash
TypeScript
function countPrefixSuffixPairs(words: string[]): number { let ans = 0; for (let i = 0; i < words.length; ++i) { const s = words[i]; for (const t of words.slice(i + 1)) { if (t.startsWith(s) && t.endsWith(s)) { ++ans; } } } return ans; }
3,043
Find the Length of the Longest Common Prefix
Medium
<p>You are given two arrays with <strong>positive</strong> integers <code>arr1</code> and <code>arr2</code>.</p> <p>A <strong>prefix</strong> of a positive integer is an integer formed by one or more of its digits, starting from its <strong>leftmost</strong> digit. For example, <code>123</code> is a prefix of the integer <code>12345</code>, while <code>234</code> is <strong>not</strong>.</p> <p>A <strong>common prefix</strong> of two integers <code>a</code> and <code>b</code> is an integer <code>c</code>, such that <code>c</code> is a prefix of both <code>a</code> and <code>b</code>. For example, <code>5655359</code> and <code>56554</code> have common prefixes <code>565</code> and <code>5655</code> while <code>1223</code> and <code>43456</code> <strong>do not</strong> have a common prefix.</p> <p>You need to find the length of the <strong>longest common prefix</strong> between all pairs of integers <code>(x, y)</code> such that <code>x</code> belongs to <code>arr1</code> and <code>y</code> belongs to <code>arr2</code>.</p> <p>Return <em>the length of the <strong>longest</strong> common prefix among all pairs</em>.<em> If no common prefix exists among them</em>, <em>return</em> <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr1 = [1,10,100], arr2 = [1000] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 pairs (arr1[i], arr2[j]): - The longest common prefix of (1, 1000) is 1. - The longest common prefix of (10, 1000) is 10. - The longest common prefix of (100, 1000) is 100. The longest common prefix is 100 with a length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr1 = [1,2,3], arr2 = [4,4,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0. Note that common prefixes between elements of the same array do not count. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arr1.length, arr2.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= arr1[i], arr2[i] &lt;= 10<sup>8</sup></code></li> </ul>
Trie; Array; Hash Table; String
C++
class Solution { public: int longestCommonPrefix(vector<int>& arr1, vector<int>& arr2) { unordered_set<int> s; for (int x : arr1) { for (; x; x /= 10) { s.insert(x); } } int ans = 0; for (int x : arr2) { for (; x; x /= 10) { if (s.count(x)) { ans = max(ans, (int) log10(x) + 1); break; } } } return ans; } };
3,043
Find the Length of the Longest Common Prefix
Medium
<p>You are given two arrays with <strong>positive</strong> integers <code>arr1</code> and <code>arr2</code>.</p> <p>A <strong>prefix</strong> of a positive integer is an integer formed by one or more of its digits, starting from its <strong>leftmost</strong> digit. For example, <code>123</code> is a prefix of the integer <code>12345</code>, while <code>234</code> is <strong>not</strong>.</p> <p>A <strong>common prefix</strong> of two integers <code>a</code> and <code>b</code> is an integer <code>c</code>, such that <code>c</code> is a prefix of both <code>a</code> and <code>b</code>. For example, <code>5655359</code> and <code>56554</code> have common prefixes <code>565</code> and <code>5655</code> while <code>1223</code> and <code>43456</code> <strong>do not</strong> have a common prefix.</p> <p>You need to find the length of the <strong>longest common prefix</strong> between all pairs of integers <code>(x, y)</code> such that <code>x</code> belongs to <code>arr1</code> and <code>y</code> belongs to <code>arr2</code>.</p> <p>Return <em>the length of the <strong>longest</strong> common prefix among all pairs</em>.<em> If no common prefix exists among them</em>, <em>return</em> <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr1 = [1,10,100], arr2 = [1000] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 pairs (arr1[i], arr2[j]): - The longest common prefix of (1, 1000) is 1. - The longest common prefix of (10, 1000) is 10. - The longest common prefix of (100, 1000) is 100. The longest common prefix is 100 with a length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr1 = [1,2,3], arr2 = [4,4,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0. Note that common prefixes between elements of the same array do not count. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arr1.length, arr2.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= arr1[i], arr2[i] &lt;= 10<sup>8</sup></code></li> </ul>
Trie; Array; Hash Table; String
Go
func longestCommonPrefix(arr1 []int, arr2 []int) (ans int) { s := map[int]bool{} for _, x := range arr1 { for ; x > 0; x /= 10 { s[x] = true } } for _, x := range arr2 { for ; x > 0; x /= 10 { if s[x] { ans = max(ans, int(math.Log10(float64(x)))+1) break } } } return }
3,043
Find the Length of the Longest Common Prefix
Medium
<p>You are given two arrays with <strong>positive</strong> integers <code>arr1</code> and <code>arr2</code>.</p> <p>A <strong>prefix</strong> of a positive integer is an integer formed by one or more of its digits, starting from its <strong>leftmost</strong> digit. For example, <code>123</code> is a prefix of the integer <code>12345</code>, while <code>234</code> is <strong>not</strong>.</p> <p>A <strong>common prefix</strong> of two integers <code>a</code> and <code>b</code> is an integer <code>c</code>, such that <code>c</code> is a prefix of both <code>a</code> and <code>b</code>. For example, <code>5655359</code> and <code>56554</code> have common prefixes <code>565</code> and <code>5655</code> while <code>1223</code> and <code>43456</code> <strong>do not</strong> have a common prefix.</p> <p>You need to find the length of the <strong>longest common prefix</strong> between all pairs of integers <code>(x, y)</code> such that <code>x</code> belongs to <code>arr1</code> and <code>y</code> belongs to <code>arr2</code>.</p> <p>Return <em>the length of the <strong>longest</strong> common prefix among all pairs</em>.<em> If no common prefix exists among them</em>, <em>return</em> <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr1 = [1,10,100], arr2 = [1000] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 pairs (arr1[i], arr2[j]): - The longest common prefix of (1, 1000) is 1. - The longest common prefix of (10, 1000) is 10. - The longest common prefix of (100, 1000) is 100. The longest common prefix is 100 with a length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr1 = [1,2,3], arr2 = [4,4,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0. Note that common prefixes between elements of the same array do not count. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arr1.length, arr2.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= arr1[i], arr2[i] &lt;= 10<sup>8</sup></code></li> </ul>
Trie; Array; Hash Table; String
Java
class Solution { public int longestCommonPrefix(int[] arr1, int[] arr2) { Set<Integer> s = new HashSet<>(); for (int x : arr1) { for (; x > 0; x /= 10) { s.add(x); } } int ans = 0; for (int x : arr2) { for (; x > 0; x /= 10) { if (s.contains(x)) { ans = Math.max(ans, String.valueOf(x).length()); break; } } } return ans; } }
3,043
Find the Length of the Longest Common Prefix
Medium
<p>You are given two arrays with <strong>positive</strong> integers <code>arr1</code> and <code>arr2</code>.</p> <p>A <strong>prefix</strong> of a positive integer is an integer formed by one or more of its digits, starting from its <strong>leftmost</strong> digit. For example, <code>123</code> is a prefix of the integer <code>12345</code>, while <code>234</code> is <strong>not</strong>.</p> <p>A <strong>common prefix</strong> of two integers <code>a</code> and <code>b</code> is an integer <code>c</code>, such that <code>c</code> is a prefix of both <code>a</code> and <code>b</code>. For example, <code>5655359</code> and <code>56554</code> have common prefixes <code>565</code> and <code>5655</code> while <code>1223</code> and <code>43456</code> <strong>do not</strong> have a common prefix.</p> <p>You need to find the length of the <strong>longest common prefix</strong> between all pairs of integers <code>(x, y)</code> such that <code>x</code> belongs to <code>arr1</code> and <code>y</code> belongs to <code>arr2</code>.</p> <p>Return <em>the length of the <strong>longest</strong> common prefix among all pairs</em>.<em> If no common prefix exists among them</em>, <em>return</em> <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr1 = [1,10,100], arr2 = [1000] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 pairs (arr1[i], arr2[j]): - The longest common prefix of (1, 1000) is 1. - The longest common prefix of (10, 1000) is 10. - The longest common prefix of (100, 1000) is 100. The longest common prefix is 100 with a length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr1 = [1,2,3], arr2 = [4,4,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0. Note that common prefixes between elements of the same array do not count. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arr1.length, arr2.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= arr1[i], arr2[i] &lt;= 10<sup>8</sup></code></li> </ul>
Trie; Array; Hash Table; String
JavaScript
/** * @param {number[]} arr1 * @param {number[]} arr2 * @return {number} */ var longestCommonPrefix = function (arr1, arr2) { const s = new Set(); for (let x of arr1) { for (; x; x = Math.floor(x / 10)) { s.add(x); } } let ans = 0; for (let x of arr2) { for (; x; x = Math.floor(x / 10)) { if (s.has(x)) { ans = Math.max(ans, Math.floor(Math.log10(x)) + 1); } } } return ans; };
3,043
Find the Length of the Longest Common Prefix
Medium
<p>You are given two arrays with <strong>positive</strong> integers <code>arr1</code> and <code>arr2</code>.</p> <p>A <strong>prefix</strong> of a positive integer is an integer formed by one or more of its digits, starting from its <strong>leftmost</strong> digit. For example, <code>123</code> is a prefix of the integer <code>12345</code>, while <code>234</code> is <strong>not</strong>.</p> <p>A <strong>common prefix</strong> of two integers <code>a</code> and <code>b</code> is an integer <code>c</code>, such that <code>c</code> is a prefix of both <code>a</code> and <code>b</code>. For example, <code>5655359</code> and <code>56554</code> have common prefixes <code>565</code> and <code>5655</code> while <code>1223</code> and <code>43456</code> <strong>do not</strong> have a common prefix.</p> <p>You need to find the length of the <strong>longest common prefix</strong> between all pairs of integers <code>(x, y)</code> such that <code>x</code> belongs to <code>arr1</code> and <code>y</code> belongs to <code>arr2</code>.</p> <p>Return <em>the length of the <strong>longest</strong> common prefix among all pairs</em>.<em> If no common prefix exists among them</em>, <em>return</em> <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr1 = [1,10,100], arr2 = [1000] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 pairs (arr1[i], arr2[j]): - The longest common prefix of (1, 1000) is 1. - The longest common prefix of (10, 1000) is 10. - The longest common prefix of (100, 1000) is 100. The longest common prefix is 100 with a length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr1 = [1,2,3], arr2 = [4,4,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0. Note that common prefixes between elements of the same array do not count. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arr1.length, arr2.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= arr1[i], arr2[i] &lt;= 10<sup>8</sup></code></li> </ul>
Trie; Array; Hash Table; String
Python
class Solution: def longestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int: s = set() for x in arr1: while x: s.add(x) x //= 10 ans = 0 for x in arr2: while x: if x in s: ans = max(ans, len(str(x))) break x //= 10 return ans
3,043
Find the Length of the Longest Common Prefix
Medium
<p>You are given two arrays with <strong>positive</strong> integers <code>arr1</code> and <code>arr2</code>.</p> <p>A <strong>prefix</strong> of a positive integer is an integer formed by one or more of its digits, starting from its <strong>leftmost</strong> digit. For example, <code>123</code> is a prefix of the integer <code>12345</code>, while <code>234</code> is <strong>not</strong>.</p> <p>A <strong>common prefix</strong> of two integers <code>a</code> and <code>b</code> is an integer <code>c</code>, such that <code>c</code> is a prefix of both <code>a</code> and <code>b</code>. For example, <code>5655359</code> and <code>56554</code> have common prefixes <code>565</code> and <code>5655</code> while <code>1223</code> and <code>43456</code> <strong>do not</strong> have a common prefix.</p> <p>You need to find the length of the <strong>longest common prefix</strong> between all pairs of integers <code>(x, y)</code> such that <code>x</code> belongs to <code>arr1</code> and <code>y</code> belongs to <code>arr2</code>.</p> <p>Return <em>the length of the <strong>longest</strong> common prefix among all pairs</em>.<em> If no common prefix exists among them</em>, <em>return</em> <code>0</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr1 = [1,10,100], arr2 = [1000] <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 pairs (arr1[i], arr2[j]): - The longest common prefix of (1, 1000) is 1. - The longest common prefix of (10, 1000) is 10. - The longest common prefix of (100, 1000) is 100. The longest common prefix is 100 with a length of 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr1 = [1,2,3], arr2 = [4,4,4] <strong>Output:</strong> 0 <strong>Explanation:</strong> There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0. Note that common prefixes between elements of the same array do not count. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= arr1.length, arr2.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= arr1[i], arr2[i] &lt;= 10<sup>8</sup></code></li> </ul>
Trie; Array; Hash Table; String
TypeScript
function longestCommonPrefix(arr1: number[], arr2: number[]): number { const s: Set<number> = new Set<number>(); for (let x of arr1) { for (; x; x = Math.floor(x / 10)) { s.add(x); } } let ans: number = 0; for (let x of arr2) { for (; x; x = Math.floor(x / 10)) { if (s.has(x)) { ans = Math.max(ans, Math.floor(Math.log10(x)) + 1); } } } return ans; }
3,044
Most Frequent Prime
Medium
<p>You are given a <code>m x n</code> <strong>0-indexed </strong>2D<strong> </strong>matrix <code>mat</code>. From every cell, you can create numbers in the following way:</p> <ul> <li>There could be at most <code>8</code> paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east.</li> <li>Select a path from them and append digits in this path to the number being formed by traveling in this direction.</li> <li>Note that numbers are generated at every step, for example, if the digits along the path are <code>1, 9, 1</code>, then there will be three numbers generated along the way: <code>1, 19, 191</code>.</li> </ul> <p>Return <em>the most frequent <span data-keyword="prime-number">prime number</span> <strong>greater</strong> than </em><code>10</code><em> out of all the numbers created by traversing the matrix or </em><code>-1</code><em> if no such prime number exists. If there are multiple prime numbers with the highest frequency, then return the <b>largest</b> among them.</em></p> <p><strong>Note:</strong> It is invalid to change the direction during the move.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3044.Most%20Frequent%20Prime/images/south" style="width: 641px; height: 291px;" /> </strong> <pre> <strong> Input:</strong> mat = [[1,1],[9,9],[1,1]] <strong>Output:</strong> 19 <strong>Explanation:</strong> From cell (0,0) there are 3 possible directions and the numbers greater than 10 which can be created in those directions are: East: [11], South-East: [19], South: [19,191]. Numbers greater than 10 created from the cell (0,1) in all possible directions are: [19,191,19,11]. Numbers greater than 10 created from the cell (1,0) in all possible directions are: [99,91,91,91,91]. Numbers greater than 10 created from the cell (1,1) in all possible directions are: [91,91,99,91,91]. Numbers greater than 10 created from the cell (2,0) in all possible directions are: [11,19,191,19]. Numbers greater than 10 created from the cell (2,1) in all possible directions are: [11,19,19,191]. The most frequent prime number among all the created numbers is 19.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[7]] <strong>Output:</strong> -1 <strong>Explanation:</strong> The only number which can be formed is 7. It is a prime number however it is not greater than 10, so return -1.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> mat = [[9,7,8],[4,6,5],[2,8,6]] <strong>Output:</strong> 97 <strong>Explanation:</strong> Numbers greater than 10 created from the cell (0,0) in all possible directions are: [97,978,96,966,94,942]. Numbers greater than 10 created from the cell (0,1) in all possible directions are: [78,75,76,768,74,79]. Numbers greater than 10 created from the cell (0,2) in all possible directions are: [85,856,86,862,87,879]. Numbers greater than 10 created from the cell (1,0) in all possible directions are: [46,465,48,42,49,47]. Numbers greater than 10 created from the cell (1,1) in all possible directions are: [65,66,68,62,64,69,67,68]. Numbers greater than 10 created from the cell (1,2) in all possible directions are: [56,58,56,564,57,58]. Numbers greater than 10 created from the cell (2,0) in all possible directions are: [28,286,24,249,26,268]. Numbers greater than 10 created from the cell (2,1) in all possible directions are: [86,82,84,86,867,85]. Numbers greater than 10 created from the cell (2,2) in all possible directions are: [68,682,66,669,65,658]. The most frequent prime number among all the created numbers is 97. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 6</code></li> <li><code>1 &lt;= mat[i][j] &lt;= 9</code></li> </ul>
Array; Hash Table; Math; Counting; Enumeration; Matrix; Number Theory
C++
class Solution { public: int mostFrequentPrime(vector<vector<int>>& mat) { int m = mat.size(), n = mat[0].size(); unordered_map<int, int> cnt; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { for (int a = -1; a <= 1; ++a) { for (int b = -1; b <= 1; ++b) { if (a == 0 && b == 0) { continue; } int x = i + a, y = j + b, v = mat[i][j]; while (x >= 0 && x < m && y >= 0 && y < n) { v = v * 10 + mat[x][y]; if (isPrime(v)) { cnt[v]++; } x += a; y += b; } } } } } int ans = -1, mx = 0; for (auto& [v, x] : cnt) { if (mx < x || (mx == x && ans < v)) { mx = x; ans = v; } } return ans; } private: bool isPrime(int n) { for (int i = 2; i <= n / i; ++i) { if (n % i == 0) { return false; } } return true; } };
3,044
Most Frequent Prime
Medium
<p>You are given a <code>m x n</code> <strong>0-indexed </strong>2D<strong> </strong>matrix <code>mat</code>. From every cell, you can create numbers in the following way:</p> <ul> <li>There could be at most <code>8</code> paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east.</li> <li>Select a path from them and append digits in this path to the number being formed by traveling in this direction.</li> <li>Note that numbers are generated at every step, for example, if the digits along the path are <code>1, 9, 1</code>, then there will be three numbers generated along the way: <code>1, 19, 191</code>.</li> </ul> <p>Return <em>the most frequent <span data-keyword="prime-number">prime number</span> <strong>greater</strong> than </em><code>10</code><em> out of all the numbers created by traversing the matrix or </em><code>-1</code><em> if no such prime number exists. If there are multiple prime numbers with the highest frequency, then return the <b>largest</b> among them.</em></p> <p><strong>Note:</strong> It is invalid to change the direction during the move.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3044.Most%20Frequent%20Prime/images/south" style="width: 641px; height: 291px;" /> </strong> <pre> <strong> Input:</strong> mat = [[1,1],[9,9],[1,1]] <strong>Output:</strong> 19 <strong>Explanation:</strong> From cell (0,0) there are 3 possible directions and the numbers greater than 10 which can be created in those directions are: East: [11], South-East: [19], South: [19,191]. Numbers greater than 10 created from the cell (0,1) in all possible directions are: [19,191,19,11]. Numbers greater than 10 created from the cell (1,0) in all possible directions are: [99,91,91,91,91]. Numbers greater than 10 created from the cell (1,1) in all possible directions are: [91,91,99,91,91]. Numbers greater than 10 created from the cell (2,0) in all possible directions are: [11,19,191,19]. Numbers greater than 10 created from the cell (2,1) in all possible directions are: [11,19,19,191]. The most frequent prime number among all the created numbers is 19.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[7]] <strong>Output:</strong> -1 <strong>Explanation:</strong> The only number which can be formed is 7. It is a prime number however it is not greater than 10, so return -1.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> mat = [[9,7,8],[4,6,5],[2,8,6]] <strong>Output:</strong> 97 <strong>Explanation:</strong> Numbers greater than 10 created from the cell (0,0) in all possible directions are: [97,978,96,966,94,942]. Numbers greater than 10 created from the cell (0,1) in all possible directions are: [78,75,76,768,74,79]. Numbers greater than 10 created from the cell (0,2) in all possible directions are: [85,856,86,862,87,879]. Numbers greater than 10 created from the cell (1,0) in all possible directions are: [46,465,48,42,49,47]. Numbers greater than 10 created from the cell (1,1) in all possible directions are: [65,66,68,62,64,69,67,68]. Numbers greater than 10 created from the cell (1,2) in all possible directions are: [56,58,56,564,57,58]. Numbers greater than 10 created from the cell (2,0) in all possible directions are: [28,286,24,249,26,268]. Numbers greater than 10 created from the cell (2,1) in all possible directions are: [86,82,84,86,867,85]. Numbers greater than 10 created from the cell (2,2) in all possible directions are: [68,682,66,669,65,658]. The most frequent prime number among all the created numbers is 97. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 6</code></li> <li><code>1 &lt;= mat[i][j] &lt;= 9</code></li> </ul>
Array; Hash Table; Math; Counting; Enumeration; Matrix; Number Theory
Go
func mostFrequentPrime(mat [][]int) int { m, n := len(mat), len(mat[0]) cnt := make(map[int]int) for i := 0; i < m; i++ { for j := 0; j < n; j++ { for a := -1; a <= 1; a++ { for b := -1; b <= 1; b++ { if a == 0 && b == 0 { continue } x, y, v := i+a, j+b, mat[i][j] for x >= 0 && x < m && y >= 0 && y < n { v = v*10 + mat[x][y] if isPrime(v) { cnt[v]++ } x += a y += b } } } } } ans, mx := -1, 0 for v, x := range cnt { if mx < x || (mx == x && ans < v) { mx = x ans = v } } return ans } func isPrime(n int) bool { for i := 2; i <= n/i; i++ { if n%i == 0 { return false } } return true }
3,044
Most Frequent Prime
Medium
<p>You are given a <code>m x n</code> <strong>0-indexed </strong>2D<strong> </strong>matrix <code>mat</code>. From every cell, you can create numbers in the following way:</p> <ul> <li>There could be at most <code>8</code> paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east.</li> <li>Select a path from them and append digits in this path to the number being formed by traveling in this direction.</li> <li>Note that numbers are generated at every step, for example, if the digits along the path are <code>1, 9, 1</code>, then there will be three numbers generated along the way: <code>1, 19, 191</code>.</li> </ul> <p>Return <em>the most frequent <span data-keyword="prime-number">prime number</span> <strong>greater</strong> than </em><code>10</code><em> out of all the numbers created by traversing the matrix or </em><code>-1</code><em> if no such prime number exists. If there are multiple prime numbers with the highest frequency, then return the <b>largest</b> among them.</em></p> <p><strong>Note:</strong> It is invalid to change the direction during the move.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3044.Most%20Frequent%20Prime/images/south" style="width: 641px; height: 291px;" /> </strong> <pre> <strong> Input:</strong> mat = [[1,1],[9,9],[1,1]] <strong>Output:</strong> 19 <strong>Explanation:</strong> From cell (0,0) there are 3 possible directions and the numbers greater than 10 which can be created in those directions are: East: [11], South-East: [19], South: [19,191]. Numbers greater than 10 created from the cell (0,1) in all possible directions are: [19,191,19,11]. Numbers greater than 10 created from the cell (1,0) in all possible directions are: [99,91,91,91,91]. Numbers greater than 10 created from the cell (1,1) in all possible directions are: [91,91,99,91,91]. Numbers greater than 10 created from the cell (2,0) in all possible directions are: [11,19,191,19]. Numbers greater than 10 created from the cell (2,1) in all possible directions are: [11,19,19,191]. The most frequent prime number among all the created numbers is 19.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[7]] <strong>Output:</strong> -1 <strong>Explanation:</strong> The only number which can be formed is 7. It is a prime number however it is not greater than 10, so return -1.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> mat = [[9,7,8],[4,6,5],[2,8,6]] <strong>Output:</strong> 97 <strong>Explanation:</strong> Numbers greater than 10 created from the cell (0,0) in all possible directions are: [97,978,96,966,94,942]. Numbers greater than 10 created from the cell (0,1) in all possible directions are: [78,75,76,768,74,79]. Numbers greater than 10 created from the cell (0,2) in all possible directions are: [85,856,86,862,87,879]. Numbers greater than 10 created from the cell (1,0) in all possible directions are: [46,465,48,42,49,47]. Numbers greater than 10 created from the cell (1,1) in all possible directions are: [65,66,68,62,64,69,67,68]. Numbers greater than 10 created from the cell (1,2) in all possible directions are: [56,58,56,564,57,58]. Numbers greater than 10 created from the cell (2,0) in all possible directions are: [28,286,24,249,26,268]. Numbers greater than 10 created from the cell (2,1) in all possible directions are: [86,82,84,86,867,85]. Numbers greater than 10 created from the cell (2,2) in all possible directions are: [68,682,66,669,65,658]. The most frequent prime number among all the created numbers is 97. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 6</code></li> <li><code>1 &lt;= mat[i][j] &lt;= 9</code></li> </ul>
Array; Hash Table; Math; Counting; Enumeration; Matrix; Number Theory
Java
class Solution { public int mostFrequentPrime(int[][] mat) { int m = mat.length, n = mat[0].length; Map<Integer, Integer> cnt = new HashMap<>(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { for (int a = -1; a <= 1; ++a) { for (int b = -1; b <= 1; ++b) { if (a == 0 && b == 0) { continue; } int x = i + a, y = j + b, v = mat[i][j]; while (x >= 0 && x < m && y >= 0 && y < n) { v = v * 10 + mat[x][y]; if (isPrime(v)) { cnt.merge(v, 1, Integer::sum); } x += a; y += b; } } } } } int ans = -1, mx = 0; for (var e : cnt.entrySet()) { int v = e.getKey(), x = e.getValue(); if (mx < x || (mx == x && ans < v)) { mx = x; ans = v; } } return ans; } private boolean isPrime(int n) { for (int i = 2; i <= n / i; ++i) { if (n % i == 0) { return false; } } return true; } }
3,044
Most Frequent Prime
Medium
<p>You are given a <code>m x n</code> <strong>0-indexed </strong>2D<strong> </strong>matrix <code>mat</code>. From every cell, you can create numbers in the following way:</p> <ul> <li>There could be at most <code>8</code> paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east.</li> <li>Select a path from them and append digits in this path to the number being formed by traveling in this direction.</li> <li>Note that numbers are generated at every step, for example, if the digits along the path are <code>1, 9, 1</code>, then there will be three numbers generated along the way: <code>1, 19, 191</code>.</li> </ul> <p>Return <em>the most frequent <span data-keyword="prime-number">prime number</span> <strong>greater</strong> than </em><code>10</code><em> out of all the numbers created by traversing the matrix or </em><code>-1</code><em> if no such prime number exists. If there are multiple prime numbers with the highest frequency, then return the <b>largest</b> among them.</em></p> <p><strong>Note:</strong> It is invalid to change the direction during the move.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3044.Most%20Frequent%20Prime/images/south" style="width: 641px; height: 291px;" /> </strong> <pre> <strong> Input:</strong> mat = [[1,1],[9,9],[1,1]] <strong>Output:</strong> 19 <strong>Explanation:</strong> From cell (0,0) there are 3 possible directions and the numbers greater than 10 which can be created in those directions are: East: [11], South-East: [19], South: [19,191]. Numbers greater than 10 created from the cell (0,1) in all possible directions are: [19,191,19,11]. Numbers greater than 10 created from the cell (1,0) in all possible directions are: [99,91,91,91,91]. Numbers greater than 10 created from the cell (1,1) in all possible directions are: [91,91,99,91,91]. Numbers greater than 10 created from the cell (2,0) in all possible directions are: [11,19,191,19]. Numbers greater than 10 created from the cell (2,1) in all possible directions are: [11,19,19,191]. The most frequent prime number among all the created numbers is 19.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[7]] <strong>Output:</strong> -1 <strong>Explanation:</strong> The only number which can be formed is 7. It is a prime number however it is not greater than 10, so return -1.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> mat = [[9,7,8],[4,6,5],[2,8,6]] <strong>Output:</strong> 97 <strong>Explanation:</strong> Numbers greater than 10 created from the cell (0,0) in all possible directions are: [97,978,96,966,94,942]. Numbers greater than 10 created from the cell (0,1) in all possible directions are: [78,75,76,768,74,79]. Numbers greater than 10 created from the cell (0,2) in all possible directions are: [85,856,86,862,87,879]. Numbers greater than 10 created from the cell (1,0) in all possible directions are: [46,465,48,42,49,47]. Numbers greater than 10 created from the cell (1,1) in all possible directions are: [65,66,68,62,64,69,67,68]. Numbers greater than 10 created from the cell (1,2) in all possible directions are: [56,58,56,564,57,58]. Numbers greater than 10 created from the cell (2,0) in all possible directions are: [28,286,24,249,26,268]. Numbers greater than 10 created from the cell (2,1) in all possible directions are: [86,82,84,86,867,85]. Numbers greater than 10 created from the cell (2,2) in all possible directions are: [68,682,66,669,65,658]. The most frequent prime number among all the created numbers is 97. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 6</code></li> <li><code>1 &lt;= mat[i][j] &lt;= 9</code></li> </ul>
Array; Hash Table; Math; Counting; Enumeration; Matrix; Number Theory
Python
class Solution: def mostFrequentPrime(self, mat: List[List[int]]) -> int: def is_prime(x: int) -> int: return all(x % i != 0 for i in range(2, isqrt(x) + 1)) m, n = len(mat), len(mat[0]) cnt = Counter() for i in range(m): for j in range(n): for a in range(-1, 2): for b in range(-1, 2): if a == 0 and b == 0: continue x, y, v = i + a, j + b, mat[i][j] while 0 <= x < m and 0 <= y < n: v = v * 10 + mat[x][y] if is_prime(v): cnt[v] += 1 x, y = x + a, y + b ans, mx = -1, 0 for v, x in cnt.items(): if mx < x: mx = x ans = v elif mx == x: ans = max(ans, v) return ans
3,044
Most Frequent Prime
Medium
<p>You are given a <code>m x n</code> <strong>0-indexed </strong>2D<strong> </strong>matrix <code>mat</code>. From every cell, you can create numbers in the following way:</p> <ul> <li>There could be at most <code>8</code> paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east.</li> <li>Select a path from them and append digits in this path to the number being formed by traveling in this direction.</li> <li>Note that numbers are generated at every step, for example, if the digits along the path are <code>1, 9, 1</code>, then there will be three numbers generated along the way: <code>1, 19, 191</code>.</li> </ul> <p>Return <em>the most frequent <span data-keyword="prime-number">prime number</span> <strong>greater</strong> than </em><code>10</code><em> out of all the numbers created by traversing the matrix or </em><code>-1</code><em> if no such prime number exists. If there are multiple prime numbers with the highest frequency, then return the <b>largest</b> among them.</em></p> <p><strong>Note:</strong> It is invalid to change the direction during the move.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <strong><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3044.Most%20Frequent%20Prime/images/south" style="width: 641px; height: 291px;" /> </strong> <pre> <strong> Input:</strong> mat = [[1,1],[9,9],[1,1]] <strong>Output:</strong> 19 <strong>Explanation:</strong> From cell (0,0) there are 3 possible directions and the numbers greater than 10 which can be created in those directions are: East: [11], South-East: [19], South: [19,191]. Numbers greater than 10 created from the cell (0,1) in all possible directions are: [19,191,19,11]. Numbers greater than 10 created from the cell (1,0) in all possible directions are: [99,91,91,91,91]. Numbers greater than 10 created from the cell (1,1) in all possible directions are: [91,91,99,91,91]. Numbers greater than 10 created from the cell (2,0) in all possible directions are: [11,19,191,19]. Numbers greater than 10 created from the cell (2,1) in all possible directions are: [11,19,19,191]. The most frequent prime number among all the created numbers is 19.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mat = [[7]] <strong>Output:</strong> -1 <strong>Explanation:</strong> The only number which can be formed is 7. It is a prime number however it is not greater than 10, so return -1.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> mat = [[9,7,8],[4,6,5],[2,8,6]] <strong>Output:</strong> 97 <strong>Explanation:</strong> Numbers greater than 10 created from the cell (0,0) in all possible directions are: [97,978,96,966,94,942]. Numbers greater than 10 created from the cell (0,1) in all possible directions are: [78,75,76,768,74,79]. Numbers greater than 10 created from the cell (0,2) in all possible directions are: [85,856,86,862,87,879]. Numbers greater than 10 created from the cell (1,0) in all possible directions are: [46,465,48,42,49,47]. Numbers greater than 10 created from the cell (1,1) in all possible directions are: [65,66,68,62,64,69,67,68]. Numbers greater than 10 created from the cell (1,2) in all possible directions are: [56,58,56,564,57,58]. Numbers greater than 10 created from the cell (2,0) in all possible directions are: [28,286,24,249,26,268]. Numbers greater than 10 created from the cell (2,1) in all possible directions are: [86,82,84,86,867,85]. Numbers greater than 10 created from the cell (2,2) in all possible directions are: [68,682,66,669,65,658]. The most frequent prime number among all the created numbers is 97. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n == mat[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 6</code></li> <li><code>1 &lt;= mat[i][j] &lt;= 9</code></li> </ul>
Array; Hash Table; Math; Counting; Enumeration; Matrix; Number Theory
TypeScript
function mostFrequentPrime(mat: number[][]): number { const m: number = mat.length; const n: number = mat[0].length; const cnt: Map<number, number> = new Map(); const isPrime = (x: number): boolean => { for (let i = 2; i <= x / i; ++i) { if (x % i === 0) { return false; } } return true; }; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { for (let a = -1; a <= 1; ++a) { for (let b = -1; b <= 1; ++b) { if (a === 0 && b === 0) { continue; } let [x, y, v] = [i + a, j + b, mat[i][j]]; while (x >= 0 && x < m && y >= 0 && y < n) { v = v * 10 + mat[x][y]; if (isPrime(v)) { cnt.set(v, (cnt.get(v) || 0) + 1); } x += a; y += b; } } } } } let [ans, mx] = [-1, 0]; cnt.forEach((x, v) => { if (mx < x || (mx === x && ans < v)) { mx = x; ans = v; } }); return ans; }
3,045
Count Prefix and Suffix Pairs II
Hard
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p> <p>Let&#39;s define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p> <ul> <li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li> </ul> <p>For example, <code>isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;)</code> is <code>true</code> because <code>&quot;aba&quot;</code> is a prefix of <code>&quot;ababa&quot;</code> and also a suffix, but <code>isPrefixAndSuffix(&quot;abc&quot;, &quot;abcd&quot;)</code> is <code>false</code>.</p> <p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i<em>, </em>j)</code><em> such that </em><code>i &lt; j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;aba&quot;,&quot;ababa&quot;,&quot;aa&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;a&quot;, &quot;aba&quot;) is true. i = 0 and j = 2 because isPrefixAndSuffix(&quot;a&quot;, &quot;ababa&quot;) is true. i = 0 and j = 3 because isPrefixAndSuffix(&quot;a&quot;, &quot;aa&quot;) is true. i = 1 and j = 2 because isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;) is true. Therefore, the answer is 4.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;pa&quot;,&quot;papa&quot;,&quot;ma&quot;,&quot;mama&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;pa&quot;, &quot;papa&quot;) is true. i = 2 and j = 3 because isPrefixAndSuffix(&quot;ma&quot;, &quot;mama&quot;) is true. Therefore, the answer is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abab&quot;,&quot;ab&quot;] <strong>Output:</strong> 0 <strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix(&quot;abab&quot;, &quot;ab&quot;) is false. Therefore, the answer is 0.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10<sup>5</sup></code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li>The sum of the lengths of all <code>words[i]</code> does not exceed <code>5 * 10<sup>5</sup></code>.</li> </ul>
Trie; Array; String; String Matching; Hash Function; Rolling Hash
C++
class Node { public: unordered_map<int, Node*> children; int cnt; Node() : cnt(0) {} }; class Solution { public: long long countPrefixSuffixPairs(vector<string>& words) { long long ans = 0; Node* trie = new Node(); for (const string& s : words) { Node* node = trie; int m = s.length(); for (int i = 0; i < m; ++i) { int p = s[i] * 32 + s[m - i - 1]; if (node->children.find(p) == node->children.end()) { node->children[p] = new Node(); } node = node->children[p]; ans += node->cnt; } ++node->cnt; } return ans; } };
3,045
Count Prefix and Suffix Pairs II
Hard
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p> <p>Let&#39;s define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p> <ul> <li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li> </ul> <p>For example, <code>isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;)</code> is <code>true</code> because <code>&quot;aba&quot;</code> is a prefix of <code>&quot;ababa&quot;</code> and also a suffix, but <code>isPrefixAndSuffix(&quot;abc&quot;, &quot;abcd&quot;)</code> is <code>false</code>.</p> <p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i<em>, </em>j)</code><em> such that </em><code>i &lt; j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;aba&quot;,&quot;ababa&quot;,&quot;aa&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;a&quot;, &quot;aba&quot;) is true. i = 0 and j = 2 because isPrefixAndSuffix(&quot;a&quot;, &quot;ababa&quot;) is true. i = 0 and j = 3 because isPrefixAndSuffix(&quot;a&quot;, &quot;aa&quot;) is true. i = 1 and j = 2 because isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;) is true. Therefore, the answer is 4.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;pa&quot;,&quot;papa&quot;,&quot;ma&quot;,&quot;mama&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;pa&quot;, &quot;papa&quot;) is true. i = 2 and j = 3 because isPrefixAndSuffix(&quot;ma&quot;, &quot;mama&quot;) is true. Therefore, the answer is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abab&quot;,&quot;ab&quot;] <strong>Output:</strong> 0 <strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix(&quot;abab&quot;, &quot;ab&quot;) is false. Therefore, the answer is 0.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10<sup>5</sup></code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li>The sum of the lengths of all <code>words[i]</code> does not exceed <code>5 * 10<sup>5</sup></code>.</li> </ul>
Trie; Array; String; String Matching; Hash Function; Rolling Hash
Go
type Node struct { children map[int]*Node cnt int } func countPrefixSuffixPairs(words []string) (ans int64) { trie := &Node{children: make(map[int]*Node)} for _, s := range words { node := trie m := len(s) for i := 0; i < m; i++ { p := int(s[i])*32 + int(s[m-i-1]) if _, ok := node.children[p]; !ok { node.children[p] = &Node{children: make(map[int]*Node)} } node = node.children[p] ans += int64(node.cnt) } node.cnt++ } return }
3,045
Count Prefix and Suffix Pairs II
Hard
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p> <p>Let&#39;s define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p> <ul> <li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li> </ul> <p>For example, <code>isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;)</code> is <code>true</code> because <code>&quot;aba&quot;</code> is a prefix of <code>&quot;ababa&quot;</code> and also a suffix, but <code>isPrefixAndSuffix(&quot;abc&quot;, &quot;abcd&quot;)</code> is <code>false</code>.</p> <p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i<em>, </em>j)</code><em> such that </em><code>i &lt; j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;aba&quot;,&quot;ababa&quot;,&quot;aa&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;a&quot;, &quot;aba&quot;) is true. i = 0 and j = 2 because isPrefixAndSuffix(&quot;a&quot;, &quot;ababa&quot;) is true. i = 0 and j = 3 because isPrefixAndSuffix(&quot;a&quot;, &quot;aa&quot;) is true. i = 1 and j = 2 because isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;) is true. Therefore, the answer is 4.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;pa&quot;,&quot;papa&quot;,&quot;ma&quot;,&quot;mama&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;pa&quot;, &quot;papa&quot;) is true. i = 2 and j = 3 because isPrefixAndSuffix(&quot;ma&quot;, &quot;mama&quot;) is true. Therefore, the answer is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abab&quot;,&quot;ab&quot;] <strong>Output:</strong> 0 <strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix(&quot;abab&quot;, &quot;ab&quot;) is false. Therefore, the answer is 0.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10<sup>5</sup></code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li>The sum of the lengths of all <code>words[i]</code> does not exceed <code>5 * 10<sup>5</sup></code>.</li> </ul>
Trie; Array; String; String Matching; Hash Function; Rolling Hash
Java
class Node { Map<Integer, Node> children = new HashMap<>(); int cnt; } class Solution { public long countPrefixSuffixPairs(String[] words) { long ans = 0; Node trie = new Node(); for (String s : words) { Node node = trie; int m = s.length(); for (int i = 0; i < m; ++i) { int p = s.charAt(i) * 32 + s.charAt(m - i - 1); node.children.putIfAbsent(p, new Node()); node = node.children.get(p); ans += node.cnt; } ++node.cnt; } return ans; } }
3,045
Count Prefix and Suffix Pairs II
Hard
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p> <p>Let&#39;s define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p> <ul> <li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li> </ul> <p>For example, <code>isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;)</code> is <code>true</code> because <code>&quot;aba&quot;</code> is a prefix of <code>&quot;ababa&quot;</code> and also a suffix, but <code>isPrefixAndSuffix(&quot;abc&quot;, &quot;abcd&quot;)</code> is <code>false</code>.</p> <p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i<em>, </em>j)</code><em> such that </em><code>i &lt; j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;aba&quot;,&quot;ababa&quot;,&quot;aa&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;a&quot;, &quot;aba&quot;) is true. i = 0 and j = 2 because isPrefixAndSuffix(&quot;a&quot;, &quot;ababa&quot;) is true. i = 0 and j = 3 because isPrefixAndSuffix(&quot;a&quot;, &quot;aa&quot;) is true. i = 1 and j = 2 because isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;) is true. Therefore, the answer is 4.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;pa&quot;,&quot;papa&quot;,&quot;ma&quot;,&quot;mama&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;pa&quot;, &quot;papa&quot;) is true. i = 2 and j = 3 because isPrefixAndSuffix(&quot;ma&quot;, &quot;mama&quot;) is true. Therefore, the answer is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abab&quot;,&quot;ab&quot;] <strong>Output:</strong> 0 <strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix(&quot;abab&quot;, &quot;ab&quot;) is false. Therefore, the answer is 0.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10<sup>5</sup></code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li>The sum of the lengths of all <code>words[i]</code> does not exceed <code>5 * 10<sup>5</sup></code>.</li> </ul>
Trie; Array; String; String Matching; Hash Function; Rolling Hash
Python
class Node: __slots__ = ["children", "cnt"] def __init__(self): self.children = {} self.cnt = 0 class Solution: def countPrefixSuffixPairs(self, words: List[str]) -> int: ans = 0 trie = Node() for s in words: node = trie for p in zip(s, reversed(s)): if p not in node.children: node.children[p] = Node() node = node.children[p] ans += node.cnt node.cnt += 1 return ans
3,045
Count Prefix and Suffix Pairs II
Hard
<p>You are given a <strong>0-indexed</strong> string array <code>words</code>.</p> <p>Let&#39;s define a <strong>boolean</strong> function <code>isPrefixAndSuffix</code> that takes two strings, <code>str1</code> and <code>str2</code>:</p> <ul> <li><code>isPrefixAndSuffix(str1, str2)</code> returns <code>true</code> if <code>str1</code> is <strong>both</strong> a <span data-keyword="string-prefix">prefix</span> and a <span data-keyword="string-suffix">suffix</span> of <code>str2</code>, and <code>false</code> otherwise.</li> </ul> <p>For example, <code>isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;)</code> is <code>true</code> because <code>&quot;aba&quot;</code> is a prefix of <code>&quot;ababa&quot;</code> and also a suffix, but <code>isPrefixAndSuffix(&quot;abc&quot;, &quot;abcd&quot;)</code> is <code>false</code>.</p> <p>Return <em>an integer denoting the <strong>number</strong> of index pairs </em><code>(i<em>, </em>j)</code><em> such that </em><code>i &lt; j</code><em>, and </em><code>isPrefixAndSuffix(words[i], words[j])</code><em> is </em><code>true</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;a&quot;,&quot;aba&quot;,&quot;ababa&quot;,&quot;aa&quot;] <strong>Output:</strong> 4 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;a&quot;, &quot;aba&quot;) is true. i = 0 and j = 2 because isPrefixAndSuffix(&quot;a&quot;, &quot;ababa&quot;) is true. i = 0 and j = 3 because isPrefixAndSuffix(&quot;a&quot;, &quot;aa&quot;) is true. i = 1 and j = 2 because isPrefixAndSuffix(&quot;aba&quot;, &quot;ababa&quot;) is true. Therefore, the answer is 4.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;pa&quot;,&quot;papa&quot;,&quot;ma&quot;,&quot;mama&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the counted index pairs are: i = 0 and j = 1 because isPrefixAndSuffix(&quot;pa&quot;, &quot;papa&quot;) is true. i = 2 and j = 3 because isPrefixAndSuffix(&quot;ma&quot;, &quot;mama&quot;) is true. Therefore, the answer is 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abab&quot;,&quot;ab&quot;] <strong>Output:</strong> 0 <strong>Explanation: </strong>In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix(&quot;abab&quot;, &quot;ab&quot;) is false. Therefore, the answer is 0.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10<sup>5</sup></code></li> <li><code>words[i]</code> consists only of lowercase English letters.</li> <li>The sum of the lengths of all <code>words[i]</code> does not exceed <code>5 * 10<sup>5</sup></code>.</li> </ul>
Trie; Array; String; String Matching; Hash Function; Rolling Hash
TypeScript
class Node { children: Map<number, Node> = new Map<number, Node>(); cnt: number = 0; } function countPrefixSuffixPairs(words: string[]): number { let ans: number = 0; const trie: Node = new Node(); for (const s of words) { let node: Node = trie; const m: number = s.length; for (let i: number = 0; i < m; ++i) { const p: number = s.charCodeAt(i) * 32 + s.charCodeAt(m - i - 1); if (!node.children.has(p)) { node.children.set(p, new Node()); } node = node.children.get(p)!; ans += node.cnt; } ++node.cnt; } return ans; }
3,046
Split the Array
Easy
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p> <ul> <li><code>nums1.length == nums2.length == nums.length / 2</code>.</li> <li><code>nums1</code> should contain <strong>distinct </strong>elements.</li> <li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li> </ul> <p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,2,3,4] <strong>Output:</strong> true <strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1] <strong>Output:</strong> false <strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums.length % 2 == 0 </code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Hash Table; Counting
C++
class Solution { public: bool isPossibleToSplit(vector<int>& nums) { int cnt[101]{}; for (int x : nums) { if (++cnt[x] >= 3) { return false; } } return true; } };
3,046
Split the Array
Easy
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p> <ul> <li><code>nums1.length == nums2.length == nums.length / 2</code>.</li> <li><code>nums1</code> should contain <strong>distinct </strong>elements.</li> <li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li> </ul> <p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,2,3,4] <strong>Output:</strong> true <strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1] <strong>Output:</strong> false <strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums.length % 2 == 0 </code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Hash Table; Counting
C#
public class Solution { public bool IsPossibleToSplit(int[] nums) { int[] cnt = new int[101]; foreach (int x in nums) { if (++cnt[x] >= 3) { return false; } } return true; } }
3,046
Split the Array
Easy
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p> <ul> <li><code>nums1.length == nums2.length == nums.length / 2</code>.</li> <li><code>nums1</code> should contain <strong>distinct </strong>elements.</li> <li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li> </ul> <p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,2,3,4] <strong>Output:</strong> true <strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1] <strong>Output:</strong> false <strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums.length % 2 == 0 </code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Hash Table; Counting
Go
func isPossibleToSplit(nums []int) bool { cnt := [101]int{} for _, x := range nums { cnt[x]++ if cnt[x] >= 3 { return false } } return true }
3,046
Split the Array
Easy
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p> <ul> <li><code>nums1.length == nums2.length == nums.length / 2</code>.</li> <li><code>nums1</code> should contain <strong>distinct </strong>elements.</li> <li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li> </ul> <p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,2,3,4] <strong>Output:</strong> true <strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1] <strong>Output:</strong> false <strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums.length % 2 == 0 </code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Hash Table; Counting
Java
class Solution { public boolean isPossibleToSplit(int[] nums) { int[] cnt = new int[101]; for (int x : nums) { if (++cnt[x] >= 3) { return false; } } return true; } }
3,046
Split the Array
Easy
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p> <ul> <li><code>nums1.length == nums2.length == nums.length / 2</code>.</li> <li><code>nums1</code> should contain <strong>distinct </strong>elements.</li> <li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li> </ul> <p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,2,3,4] <strong>Output:</strong> true <strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1] <strong>Output:</strong> false <strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums.length % 2 == 0 </code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Hash Table; Counting
Python
class Solution: def isPossibleToSplit(self, nums: List[int]) -> bool: return max(Counter(nums).values()) < 3
3,046
Split the Array
Easy
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p> <ul> <li><code>nums1.length == nums2.length == nums.length / 2</code>.</li> <li><code>nums1</code> should contain <strong>distinct </strong>elements.</li> <li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li> </ul> <p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,2,3,4] <strong>Output:</strong> true <strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1] <strong>Output:</strong> false <strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums.length % 2 == 0 </code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Hash Table; Counting
Rust
use std::collections::HashMap; impl Solution { pub fn is_possible_to_split(nums: Vec<i32>) -> bool { let mut cnt = HashMap::new(); for &x in &nums { *cnt.entry(x).or_insert(0) += 1; } *cnt.values().max().unwrap_or(&0) < 3 } }
3,046
Split the Array
Easy
<p>You are given an integer array <code>nums</code> of <strong>even</strong> length. You have to split the array into two parts <code>nums1</code> and <code>nums2</code> such that:</p> <ul> <li><code>nums1.length == nums2.length == nums.length / 2</code>.</li> <li><code>nums1</code> should contain <strong>distinct </strong>elements.</li> <li><code>nums2</code> should also contain <strong>distinct</strong> elements.</li> </ul> <p>Return <code>true</code><em> if it is possible to split the array, and </em><code>false</code> <em>otherwise</em><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,2,2,3,4] <strong>Output:</strong> true <strong>Explanation:</strong> One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1,1] <strong>Output:</strong> false <strong>Explanation:</strong> The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>nums.length % 2 == 0 </code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Hash Table; Counting
TypeScript
function isPossibleToSplit(nums: number[]): boolean { const cnt: number[] = Array(101).fill(0); for (const x of nums) { if (++cnt[x] >= 3) { return false; } } return true; }
3,047
Find the Largest Area of Square Inside Two Rectangles
Medium
<p>There exist <code>n</code> rectangles in a 2D plane with edges parallel to the x and y axis. You are given two 2D integer arrays&nbsp;<code>bottomLeft</code> and <code>topRight</code>&nbsp;where <code>bottomLeft[i] = [a_i, b_i]</code> and <code>topRight[i] = [c_i, d_i]</code> represent&nbsp;the <strong>bottom-left</strong> and <strong>top-right</strong> coordinates of the <code>i<sup>th</sup></code> rectangle, respectively.</p> <p>You need to find the <strong>maximum</strong> area of a <strong>square</strong> that can fit inside the intersecting region of at least two rectangles. Return <code>0</code> if such a square does not exist.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/example12.png" style="width: 443px; height: 364px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[3,1]], topRight = [[3,3],[4,4],[6,6]]</p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>A square with side length 1 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 1. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/diag.png" style="width: 451px; height: 470px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <p><strong>Input:</strong> bottomLeft = [[1,1],[1,3],[1,5]], topRight = [[5,5],[5,7],[5,9]]</p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <p>A square with side length 2 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is <code>2 * 2 = 4</code>. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p> <p><strong class="example">Example 3:</strong></p> <code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 445px; height: 365px;" /> </code> <p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[1,2]], topRight = [[3,3],[4,4],[3,4]]</p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>A square with side length 1 can fit inside the intersecting region of any two rectangles. Also, no larger square can, so the maximum area is 1. Note that the region can be formed by the intersection of more than 2 rectangles.</p> <p><strong class="example">Example 4:</strong></p> <code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 444px; height: 364px;" /> </code> <p><strong>Input:&nbsp;</strong>bottomLeft = [[1,1],[3,3],[3,1]], topRight = [[2,2],[4,4],[4,2]]</p> <p><strong>Output:</strong> 0</p> <p><strong>Explanation:</strong></p> <p>No pair of rectangles intersect, hence, the answer is 0.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == bottomLeft.length == topRight.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>3</sup></code></li> <li><code>bottomLeft[i].length == topRight[i].length == 2</code></li> <li><code>1 &lt;= bottomLeft[i][0], bottomLeft[i][1] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= topRight[i][0], topRight[i][1] &lt;= 10<sup>7</sup></code></li> <li><code>bottomLeft[i][0] &lt; topRight[i][0]</code></li> <li><code>bottomLeft[i][1] &lt; topRight[i][1]</code></li> </ul>
Geometry; Array; Math
C++
class Solution { public: long long largestSquareArea(vector<vector<int>>& bottomLeft, vector<vector<int>>& topRight) { long long ans = 0; for (int i = 0; i < bottomLeft.size(); ++i) { int x1 = bottomLeft[i][0], y1 = bottomLeft[i][1]; int x2 = topRight[i][0], y2 = topRight[i][1]; for (int j = i + 1; j < bottomLeft.size(); ++j) { int x3 = bottomLeft[j][0], y3 = bottomLeft[j][1]; int x4 = topRight[j][0], y4 = topRight[j][1]; int w = min(x2, x4) - max(x1, x3); int h = min(y2, y4) - max(y1, y3); int e = min(w, h); if (e > 0) { ans = max(ans, 1LL * e * e); } } } return ans; } };
3,047
Find the Largest Area of Square Inside Two Rectangles
Medium
<p>There exist <code>n</code> rectangles in a 2D plane with edges parallel to the x and y axis. You are given two 2D integer arrays&nbsp;<code>bottomLeft</code> and <code>topRight</code>&nbsp;where <code>bottomLeft[i] = [a_i, b_i]</code> and <code>topRight[i] = [c_i, d_i]</code> represent&nbsp;the <strong>bottom-left</strong> and <strong>top-right</strong> coordinates of the <code>i<sup>th</sup></code> rectangle, respectively.</p> <p>You need to find the <strong>maximum</strong> area of a <strong>square</strong> that can fit inside the intersecting region of at least two rectangles. Return <code>0</code> if such a square does not exist.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/example12.png" style="width: 443px; height: 364px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[3,1]], topRight = [[3,3],[4,4],[6,6]]</p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>A square with side length 1 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 1. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/diag.png" style="width: 451px; height: 470px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <p><strong>Input:</strong> bottomLeft = [[1,1],[1,3],[1,5]], topRight = [[5,5],[5,7],[5,9]]</p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <p>A square with side length 2 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is <code>2 * 2 = 4</code>. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p> <p><strong class="example">Example 3:</strong></p> <code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 445px; height: 365px;" /> </code> <p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[1,2]], topRight = [[3,3],[4,4],[3,4]]</p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>A square with side length 1 can fit inside the intersecting region of any two rectangles. Also, no larger square can, so the maximum area is 1. Note that the region can be formed by the intersection of more than 2 rectangles.</p> <p><strong class="example">Example 4:</strong></p> <code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 444px; height: 364px;" /> </code> <p><strong>Input:&nbsp;</strong>bottomLeft = [[1,1],[3,3],[3,1]], topRight = [[2,2],[4,4],[4,2]]</p> <p><strong>Output:</strong> 0</p> <p><strong>Explanation:</strong></p> <p>No pair of rectangles intersect, hence, the answer is 0.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == bottomLeft.length == topRight.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>3</sup></code></li> <li><code>bottomLeft[i].length == topRight[i].length == 2</code></li> <li><code>1 &lt;= bottomLeft[i][0], bottomLeft[i][1] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= topRight[i][0], topRight[i][1] &lt;= 10<sup>7</sup></code></li> <li><code>bottomLeft[i][0] &lt; topRight[i][0]</code></li> <li><code>bottomLeft[i][1] &lt; topRight[i][1]</code></li> </ul>
Geometry; Array; Math
Go
func largestSquareArea(bottomLeft [][]int, topRight [][]int) (ans int64) { for i, b1 := range bottomLeft { t1 := topRight[i] x1, y1 := b1[0], b1[1] x2, y2 := t1[0], t1[1] for j := i + 1; j < len(bottomLeft); j++ { x3, y3 := bottomLeft[j][0], bottomLeft[j][1] x4, y4 := topRight[j][0], topRight[j][1] w := min(x2, x4) - max(x1, x3) h := min(y2, y4) - max(y1, y3) e := min(w, h) if e > 0 { ans = max(ans, int64(e)*int64(e)) } } } return }
3,047
Find the Largest Area of Square Inside Two Rectangles
Medium
<p>There exist <code>n</code> rectangles in a 2D plane with edges parallel to the x and y axis. You are given two 2D integer arrays&nbsp;<code>bottomLeft</code> and <code>topRight</code>&nbsp;where <code>bottomLeft[i] = [a_i, b_i]</code> and <code>topRight[i] = [c_i, d_i]</code> represent&nbsp;the <strong>bottom-left</strong> and <strong>top-right</strong> coordinates of the <code>i<sup>th</sup></code> rectangle, respectively.</p> <p>You need to find the <strong>maximum</strong> area of a <strong>square</strong> that can fit inside the intersecting region of at least two rectangles. Return <code>0</code> if such a square does not exist.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/example12.png" style="width: 443px; height: 364px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[3,1]], topRight = [[3,3],[4,4],[6,6]]</p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>A square with side length 1 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 1. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/diag.png" style="width: 451px; height: 470px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <p><strong>Input:</strong> bottomLeft = [[1,1],[1,3],[1,5]], topRight = [[5,5],[5,7],[5,9]]</p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <p>A square with side length 2 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is <code>2 * 2 = 4</code>. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p> <p><strong class="example">Example 3:</strong></p> <code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 445px; height: 365px;" /> </code> <p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[1,2]], topRight = [[3,3],[4,4],[3,4]]</p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>A square with side length 1 can fit inside the intersecting region of any two rectangles. Also, no larger square can, so the maximum area is 1. Note that the region can be formed by the intersection of more than 2 rectangles.</p> <p><strong class="example">Example 4:</strong></p> <code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 444px; height: 364px;" /> </code> <p><strong>Input:&nbsp;</strong>bottomLeft = [[1,1],[3,3],[3,1]], topRight = [[2,2],[4,4],[4,2]]</p> <p><strong>Output:</strong> 0</p> <p><strong>Explanation:</strong></p> <p>No pair of rectangles intersect, hence, the answer is 0.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == bottomLeft.length == topRight.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>3</sup></code></li> <li><code>bottomLeft[i].length == topRight[i].length == 2</code></li> <li><code>1 &lt;= bottomLeft[i][0], bottomLeft[i][1] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= topRight[i][0], topRight[i][1] &lt;= 10<sup>7</sup></code></li> <li><code>bottomLeft[i][0] &lt; topRight[i][0]</code></li> <li><code>bottomLeft[i][1] &lt; topRight[i][1]</code></li> </ul>
Geometry; Array; Math
Java
class Solution { public long largestSquareArea(int[][] bottomLeft, int[][] topRight) { long ans = 0; for (int i = 0; i < bottomLeft.length; ++i) { int x1 = bottomLeft[i][0], y1 = bottomLeft[i][1]; int x2 = topRight[i][0], y2 = topRight[i][1]; for (int j = i + 1; j < bottomLeft.length; ++j) { int x3 = bottomLeft[j][0], y3 = bottomLeft[j][1]; int x4 = topRight[j][0], y4 = topRight[j][1]; int w = Math.min(x2, x4) - Math.max(x1, x3); int h = Math.min(y2, y4) - Math.max(y1, y3); int e = Math.min(w, h); if (e > 0) { ans = Math.max(ans, 1L * e * e); } } } return ans; } }
3,047
Find the Largest Area of Square Inside Two Rectangles
Medium
<p>There exist <code>n</code> rectangles in a 2D plane with edges parallel to the x and y axis. You are given two 2D integer arrays&nbsp;<code>bottomLeft</code> and <code>topRight</code>&nbsp;where <code>bottomLeft[i] = [a_i, b_i]</code> and <code>topRight[i] = [c_i, d_i]</code> represent&nbsp;the <strong>bottom-left</strong> and <strong>top-right</strong> coordinates of the <code>i<sup>th</sup></code> rectangle, respectively.</p> <p>You need to find the <strong>maximum</strong> area of a <strong>square</strong> that can fit inside the intersecting region of at least two rectangles. Return <code>0</code> if such a square does not exist.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/example12.png" style="width: 443px; height: 364px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[3,1]], topRight = [[3,3],[4,4],[6,6]]</p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>A square with side length 1 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 1. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/diag.png" style="width: 451px; height: 470px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <p><strong>Input:</strong> bottomLeft = [[1,1],[1,3],[1,5]], topRight = [[5,5],[5,7],[5,9]]</p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <p>A square with side length 2 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is <code>2 * 2 = 4</code>. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p> <p><strong class="example">Example 3:</strong></p> <code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 445px; height: 365px;" /> </code> <p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[1,2]], topRight = [[3,3],[4,4],[3,4]]</p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>A square with side length 1 can fit inside the intersecting region of any two rectangles. Also, no larger square can, so the maximum area is 1. Note that the region can be formed by the intersection of more than 2 rectangles.</p> <p><strong class="example">Example 4:</strong></p> <code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 444px; height: 364px;" /> </code> <p><strong>Input:&nbsp;</strong>bottomLeft = [[1,1],[3,3],[3,1]], topRight = [[2,2],[4,4],[4,2]]</p> <p><strong>Output:</strong> 0</p> <p><strong>Explanation:</strong></p> <p>No pair of rectangles intersect, hence, the answer is 0.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == bottomLeft.length == topRight.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>3</sup></code></li> <li><code>bottomLeft[i].length == topRight[i].length == 2</code></li> <li><code>1 &lt;= bottomLeft[i][0], bottomLeft[i][1] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= topRight[i][0], topRight[i][1] &lt;= 10<sup>7</sup></code></li> <li><code>bottomLeft[i][0] &lt; topRight[i][0]</code></li> <li><code>bottomLeft[i][1] &lt; topRight[i][1]</code></li> </ul>
Geometry; Array; Math
Python
class Solution: def largestSquareArea( self, bottomLeft: List[List[int]], topRight: List[List[int]] ) -> int: ans = 0 for ((x1, y1), (x2, y2)), ((x3, y3), (x4, y4)) in combinations( zip(bottomLeft, topRight), 2 ): w = min(x2, x4) - max(x1, x3) h = min(y2, y4) - max(y1, y3) e = min(w, h) if e > 0: ans = max(ans, e * e) return ans
3,047
Find the Largest Area of Square Inside Two Rectangles
Medium
<p>There exist <code>n</code> rectangles in a 2D plane with edges parallel to the x and y axis. You are given two 2D integer arrays&nbsp;<code>bottomLeft</code> and <code>topRight</code>&nbsp;where <code>bottomLeft[i] = [a_i, b_i]</code> and <code>topRight[i] = [c_i, d_i]</code> represent&nbsp;the <strong>bottom-left</strong> and <strong>top-right</strong> coordinates of the <code>i<sup>th</sup></code> rectangle, respectively.</p> <p>You need to find the <strong>maximum</strong> area of a <strong>square</strong> that can fit inside the intersecting region of at least two rectangles. Return <code>0</code> if such a square does not exist.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/example12.png" style="width: 443px; height: 364px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[3,1]], topRight = [[3,3],[4,4],[6,6]]</p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>A square with side length 1 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 1. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/diag.png" style="width: 451px; height: 470px; padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem;" /> <p><strong>Input:</strong> bottomLeft = [[1,1],[1,3],[1,5]], topRight = [[5,5],[5,7],[5,9]]</p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <p>A square with side length 2 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is <code>2 * 2 = 4</code>. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.</p> <p><strong class="example">Example 3:</strong></p> <code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample2.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 445px; height: 365px;" /> </code> <p><strong>Input:</strong> bottomLeft = [[1,1],[2,2],[1,2]], topRight = [[3,3],[4,4],[3,4]]</p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>A square with side length 1 can fit inside the intersecting region of any two rectangles. Also, no larger square can, so the maximum area is 1. Note that the region can be formed by the intersection of more than 2 rectangles.</p> <p><strong class="example">Example 4:</strong></p> <code> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3000-3099/3047.Find%20the%20Largest%20Area%20of%20Square%20Inside%20Two%20Rectangles/images/rectanglesexample3.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 444px; height: 364px;" /> </code> <p><strong>Input:&nbsp;</strong>bottomLeft = [[1,1],[3,3],[3,1]], topRight = [[2,2],[4,4],[4,2]]</p> <p><strong>Output:</strong> 0</p> <p><strong>Explanation:</strong></p> <p>No pair of rectangles intersect, hence, the answer is 0.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == bottomLeft.length == topRight.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>3</sup></code></li> <li><code>bottomLeft[i].length == topRight[i].length == 2</code></li> <li><code>1 &lt;= bottomLeft[i][0], bottomLeft[i][1] &lt;= 10<sup>7</sup></code></li> <li><code>1 &lt;= topRight[i][0], topRight[i][1] &lt;= 10<sup>7</sup></code></li> <li><code>bottomLeft[i][0] &lt; topRight[i][0]</code></li> <li><code>bottomLeft[i][1] &lt; topRight[i][1]</code></li> </ul>
Geometry; Array; Math
TypeScript
function largestSquareArea(bottomLeft: number[][], topRight: number[][]): number { let ans = 0; for (let i = 0; i < bottomLeft.length; ++i) { const [x1, y1] = bottomLeft[i]; const [x2, y2] = topRight[i]; for (let j = i + 1; j < bottomLeft.length; ++j) { const [x3, y3] = bottomLeft[j]; const [x4, y4] = topRight[j]; const w = Math.min(x2, x4) - Math.max(x1, x3); const h = Math.min(y2, y4) - Math.max(y1, y3); const e = Math.min(w, h); if (e > 0) { ans = Math.max(ans, e * e); } } } return ans; }
3,048
Earliest Second to Mark Indices I
Medium
<p>You are given two <strong>1-indexed</strong> integer arrays, <code>nums</code> and, <code>changeIndices</code>, having lengths <code>n</code> and <code>m</code>, respectively.</p> <p>Initially, all indices in <code>nums</code> are unmarked. Your task is to mark <strong>all</strong> indices in <code>nums</code>.</p> <p>In each second, <code>s</code>, in order from <code>1</code> to <code>m</code> (<strong>inclusive</strong>), you can perform <strong>one</strong> of the following operations:</p> <ul> <li>Choose an index <code>i</code> in the range <code>[1, n]</code> and <strong>decrement</strong> <code>nums[i]</code> by <code>1</code>.</li> <li>If <code>nums[changeIndices[s]]</code> is <strong>equal</strong> to <code>0</code>, <strong>mark</strong> the index <code>changeIndices[s]</code>.</li> <li>Do nothing.</li> </ul> <p>Return <em>an integer denoting the <strong>earliest second</strong> in the range </em><code>[1, m]</code><em> when <strong>all</strong> indices in </em><code>nums</code><em> can be marked by choosing operations optimally, or </em><code>-1</code><em> if it is impossible.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,0], changeIndices = [2,2,2,2,3,2,2,1] <strong>Output:</strong> 8 <strong>Explanation:</strong> In this example, we have 8 seconds. The following operations can be performed to mark all indices: Second 1: Choose index 1 and decrement nums[1] by one. nums becomes [1,2,0]. Second 2: Choose index 1 and decrement nums[1] by one. nums becomes [0,2,0]. Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [0,1,0]. Second 4: Choose index 2 and decrement nums[2] by one. nums becomes [0,0,0]. Second 5: Mark the index changeIndices[5], which is marking index 3, since nums[3] is equal to 0. Second 6: Mark the index changeIndices[6], which is marking index 2, since nums[2] is equal to 0. Second 7: Do nothing. Second 8: Mark the index changeIndices[8], which is marking index 1, since nums[1] is equal to 0. Now all indices have been marked. It can be shown that it is not possible to mark all indices earlier than the 8th second. Hence, the answer is 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3], changeIndices = [1,1,1,2,1,1,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> In this example, we have 7 seconds. The following operations can be performed to mark all indices: Second 1: Choose index 2 and decrement nums[2] by one. nums becomes [1,2]. Second 2: Choose index 2 and decrement nums[2] by one. nums becomes [1,1]. Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [1,0]. Second 4: Mark the index changeIndices[4], which is marking index 2, since nums[2] is equal to 0. Second 5: Choose index 1 and decrement nums[1] by one. nums becomes [0,0]. Second 6: Mark the index changeIndices[6], which is marking index 1, since nums[1] is equal to 0. Now all indices have been marked. It can be shown that it is not possible to mark all indices earlier than the 6th second. Hence, the answer is 6. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1], changeIndices = [2,2,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> In this example, it is impossible to mark all indices because index 1 isn&#39;t in changeIndices. Hence, the answer is -1. </pre> <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;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == changeIndices.length &lt;= 2000</code></li> <li><code>1 &lt;= changeIndices[i] &lt;= n</code></li> </ul>
Array; Binary Search
C++
class Solution { public: int earliestSecondToMarkIndices(vector<int>& nums, vector<int>& changeIndices) { int n = nums.size(); int last[n + 1]; auto check = [&](int t) { memset(last, 0, sizeof(last)); for (int s = 0; s < t; ++s) { last[changeIndices[s]] = s; } int decrement = 0, marked = 0; for (int s = 0; s < t; ++s) { int i = changeIndices[s]; if (last[i] == s) { if (decrement < nums[i - 1]) { return false; } decrement -= nums[i - 1]; ++marked; } else { ++decrement; } } return marked == n; }; int m = changeIndices.size(); int l = 1, r = m + 1; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l > m ? -1 : l; } };
3,048
Earliest Second to Mark Indices I
Medium
<p>You are given two <strong>1-indexed</strong> integer arrays, <code>nums</code> and, <code>changeIndices</code>, having lengths <code>n</code> and <code>m</code>, respectively.</p> <p>Initially, all indices in <code>nums</code> are unmarked. Your task is to mark <strong>all</strong> indices in <code>nums</code>.</p> <p>In each second, <code>s</code>, in order from <code>1</code> to <code>m</code> (<strong>inclusive</strong>), you can perform <strong>one</strong> of the following operations:</p> <ul> <li>Choose an index <code>i</code> in the range <code>[1, n]</code> and <strong>decrement</strong> <code>nums[i]</code> by <code>1</code>.</li> <li>If <code>nums[changeIndices[s]]</code> is <strong>equal</strong> to <code>0</code>, <strong>mark</strong> the index <code>changeIndices[s]</code>.</li> <li>Do nothing.</li> </ul> <p>Return <em>an integer denoting the <strong>earliest second</strong> in the range </em><code>[1, m]</code><em> when <strong>all</strong> indices in </em><code>nums</code><em> can be marked by choosing operations optimally, or </em><code>-1</code><em> if it is impossible.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,0], changeIndices = [2,2,2,2,3,2,2,1] <strong>Output:</strong> 8 <strong>Explanation:</strong> In this example, we have 8 seconds. The following operations can be performed to mark all indices: Second 1: Choose index 1 and decrement nums[1] by one. nums becomes [1,2,0]. Second 2: Choose index 1 and decrement nums[1] by one. nums becomes [0,2,0]. Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [0,1,0]. Second 4: Choose index 2 and decrement nums[2] by one. nums becomes [0,0,0]. Second 5: Mark the index changeIndices[5], which is marking index 3, since nums[3] is equal to 0. Second 6: Mark the index changeIndices[6], which is marking index 2, since nums[2] is equal to 0. Second 7: Do nothing. Second 8: Mark the index changeIndices[8], which is marking index 1, since nums[1] is equal to 0. Now all indices have been marked. It can be shown that it is not possible to mark all indices earlier than the 8th second. Hence, the answer is 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3], changeIndices = [1,1,1,2,1,1,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> In this example, we have 7 seconds. The following operations can be performed to mark all indices: Second 1: Choose index 2 and decrement nums[2] by one. nums becomes [1,2]. Second 2: Choose index 2 and decrement nums[2] by one. nums becomes [1,1]. Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [1,0]. Second 4: Mark the index changeIndices[4], which is marking index 2, since nums[2] is equal to 0. Second 5: Choose index 1 and decrement nums[1] by one. nums becomes [0,0]. Second 6: Mark the index changeIndices[6], which is marking index 1, since nums[1] is equal to 0. Now all indices have been marked. It can be shown that it is not possible to mark all indices earlier than the 6th second. Hence, the answer is 6. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1], changeIndices = [2,2,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> In this example, it is impossible to mark all indices because index 1 isn&#39;t in changeIndices. Hence, the answer is -1. </pre> <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;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == changeIndices.length &lt;= 2000</code></li> <li><code>1 &lt;= changeIndices[i] &lt;= n</code></li> </ul>
Array; Binary Search
Go
func earliestSecondToMarkIndices(nums []int, changeIndices []int) int { n, m := len(nums), len(changeIndices) l := sort.Search(m+1, func(t int) bool { last := make([]int, n+1) for s, i := range changeIndices[:t] { last[i] = s } decrement, marked := 0, 0 for s, i := range changeIndices[:t] { if last[i] == s { if decrement < nums[i-1] { return false } decrement -= nums[i-1] marked++ } else { decrement++ } } return marked == n }) if l > m { return -1 } return l }
3,048
Earliest Second to Mark Indices I
Medium
<p>You are given two <strong>1-indexed</strong> integer arrays, <code>nums</code> and, <code>changeIndices</code>, having lengths <code>n</code> and <code>m</code>, respectively.</p> <p>Initially, all indices in <code>nums</code> are unmarked. Your task is to mark <strong>all</strong> indices in <code>nums</code>.</p> <p>In each second, <code>s</code>, in order from <code>1</code> to <code>m</code> (<strong>inclusive</strong>), you can perform <strong>one</strong> of the following operations:</p> <ul> <li>Choose an index <code>i</code> in the range <code>[1, n]</code> and <strong>decrement</strong> <code>nums[i]</code> by <code>1</code>.</li> <li>If <code>nums[changeIndices[s]]</code> is <strong>equal</strong> to <code>0</code>, <strong>mark</strong> the index <code>changeIndices[s]</code>.</li> <li>Do nothing.</li> </ul> <p>Return <em>an integer denoting the <strong>earliest second</strong> in the range </em><code>[1, m]</code><em> when <strong>all</strong> indices in </em><code>nums</code><em> can be marked by choosing operations optimally, or </em><code>-1</code><em> if it is impossible.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,0], changeIndices = [2,2,2,2,3,2,2,1] <strong>Output:</strong> 8 <strong>Explanation:</strong> In this example, we have 8 seconds. The following operations can be performed to mark all indices: Second 1: Choose index 1 and decrement nums[1] by one. nums becomes [1,2,0]. Second 2: Choose index 1 and decrement nums[1] by one. nums becomes [0,2,0]. Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [0,1,0]. Second 4: Choose index 2 and decrement nums[2] by one. nums becomes [0,0,0]. Second 5: Mark the index changeIndices[5], which is marking index 3, since nums[3] is equal to 0. Second 6: Mark the index changeIndices[6], which is marking index 2, since nums[2] is equal to 0. Second 7: Do nothing. Second 8: Mark the index changeIndices[8], which is marking index 1, since nums[1] is equal to 0. Now all indices have been marked. It can be shown that it is not possible to mark all indices earlier than the 8th second. Hence, the answer is 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3], changeIndices = [1,1,1,2,1,1,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> In this example, we have 7 seconds. The following operations can be performed to mark all indices: Second 1: Choose index 2 and decrement nums[2] by one. nums becomes [1,2]. Second 2: Choose index 2 and decrement nums[2] by one. nums becomes [1,1]. Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [1,0]. Second 4: Mark the index changeIndices[4], which is marking index 2, since nums[2] is equal to 0. Second 5: Choose index 1 and decrement nums[1] by one. nums becomes [0,0]. Second 6: Mark the index changeIndices[6], which is marking index 1, since nums[1] is equal to 0. Now all indices have been marked. It can be shown that it is not possible to mark all indices earlier than the 6th second. Hence, the answer is 6. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1], changeIndices = [2,2,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> In this example, it is impossible to mark all indices because index 1 isn&#39;t in changeIndices. Hence, the answer is -1. </pre> <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;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == changeIndices.length &lt;= 2000</code></li> <li><code>1 &lt;= changeIndices[i] &lt;= n</code></li> </ul>
Array; Binary Search
Java
class Solution { private int[] nums; private int[] changeIndices; public int earliestSecondToMarkIndices(int[] nums, int[] changeIndices) { this.nums = nums; this.changeIndices = changeIndices; int m = changeIndices.length; int l = 1, r = m + 1; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l > m ? -1 : l; } private boolean check(int t) { int[] last = new int[nums.length + 1]; for (int s = 0; s < t; ++s) { last[changeIndices[s]] = s; } int decrement = 0; int marked = 0; for (int s = 0; s < t; ++s) { int i = changeIndices[s]; if (last[i] == s) { if (decrement < nums[i - 1]) { return false; } decrement -= nums[i - 1]; ++marked; } else { ++decrement; } } return marked == nums.length; } }
3,048
Earliest Second to Mark Indices I
Medium
<p>You are given two <strong>1-indexed</strong> integer arrays, <code>nums</code> and, <code>changeIndices</code>, having lengths <code>n</code> and <code>m</code>, respectively.</p> <p>Initially, all indices in <code>nums</code> are unmarked. Your task is to mark <strong>all</strong> indices in <code>nums</code>.</p> <p>In each second, <code>s</code>, in order from <code>1</code> to <code>m</code> (<strong>inclusive</strong>), you can perform <strong>one</strong> of the following operations:</p> <ul> <li>Choose an index <code>i</code> in the range <code>[1, n]</code> and <strong>decrement</strong> <code>nums[i]</code> by <code>1</code>.</li> <li>If <code>nums[changeIndices[s]]</code> is <strong>equal</strong> to <code>0</code>, <strong>mark</strong> the index <code>changeIndices[s]</code>.</li> <li>Do nothing.</li> </ul> <p>Return <em>an integer denoting the <strong>earliest second</strong> in the range </em><code>[1, m]</code><em> when <strong>all</strong> indices in </em><code>nums</code><em> can be marked by choosing operations optimally, or </em><code>-1</code><em> if it is impossible.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,0], changeIndices = [2,2,2,2,3,2,2,1] <strong>Output:</strong> 8 <strong>Explanation:</strong> In this example, we have 8 seconds. The following operations can be performed to mark all indices: Second 1: Choose index 1 and decrement nums[1] by one. nums becomes [1,2,0]. Second 2: Choose index 1 and decrement nums[1] by one. nums becomes [0,2,0]. Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [0,1,0]. Second 4: Choose index 2 and decrement nums[2] by one. nums becomes [0,0,0]. Second 5: Mark the index changeIndices[5], which is marking index 3, since nums[3] is equal to 0. Second 6: Mark the index changeIndices[6], which is marking index 2, since nums[2] is equal to 0. Second 7: Do nothing. Second 8: Mark the index changeIndices[8], which is marking index 1, since nums[1] is equal to 0. Now all indices have been marked. It can be shown that it is not possible to mark all indices earlier than the 8th second. Hence, the answer is 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3], changeIndices = [1,1,1,2,1,1,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> In this example, we have 7 seconds. The following operations can be performed to mark all indices: Second 1: Choose index 2 and decrement nums[2] by one. nums becomes [1,2]. Second 2: Choose index 2 and decrement nums[2] by one. nums becomes [1,1]. Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [1,0]. Second 4: Mark the index changeIndices[4], which is marking index 2, since nums[2] is equal to 0. Second 5: Choose index 1 and decrement nums[1] by one. nums becomes [0,0]. Second 6: Mark the index changeIndices[6], which is marking index 1, since nums[1] is equal to 0. Now all indices have been marked. It can be shown that it is not possible to mark all indices earlier than the 6th second. Hence, the answer is 6. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1], changeIndices = [2,2,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> In this example, it is impossible to mark all indices because index 1 isn&#39;t in changeIndices. Hence, the answer is -1. </pre> <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;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == changeIndices.length &lt;= 2000</code></li> <li><code>1 &lt;= changeIndices[i] &lt;= n</code></li> </ul>
Array; Binary Search
Python
class Solution: def earliestSecondToMarkIndices( self, nums: List[int], changeIndices: List[int] ) -> int: def check(t: int) -> bool: decrement = 0 marked = 0 last = {i: s for s, i in enumerate(changeIndices[:t])} for s, i in enumerate(changeIndices[:t]): if last[i] == s: if decrement < nums[i - 1]: return False decrement -= nums[i - 1] marked += 1 else: decrement += 1 return marked == len(nums) m = len(changeIndices) l = bisect_left(range(1, m + 2), True, key=check) + 1 return -1 if l > m else l
3,048
Earliest Second to Mark Indices I
Medium
<p>You are given two <strong>1-indexed</strong> integer arrays, <code>nums</code> and, <code>changeIndices</code>, having lengths <code>n</code> and <code>m</code>, respectively.</p> <p>Initially, all indices in <code>nums</code> are unmarked. Your task is to mark <strong>all</strong> indices in <code>nums</code>.</p> <p>In each second, <code>s</code>, in order from <code>1</code> to <code>m</code> (<strong>inclusive</strong>), you can perform <strong>one</strong> of the following operations:</p> <ul> <li>Choose an index <code>i</code> in the range <code>[1, n]</code> and <strong>decrement</strong> <code>nums[i]</code> by <code>1</code>.</li> <li>If <code>nums[changeIndices[s]]</code> is <strong>equal</strong> to <code>0</code>, <strong>mark</strong> the index <code>changeIndices[s]</code>.</li> <li>Do nothing.</li> </ul> <p>Return <em>an integer denoting the <strong>earliest second</strong> in the range </em><code>[1, m]</code><em> when <strong>all</strong> indices in </em><code>nums</code><em> can be marked by choosing operations optimally, or </em><code>-1</code><em> if it is impossible.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,0], changeIndices = [2,2,2,2,3,2,2,1] <strong>Output:</strong> 8 <strong>Explanation:</strong> In this example, we have 8 seconds. The following operations can be performed to mark all indices: Second 1: Choose index 1 and decrement nums[1] by one. nums becomes [1,2,0]. Second 2: Choose index 1 and decrement nums[1] by one. nums becomes [0,2,0]. Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [0,1,0]. Second 4: Choose index 2 and decrement nums[2] by one. nums becomes [0,0,0]. Second 5: Mark the index changeIndices[5], which is marking index 3, since nums[3] is equal to 0. Second 6: Mark the index changeIndices[6], which is marking index 2, since nums[2] is equal to 0. Second 7: Do nothing. Second 8: Mark the index changeIndices[8], which is marking index 1, since nums[1] is equal to 0. Now all indices have been marked. It can be shown that it is not possible to mark all indices earlier than the 8th second. Hence, the answer is 8. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3], changeIndices = [1,1,1,2,1,1,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> In this example, we have 7 seconds. The following operations can be performed to mark all indices: Second 1: Choose index 2 and decrement nums[2] by one. nums becomes [1,2]. Second 2: Choose index 2 and decrement nums[2] by one. nums becomes [1,1]. Second 3: Choose index 2 and decrement nums[2] by one. nums becomes [1,0]. Second 4: Mark the index changeIndices[4], which is marking index 2, since nums[2] is equal to 0. Second 5: Choose index 1 and decrement nums[1] by one. nums becomes [0,0]. Second 6: Mark the index changeIndices[6], which is marking index 1, since nums[1] is equal to 0. Now all indices have been marked. It can be shown that it is not possible to mark all indices earlier than the 6th second. Hence, the answer is 6. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,1], changeIndices = [2,2,2] <strong>Output:</strong> -1 <strong>Explanation:</strong> In this example, it is impossible to mark all indices because index 1 isn&#39;t in changeIndices. Hence, the answer is -1. </pre> <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;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m == changeIndices.length &lt;= 2000</code></li> <li><code>1 &lt;= changeIndices[i] &lt;= n</code></li> </ul>
Array; Binary Search
TypeScript
function earliestSecondToMarkIndices(nums: number[], changeIndices: number[]): number { const [n, m] = [nums.length, changeIndices.length]; let [l, r] = [1, m + 1]; const check = (t: number): boolean => { const last: number[] = Array(n + 1).fill(0); for (let s = 0; s < t; ++s) { last[changeIndices[s]] = s; } let [decrement, marked] = [0, 0]; for (let s = 0; s < t; ++s) { const i = changeIndices[s]; if (last[i] === s) { if (decrement < nums[i - 1]) { return false; } decrement -= nums[i - 1]; ++marked; } else { ++decrement; } } return marked === n; }; while (l < r) { const mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l > m ? -1 : l; }
3,050
Pizza Toppings Cost Analysis
Medium
<p>Table: <code><font face="monospace">Toppings</font></code></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | topping_name | varchar | | cost | decimal | +--------------+---------+ topping_name is the primary key for this table. Each row of this table contains topping name and the cost of the topping. </pre> <p>Write a solution to calculate the <strong>total cost</strong> of <strong>all possible <code>3</code>-topping</strong> pizza combinations from a given list of toppings. The total cost of toppings must be <strong>rounded</strong> to <code>2</code> <strong>decimal</strong> places.</p> <p><strong>Note:</strong></p> <ul> <li><strong>Do not</strong> include the pizzas where a topping is <strong>repeated</strong>. For example, &lsquo;Pepperoni, Pepperoni, Onion Pizza&rsquo;.</li> <li>Toppings <strong>must be</strong> listed in <strong>alphabetical order</strong>. For example, &#39;Chicken, Onions, Sausage&#39;. &#39;Onion, Sausage, Chicken&#39; is not acceptable.</li> </ul> <p>Return<em> the result table ordered by total cost in</em> <em><strong>descending</strong></em> <em>order and combination of toppings 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 1:</strong></p> <pre> <strong>Input:</strong> Toppings table: +--------------+------+ | topping_name | cost | +--------------+------+ | Pepperoni | 0.50 | | Sausage | 0.70 | | Chicken | 0.55 | | Extra Cheese | 0.40 | +--------------+------+ <strong>Output:</strong> +--------------------------------+------------+ | pizza | total_cost | +--------------------------------+------------+ | Chicken,Pepperoni,Sausage | 1.75 | | Chicken,Extra Cheese,Sausage | 1.65 | | Extra Cheese,Pepperoni,Sausage | 1.60 | | Chicken,Extra Cheese,Pepperoni | 1.45 | +--------------------------------+------------+ <strong>Explanation:</strong> There are only four different combinations possible with the three topings: - Chicken, Pepperoni, Sausage: Total cost is $1.75 (Chicken $0.55, Pepperoni $0.50, Sausage $0.70). - Chicken, Extra Cheese, Sausage: Total cost is $1.65 (Chicken $0.55, Extra Cheese $0.40, Sausage $0.70). - Extra Cheese, Pepperoni, Sausage: Total cost is $1.60 (Extra Cheese $0.40, Pepperoni $0.50, Sausage $0.70). - Chicken, Extra Cheese, Pepperoni: Total cost is $1.45 (Chicken $0.55, Extra Cheese $0.40, Pepperoni $0.50). Output table is ordered by the total cost in descending order.</pre>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT *, RANK() OVER (ORDER BY topping_name) AS rk FROM Toppings ) SELECT CONCAT(t1.topping_name, ',', t2.topping_name, ',', t3.topping_name) AS pizza, t1.cost + t2.cost + t3.cost AS total_cost FROM T AS t1 JOIN T AS t2 ON t1.rk < t2.rk JOIN T AS t3 ON t2.rk < t3.rk ORDER BY 2 DESC, 1 ASC;
3,051
Find Candidates for Data Scientist Position
Easy
<p>Table: <font face="monospace"><code>Candidates</code></font></p> <pre> +--------------+---------+ | Column Name | Type | +--------------+---------+ | candidate_id | int | | skill | varchar | +--------------+---------+ (candidate_id, skill) is the primary key (columns with unique values) for this table. Each row includes candidate_id and skill. </pre> <p>Write a query to find the <strong>candidates</strong> best suited for a Data Scientist position. The candidate must be proficient in <strong>Python</strong>, <strong>Tableau</strong>, and <strong>PostgreSQL</strong>.</p> <p>Return <em>the result table ordered by </em><code>candidate_id</code> <em>in <strong>ascending order</strong></em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Candidates table: +---------------+--------------+ | candidate_id | skill | +---------------+--------------+ | 123 | Python | | 234 | R | | 123 | Tableau | | 123 | PostgreSQL | | 234 | PowerBI | | 234 | SQL Server | | 147 | Python | | 147 | Tableau | | 147 | Java | | 147 | PostgreSQL | | 256 | Tableau | | 102 | DataAnalysis | +---------------+--------------+ <strong>Output:</strong> +--------------+ | candidate_id | +--------------+ | 123 | | 147 | +--------------+ <strong>Explanation:</strong> - Candidates 123 and 147 possess the necessary skills in Python, Tableau, and PostgreSQL for the data scientist position. - Candidates 234 and 102 do not possess any of the required skills for this position. - Candidate 256 has proficiency in Tableau but is missing skills in Python and PostgreSQL. The output table is sorted by candidate_id in ascending order. </pre>
Database
SQL
# Write your MySQL query statement below SELECT candidate_id FROM Candidates WHERE skill IN ('Python', 'Tableau', 'PostgreSQL') GROUP BY 1 HAVING COUNT(1) = 3 ORDER BY 1;
3,052
Maximize Items
Hard
<p>Table: <font face="monospace"><code>Inventory</code></font></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | item_id | int | | item_type | varchar | | item_category | varchar | | square_footage | decimal | +----------------+---------+ item_id is the column of unique values for this table. Each row includes item id, item type, item category and sqaure footage. </pre> <p>Leetcode warehouse wants to maximize the number of items it can stock in a <code>500,000</code> square feet warehouse. It wants to stock as many <strong>prime</strong> items as possible, and afterwards use the <strong>remaining</strong> square footage to stock the most number of <strong>non-prime</strong> items.</p> <p>Write a solution to find the number of <strong>prime</strong> and <strong>non-prime</strong> items that can be <strong>stored</strong> in the <code>500,000</code> square feet warehouse. Output the item type with <code>prime_eligible</code> followed by <code>not_prime</code> and the maximum number of items that can be stocked.</p> <p><strong>Note:</strong></p> <ul> <li>Item <strong>count</strong> must be a whole number (integer).</li> <li>If the count for the <strong>not_prime</strong> category is <code>0</code>, you should <strong>output</strong> <code>0</code> for that particular category.</li> </ul> <p>Return <em>the result table ordered by item count in <strong>descending order</strong></em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Inventory table: +---------+----------------+---------------+----------------+ | item_id | item_type | item_category | square_footage | +---------+----------------+---------------+----------------+ | 1374 | prime_eligible | Watches | 68.00 | | 4245 | not_prime | Art | 26.40 | | 5743 | prime_eligible | Software | 325.00 | | 8543 | not_prime | Clothing | 64.50 | | 2556 | not_prime | Shoes | 15.00 | | 2452 | prime_eligible | Scientific | 85.00 | | 3255 | not_prime | Furniture | 22.60 | | 1672 | prime_eligible | Beauty | 8.50 | | 4256 | prime_eligible | Furniture | 55.50 | | 6325 | prime_eligible | Food | 13.20 | +---------+----------------+---------------+----------------+ <strong>Output:</strong> +----------------+-------------+ | item_type | item_count | +----------------+-------------+ | prime_eligible | 5400 | | not_prime | 8 | +----------------+-------------+ <strong>Explanation:</strong> - The prime-eligible category comprises a total of 6 items, amounting to a combined square footage of 555.20 (68 + 325 + 85 + 8.50 + 55.50 + 13.20). It is possible to store 900 combinations of these 6 items, totaling 5400 items and occupying 499,680 square footage. - In the not_prime category, there are a total of 4 items with a combined square footage of 128.50. After deducting the storage used by prime-eligible items (500,000 - 499,680 = 320), there is room for 2 combinations of non-prime items, accommodating a total of 8 non-prime items within the available 320 square footage. Output table is ordered by item count in descending order.</pre>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT SUM(square_footage) AS s FROM Inventory WHERE item_type = 'prime_eligible' ) SELECT 'prime_eligible' AS item_type, COUNT(1) * FLOOR(500000 / s) AS item_count FROM Inventory JOIN T WHERE item_type = 'prime_eligible' UNION ALL SELECT 'not_prime', IFNULL(COUNT(1) * FLOOR(IF(s = 0, 500000, 500000 % s) / SUM(square_footage)), 0) FROM Inventory JOIN T WHERE item_type = 'not_prime';