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
2,942
Find Words Containing Character
Easy
<p>You are given a <strong>0-indexed</strong> array of strings <code>words</code> and a character <code>x</code>.</p> <p>Return <em>an <strong>array of indices</strong> representing the words that contain the character </em><code>x</code>.</p> <p><strong>Note</strong> that the returned array may be in <strong>any</strong> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;leet&quot;,&quot;code&quot;], x = &quot;e&quot; <strong>Output:</strong> [0,1] <strong>Explanation:</strong> &quot;e&quot; occurs in both words: &quot;l<strong><u>ee</u></strong>t&quot;, and &quot;cod<u><strong>e</strong></u>&quot;. Hence, we return indices 0 and 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abc&quot;,&quot;bcd&quot;,&quot;aaaa&quot;,&quot;cbc&quot;], x = &quot;a&quot; <strong>Output:</strong> [0,2] <strong>Explanation:</strong> &quot;a&quot; occurs in &quot;<strong><u>a</u></strong>bc&quot;, and &quot;<u><strong>aaaa</strong></u>&quot;. Hence, we return indices 0 and 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;abc&quot;,&quot;bcd&quot;,&quot;aaaa&quot;,&quot;cbc&quot;], x = &quot;z&quot; <strong>Output:</strong> [] <strong>Explanation:</strong> &quot;z&quot; does not occur in any of the words. Hence, we return an empty array. </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;= 50</code></li> <li><code>x</code> is a lowercase English letter.</li> <li><code>words[i]</code> consists only of lowercase English letters.</li> </ul>
Array; String
TypeScript
function findWordsContaining(words: string[], x: string): number[] { return words.flatMap((w, i) => (w.includes(x) ? [i] : [])); }
2,943
Maximize Area of Square Hole in Grid
Medium
<p>You are given the two integers, <code>n</code> and <code>m</code> and two integer arrays, <code>hBars</code> and <code>vBars</code>. The grid has <code>n + 2</code> horizontal and <code>m + 2</code> vertical bars, creating 1 x 1 unit cells. The bars are indexed starting from <code>1</code>.</p> <p>You can <strong>remove</strong> some of the bars in <code>hBars</code> from horizontal bars and some of the bars in <code>vBars</code> from vertical bars. Note that other bars are fixed and cannot be removed.</p> <p>Return an integer denoting the <strong>maximum area</strong> of a <em>square-shaped</em> hole in the grid, after removing some bars (possibly none).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/screenshot-from-2023-11-05-22-40-25.png" style="width: 411px; height: 220px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 2, m = 1, hBars = [2,3], vBars = [2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p>The left image shows the initial grid formed by the bars. The horizontal bars are <code>[1,2,3,4]</code>, and the vertical bars are&nbsp;<code>[1,2,3]</code>.</p> <p>One way to get the maximum square-shaped hole is by removing horizontal bar 2 and vertical bar 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/screenshot-from-2023-11-04-17-01-02.png" style="width: 368px; height: 145px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 1, m = 1, hBars = [2], vBars = [2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p>To get the maximum square-shaped hole, we remove horizontal bar 2 and vertical bar 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/unsaved-image-2.png" style="width: 648px; height: 218px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 2, m = 3, hBars = [2,3], vBars = [2,4]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p><span style="color: var(--text-secondary); font-size: 0.875rem;">One way to get the maximum square-shaped hole is by removing horizontal bar 3, and vertical bar 4.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= hBars.length &lt;= 100</code></li> <li><code>2 &lt;= hBars[i] &lt;= n + 1</code></li> <li><code>1 &lt;= vBars.length &lt;= 100</code></li> <li><code>2 &lt;= vBars[i] &lt;= m + 1</code></li> <li>All values in <code>hBars</code> are distinct.</li> <li>All values in <code>vBars</code> are distinct.</li> </ul>
Array; Sorting
C++
class Solution { public: int maximizeSquareHoleArea(int n, int m, vector<int>& hBars, vector<int>& vBars) { auto f = [](vector<int>& nums) { int ans = 1, cnt = 1; sort(nums.begin(), nums.end()); for (int i = 1; i < nums.size(); ++i) { if (nums[i] == nums[i - 1] + 1) { ans = max(ans, ++cnt); } else { cnt = 1; } } return ans + 1; }; int x = min(f(hBars), f(vBars)); return x * x; } };
2,943
Maximize Area of Square Hole in Grid
Medium
<p>You are given the two integers, <code>n</code> and <code>m</code> and two integer arrays, <code>hBars</code> and <code>vBars</code>. The grid has <code>n + 2</code> horizontal and <code>m + 2</code> vertical bars, creating 1 x 1 unit cells. The bars are indexed starting from <code>1</code>.</p> <p>You can <strong>remove</strong> some of the bars in <code>hBars</code> from horizontal bars and some of the bars in <code>vBars</code> from vertical bars. Note that other bars are fixed and cannot be removed.</p> <p>Return an integer denoting the <strong>maximum area</strong> of a <em>square-shaped</em> hole in the grid, after removing some bars (possibly none).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/screenshot-from-2023-11-05-22-40-25.png" style="width: 411px; height: 220px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 2, m = 1, hBars = [2,3], vBars = [2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p>The left image shows the initial grid formed by the bars. The horizontal bars are <code>[1,2,3,4]</code>, and the vertical bars are&nbsp;<code>[1,2,3]</code>.</p> <p>One way to get the maximum square-shaped hole is by removing horizontal bar 2 and vertical bar 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/screenshot-from-2023-11-04-17-01-02.png" style="width: 368px; height: 145px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 1, m = 1, hBars = [2], vBars = [2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p>To get the maximum square-shaped hole, we remove horizontal bar 2 and vertical bar 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/unsaved-image-2.png" style="width: 648px; height: 218px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 2, m = 3, hBars = [2,3], vBars = [2,4]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p><span style="color: var(--text-secondary); font-size: 0.875rem;">One way to get the maximum square-shaped hole is by removing horizontal bar 3, and vertical bar 4.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= hBars.length &lt;= 100</code></li> <li><code>2 &lt;= hBars[i] &lt;= n + 1</code></li> <li><code>1 &lt;= vBars.length &lt;= 100</code></li> <li><code>2 &lt;= vBars[i] &lt;= m + 1</code></li> <li>All values in <code>hBars</code> are distinct.</li> <li>All values in <code>vBars</code> are distinct.</li> </ul>
Array; Sorting
Go
func maximizeSquareHoleArea(n int, m int, hBars []int, vBars []int) int { f := func(nums []int) int { sort.Ints(nums) ans, cnt := 1, 1 for i, x := range nums[1:] { if x == nums[i]+1 { cnt++ ans = max(ans, cnt) } else { cnt = 1 } } return ans + 1 } x := min(f(hBars), f(vBars)) return x * x }
2,943
Maximize Area of Square Hole in Grid
Medium
<p>You are given the two integers, <code>n</code> and <code>m</code> and two integer arrays, <code>hBars</code> and <code>vBars</code>. The grid has <code>n + 2</code> horizontal and <code>m + 2</code> vertical bars, creating 1 x 1 unit cells. The bars are indexed starting from <code>1</code>.</p> <p>You can <strong>remove</strong> some of the bars in <code>hBars</code> from horizontal bars and some of the bars in <code>vBars</code> from vertical bars. Note that other bars are fixed and cannot be removed.</p> <p>Return an integer denoting the <strong>maximum area</strong> of a <em>square-shaped</em> hole in the grid, after removing some bars (possibly none).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/screenshot-from-2023-11-05-22-40-25.png" style="width: 411px; height: 220px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 2, m = 1, hBars = [2,3], vBars = [2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p>The left image shows the initial grid formed by the bars. The horizontal bars are <code>[1,2,3,4]</code>, and the vertical bars are&nbsp;<code>[1,2,3]</code>.</p> <p>One way to get the maximum square-shaped hole is by removing horizontal bar 2 and vertical bar 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/screenshot-from-2023-11-04-17-01-02.png" style="width: 368px; height: 145px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 1, m = 1, hBars = [2], vBars = [2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p>To get the maximum square-shaped hole, we remove horizontal bar 2 and vertical bar 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/unsaved-image-2.png" style="width: 648px; height: 218px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 2, m = 3, hBars = [2,3], vBars = [2,4]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p><span style="color: var(--text-secondary); font-size: 0.875rem;">One way to get the maximum square-shaped hole is by removing horizontal bar 3, and vertical bar 4.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= hBars.length &lt;= 100</code></li> <li><code>2 &lt;= hBars[i] &lt;= n + 1</code></li> <li><code>1 &lt;= vBars.length &lt;= 100</code></li> <li><code>2 &lt;= vBars[i] &lt;= m + 1</code></li> <li>All values in <code>hBars</code> are distinct.</li> <li>All values in <code>vBars</code> are distinct.</li> </ul>
Array; Sorting
Java
class Solution { public int maximizeSquareHoleArea(int n, int m, int[] hBars, int[] vBars) { int x = Math.min(f(hBars), f(vBars)); return x * x; } private int f(int[] nums) { Arrays.sort(nums); int ans = 1, cnt = 1; for (int i = 1; i < nums.length; ++i) { if (nums[i] == nums[i - 1] + 1) { ans = Math.max(ans, ++cnt); } else { cnt = 1; } } return ans + 1; } }
2,943
Maximize Area of Square Hole in Grid
Medium
<p>You are given the two integers, <code>n</code> and <code>m</code> and two integer arrays, <code>hBars</code> and <code>vBars</code>. The grid has <code>n + 2</code> horizontal and <code>m + 2</code> vertical bars, creating 1 x 1 unit cells. The bars are indexed starting from <code>1</code>.</p> <p>You can <strong>remove</strong> some of the bars in <code>hBars</code> from horizontal bars and some of the bars in <code>vBars</code> from vertical bars. Note that other bars are fixed and cannot be removed.</p> <p>Return an integer denoting the <strong>maximum area</strong> of a <em>square-shaped</em> hole in the grid, after removing some bars (possibly none).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/screenshot-from-2023-11-05-22-40-25.png" style="width: 411px; height: 220px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 2, m = 1, hBars = [2,3], vBars = [2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p>The left image shows the initial grid formed by the bars. The horizontal bars are <code>[1,2,3,4]</code>, and the vertical bars are&nbsp;<code>[1,2,3]</code>.</p> <p>One way to get the maximum square-shaped hole is by removing horizontal bar 2 and vertical bar 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/screenshot-from-2023-11-04-17-01-02.png" style="width: 368px; height: 145px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 1, m = 1, hBars = [2], vBars = [2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p>To get the maximum square-shaped hole, we remove horizontal bar 2 and vertical bar 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/unsaved-image-2.png" style="width: 648px; height: 218px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 2, m = 3, hBars = [2,3], vBars = [2,4]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p><span style="color: var(--text-secondary); font-size: 0.875rem;">One way to get the maximum square-shaped hole is by removing horizontal bar 3, and vertical bar 4.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= hBars.length &lt;= 100</code></li> <li><code>2 &lt;= hBars[i] &lt;= n + 1</code></li> <li><code>1 &lt;= vBars.length &lt;= 100</code></li> <li><code>2 &lt;= vBars[i] &lt;= m + 1</code></li> <li>All values in <code>hBars</code> are distinct.</li> <li>All values in <code>vBars</code> are distinct.</li> </ul>
Array; Sorting
Python
class Solution: def maximizeSquareHoleArea( self, n: int, m: int, hBars: List[int], vBars: List[int] ) -> int: def f(nums: List[int]) -> int: nums.sort() ans = cnt = 1 for i in range(1, len(nums)): if nums[i] == nums[i - 1] + 1: cnt += 1 ans = max(ans, cnt) else: cnt = 1 return ans + 1 return min(f(hBars), f(vBars)) ** 2
2,943
Maximize Area of Square Hole in Grid
Medium
<p>You are given the two integers, <code>n</code> and <code>m</code> and two integer arrays, <code>hBars</code> and <code>vBars</code>. The grid has <code>n + 2</code> horizontal and <code>m + 2</code> vertical bars, creating 1 x 1 unit cells. The bars are indexed starting from <code>1</code>.</p> <p>You can <strong>remove</strong> some of the bars in <code>hBars</code> from horizontal bars and some of the bars in <code>vBars</code> from vertical bars. Note that other bars are fixed and cannot be removed.</p> <p>Return an integer denoting the <strong>maximum area</strong> of a <em>square-shaped</em> hole in the grid, after removing some bars (possibly none).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/screenshot-from-2023-11-05-22-40-25.png" style="width: 411px; height: 220px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 2, m = 1, hBars = [2,3], vBars = [2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p>The left image shows the initial grid formed by the bars. The horizontal bars are <code>[1,2,3,4]</code>, and the vertical bars are&nbsp;<code>[1,2,3]</code>.</p> <p>One way to get the maximum square-shaped hole is by removing horizontal bar 2 and vertical bar 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/screenshot-from-2023-11-04-17-01-02.png" style="width: 368px; height: 145px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 1, m = 1, hBars = [2], vBars = [2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p>To get the maximum square-shaped hole, we remove horizontal bar 2 and vertical bar 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/unsaved-image-2.png" style="width: 648px; height: 218px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 2, m = 3, hBars = [2,3], vBars = [2,4]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p><span style="color: var(--text-secondary); font-size: 0.875rem;">One way to get the maximum square-shaped hole is by removing horizontal bar 3, and vertical bar 4.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= hBars.length &lt;= 100</code></li> <li><code>2 &lt;= hBars[i] &lt;= n + 1</code></li> <li><code>1 &lt;= vBars.length &lt;= 100</code></li> <li><code>2 &lt;= vBars[i] &lt;= m + 1</code></li> <li>All values in <code>hBars</code> are distinct.</li> <li>All values in <code>vBars</code> are distinct.</li> </ul>
Array; Sorting
Rust
impl Solution { pub fn maximize_square_hole_area(n: i32, m: i32, h_bars: Vec<i32>, v_bars: Vec<i32>) -> i32 { let f = |nums: &mut Vec<i32>| -> i32 { let mut ans = 1; let mut cnt = 1; nums.sort(); for i in 1..nums.len() { if nums[i] == nums[i - 1] + 1 { cnt += 1; ans = ans.max(cnt); } else { cnt = 1; } } ans + 1 }; let mut h_bars = h_bars; let mut v_bars = v_bars; let x = f(&mut h_bars).min(f(&mut v_bars)); x * x } }
2,943
Maximize Area of Square Hole in Grid
Medium
<p>You are given the two integers, <code>n</code> and <code>m</code> and two integer arrays, <code>hBars</code> and <code>vBars</code>. The grid has <code>n + 2</code> horizontal and <code>m + 2</code> vertical bars, creating 1 x 1 unit cells. The bars are indexed starting from <code>1</code>.</p> <p>You can <strong>remove</strong> some of the bars in <code>hBars</code> from horizontal bars and some of the bars in <code>vBars</code> from vertical bars. Note that other bars are fixed and cannot be removed.</p> <p>Return an integer denoting the <strong>maximum area</strong> of a <em>square-shaped</em> hole in the grid, after removing some bars (possibly none).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/screenshot-from-2023-11-05-22-40-25.png" style="width: 411px; height: 220px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 2, m = 1, hBars = [2,3], vBars = [2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p>The left image shows the initial grid formed by the bars. The horizontal bars are <code>[1,2,3,4]</code>, and the vertical bars are&nbsp;<code>[1,2,3]</code>.</p> <p>One way to get the maximum square-shaped hole is by removing horizontal bar 2 and vertical bar 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/screenshot-from-2023-11-04-17-01-02.png" style="width: 368px; height: 145px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 1, m = 1, hBars = [2], vBars = [2]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p>To get the maximum square-shaped hole, we remove horizontal bar 2 and vertical bar 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2943.Maximize%20Area%20of%20Square%20Hole%20in%20Grid/images/unsaved-image-2.png" style="width: 648px; height: 218px;" /></p> <div class="example-block" style="border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;"> <p><strong>Input: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">n = 2, m = 3, hBars = [2,3], vBars = [2,4]</span></p> <p><strong>Output: </strong><span class="example-io" style="font-family: Menlo,sans-serif; font-size: 0.85rem;">4</span></p> <p><strong>Explanation:</strong></p> <p><span style="color: var(--text-secondary); font-size: 0.875rem;">One way to get the maximum square-shaped hole is by removing horizontal bar 3, and vertical bar 4.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= m &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= hBars.length &lt;= 100</code></li> <li><code>2 &lt;= hBars[i] &lt;= n + 1</code></li> <li><code>1 &lt;= vBars.length &lt;= 100</code></li> <li><code>2 &lt;= vBars[i] &lt;= m + 1</code></li> <li>All values in <code>hBars</code> are distinct.</li> <li>All values in <code>vBars</code> are distinct.</li> </ul>
Array; Sorting
TypeScript
function maximizeSquareHoleArea(n: number, m: number, hBars: number[], vBars: number[]): number { const f = (nums: number[]): number => { nums.sort((a, b) => a - b); let [ans, cnt] = [1, 1]; for (let i = 1; i < nums.length; ++i) { if (nums[i] === nums[i - 1] + 1) { ans = Math.max(ans, ++cnt); } else { cnt = 1; } } return ans + 1; }; return Math.min(f(hBars), f(vBars)) ** 2; }
2,944
Minimum Number of Coins for Fruits
Medium
<p>You are given an <strong>0-indexed</strong> integer array <code>prices</code> where <code>prices[i]</code> denotes the number of coins needed to purchase the <code>(i + 1)<sup>th</sup></code> fruit.</p> <p>The fruit market has the following reward for each fruit:</p> <ul> <li>If you purchase the <code>(i + 1)<sup>th</sup></code> fruit at <code>prices[i]</code> coins, you can get any number of the next <code>i</code> fruits for free.</li> </ul> <p><strong>Note</strong> that even if you <strong>can</strong> take fruit <code>j</code> for free, you can still purchase it for <code>prices[j - 1]</code> coins to receive its reward.</p> <p>Return the <strong>minimum</strong> number of coins needed to acquire all the fruits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [3,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 3</code> coins, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 2<sup>nd</sup> fruit with <code>prices[1] = 1</code> coin, you are allowed to take the 3<sup>rd</sup> fruit for free.</li> <li>Take the 3<sup>rd</sup> fruit for free.</li> </ul> <p>Note that even though you could take the 2<sup>nd</sup> fruit for free as a reward of buying 1<sup>st</sup> fruit, you purchase it to receive its reward, which is more optimal.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [1,10,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 1</code> coin, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 3<sup>rd</sup> fruit for <code>prices[2] = 1</code> coin, you are allowed to take the 4<sup>th</sup> fruit for free.</li> <li>Take the 4<sup>t</sup><sup>h</sup> fruit for free.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [26,18,6,12,49,7,45,45]</span></p> <p><strong>Output:</strong> <span class="example-io">39</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 26</code> coin, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 3<sup>rd</sup> fruit for <code>prices[2] = 6</code> coin, you are allowed to take the 4<sup>th</sup>, 5<sup>th</sup> and 6<sup>th</sup> (the next three) fruits for free.</li> <li>Take the 4<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Take the 5<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Purchase the 6<sup>th</sup> fruit with <code>prices[5] = 7</code> coin, you are allowed to take the 8<sup>th</sup> and 9<sup>th</sup> fruit for free.</li> <li>Take the 7<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Take the 8<sup>t</sup><sup>h</sup> fruit for free.</li> </ul> <p>Note that even though you could take the 6<sup>th</sup> fruit for free as a reward of buying 3<sup>rd</sup> fruit, you purchase it to receive its reward, which is more optimal.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 1000</code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Monotonic Queue; Heap (Priority Queue)
C++
class Solution { public: int minimumCoins(vector<int>& prices) { int n = prices.size(); int f[n + 1]; memset(f, 0x3f, sizeof(f)); function<int(int)> dfs = [&](int i) { if (i * 2 >= n) { return prices[i - 1]; } if (f[i] == 0x3f3f3f3f) { for (int j = i + 1; j <= i * 2 + 1; ++j) { f[i] = min(f[i], prices[i - 1] + dfs(j)); } } return f[i]; }; return dfs(1); } };
2,944
Minimum Number of Coins for Fruits
Medium
<p>You are given an <strong>0-indexed</strong> integer array <code>prices</code> where <code>prices[i]</code> denotes the number of coins needed to purchase the <code>(i + 1)<sup>th</sup></code> fruit.</p> <p>The fruit market has the following reward for each fruit:</p> <ul> <li>If you purchase the <code>(i + 1)<sup>th</sup></code> fruit at <code>prices[i]</code> coins, you can get any number of the next <code>i</code> fruits for free.</li> </ul> <p><strong>Note</strong> that even if you <strong>can</strong> take fruit <code>j</code> for free, you can still purchase it for <code>prices[j - 1]</code> coins to receive its reward.</p> <p>Return the <strong>minimum</strong> number of coins needed to acquire all the fruits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [3,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 3</code> coins, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 2<sup>nd</sup> fruit with <code>prices[1] = 1</code> coin, you are allowed to take the 3<sup>rd</sup> fruit for free.</li> <li>Take the 3<sup>rd</sup> fruit for free.</li> </ul> <p>Note that even though you could take the 2<sup>nd</sup> fruit for free as a reward of buying 1<sup>st</sup> fruit, you purchase it to receive its reward, which is more optimal.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [1,10,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 1</code> coin, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 3<sup>rd</sup> fruit for <code>prices[2] = 1</code> coin, you are allowed to take the 4<sup>th</sup> fruit for free.</li> <li>Take the 4<sup>t</sup><sup>h</sup> fruit for free.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [26,18,6,12,49,7,45,45]</span></p> <p><strong>Output:</strong> <span class="example-io">39</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 26</code> coin, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 3<sup>rd</sup> fruit for <code>prices[2] = 6</code> coin, you are allowed to take the 4<sup>th</sup>, 5<sup>th</sup> and 6<sup>th</sup> (the next three) fruits for free.</li> <li>Take the 4<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Take the 5<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Purchase the 6<sup>th</sup> fruit with <code>prices[5] = 7</code> coin, you are allowed to take the 8<sup>th</sup> and 9<sup>th</sup> fruit for free.</li> <li>Take the 7<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Take the 8<sup>t</sup><sup>h</sup> fruit for free.</li> </ul> <p>Note that even though you could take the 6<sup>th</sup> fruit for free as a reward of buying 3<sup>rd</sup> fruit, you purchase it to receive its reward, which is more optimal.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 1000</code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Monotonic Queue; Heap (Priority Queue)
Go
func minimumCoins(prices []int) int { n := len(prices) f := make([]int, n+1) var dfs func(int) int dfs = func(i int) int { if i*2 >= n { return prices[i-1] } if f[i] == 0 { f[i] = 1 << 30 for j := i + 1; j <= i*2+1; j++ { f[i] = min(f[i], dfs(j)+prices[i-1]) } } return f[i] } return dfs(1) }
2,944
Minimum Number of Coins for Fruits
Medium
<p>You are given an <strong>0-indexed</strong> integer array <code>prices</code> where <code>prices[i]</code> denotes the number of coins needed to purchase the <code>(i + 1)<sup>th</sup></code> fruit.</p> <p>The fruit market has the following reward for each fruit:</p> <ul> <li>If you purchase the <code>(i + 1)<sup>th</sup></code> fruit at <code>prices[i]</code> coins, you can get any number of the next <code>i</code> fruits for free.</li> </ul> <p><strong>Note</strong> that even if you <strong>can</strong> take fruit <code>j</code> for free, you can still purchase it for <code>prices[j - 1]</code> coins to receive its reward.</p> <p>Return the <strong>minimum</strong> number of coins needed to acquire all the fruits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [3,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 3</code> coins, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 2<sup>nd</sup> fruit with <code>prices[1] = 1</code> coin, you are allowed to take the 3<sup>rd</sup> fruit for free.</li> <li>Take the 3<sup>rd</sup> fruit for free.</li> </ul> <p>Note that even though you could take the 2<sup>nd</sup> fruit for free as a reward of buying 1<sup>st</sup> fruit, you purchase it to receive its reward, which is more optimal.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [1,10,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 1</code> coin, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 3<sup>rd</sup> fruit for <code>prices[2] = 1</code> coin, you are allowed to take the 4<sup>th</sup> fruit for free.</li> <li>Take the 4<sup>t</sup><sup>h</sup> fruit for free.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [26,18,6,12,49,7,45,45]</span></p> <p><strong>Output:</strong> <span class="example-io">39</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 26</code> coin, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 3<sup>rd</sup> fruit for <code>prices[2] = 6</code> coin, you are allowed to take the 4<sup>th</sup>, 5<sup>th</sup> and 6<sup>th</sup> (the next three) fruits for free.</li> <li>Take the 4<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Take the 5<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Purchase the 6<sup>th</sup> fruit with <code>prices[5] = 7</code> coin, you are allowed to take the 8<sup>th</sup> and 9<sup>th</sup> fruit for free.</li> <li>Take the 7<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Take the 8<sup>t</sup><sup>h</sup> fruit for free.</li> </ul> <p>Note that even though you could take the 6<sup>th</sup> fruit for free as a reward of buying 3<sup>rd</sup> fruit, you purchase it to receive its reward, which is more optimal.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 1000</code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Monotonic Queue; Heap (Priority Queue)
Java
class Solution { private int[] prices; private int[] f; private int n; public int minimumCoins(int[] prices) { n = prices.length; f = new int[n + 1]; this.prices = prices; return dfs(1); } private int dfs(int i) { if (i * 2 >= n) { return prices[i - 1]; } if (f[i] == 0) { f[i] = 1 << 30; for (int j = i + 1; j <= i * 2 + 1; ++j) { f[i] = Math.min(f[i], prices[i - 1] + dfs(j)); } } return f[i]; } }
2,944
Minimum Number of Coins for Fruits
Medium
<p>You are given an <strong>0-indexed</strong> integer array <code>prices</code> where <code>prices[i]</code> denotes the number of coins needed to purchase the <code>(i + 1)<sup>th</sup></code> fruit.</p> <p>The fruit market has the following reward for each fruit:</p> <ul> <li>If you purchase the <code>(i + 1)<sup>th</sup></code> fruit at <code>prices[i]</code> coins, you can get any number of the next <code>i</code> fruits for free.</li> </ul> <p><strong>Note</strong> that even if you <strong>can</strong> take fruit <code>j</code> for free, you can still purchase it for <code>prices[j - 1]</code> coins to receive its reward.</p> <p>Return the <strong>minimum</strong> number of coins needed to acquire all the fruits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [3,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 3</code> coins, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 2<sup>nd</sup> fruit with <code>prices[1] = 1</code> coin, you are allowed to take the 3<sup>rd</sup> fruit for free.</li> <li>Take the 3<sup>rd</sup> fruit for free.</li> </ul> <p>Note that even though you could take the 2<sup>nd</sup> fruit for free as a reward of buying 1<sup>st</sup> fruit, you purchase it to receive its reward, which is more optimal.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [1,10,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 1</code> coin, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 3<sup>rd</sup> fruit for <code>prices[2] = 1</code> coin, you are allowed to take the 4<sup>th</sup> fruit for free.</li> <li>Take the 4<sup>t</sup><sup>h</sup> fruit for free.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [26,18,6,12,49,7,45,45]</span></p> <p><strong>Output:</strong> <span class="example-io">39</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 26</code> coin, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 3<sup>rd</sup> fruit for <code>prices[2] = 6</code> coin, you are allowed to take the 4<sup>th</sup>, 5<sup>th</sup> and 6<sup>th</sup> (the next three) fruits for free.</li> <li>Take the 4<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Take the 5<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Purchase the 6<sup>th</sup> fruit with <code>prices[5] = 7</code> coin, you are allowed to take the 8<sup>th</sup> and 9<sup>th</sup> fruit for free.</li> <li>Take the 7<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Take the 8<sup>t</sup><sup>h</sup> fruit for free.</li> </ul> <p>Note that even though you could take the 6<sup>th</sup> fruit for free as a reward of buying 3<sup>rd</sup> fruit, you purchase it to receive its reward, which is more optimal.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 1000</code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Monotonic Queue; Heap (Priority Queue)
Python
class Solution: def minimumCoins(self, prices: List[int]) -> int: @cache def dfs(i: int) -> int: if i * 2 >= len(prices): return prices[i - 1] return prices[i - 1] + min(dfs(j) for j in range(i + 1, i * 2 + 2)) return dfs(1)
2,944
Minimum Number of Coins for Fruits
Medium
<p>You are given an <strong>0-indexed</strong> integer array <code>prices</code> where <code>prices[i]</code> denotes the number of coins needed to purchase the <code>(i + 1)<sup>th</sup></code> fruit.</p> <p>The fruit market has the following reward for each fruit:</p> <ul> <li>If you purchase the <code>(i + 1)<sup>th</sup></code> fruit at <code>prices[i]</code> coins, you can get any number of the next <code>i</code> fruits for free.</li> </ul> <p><strong>Note</strong> that even if you <strong>can</strong> take fruit <code>j</code> for free, you can still purchase it for <code>prices[j - 1]</code> coins to receive its reward.</p> <p>Return the <strong>minimum</strong> number of coins needed to acquire all the fruits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [3,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 3</code> coins, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 2<sup>nd</sup> fruit with <code>prices[1] = 1</code> coin, you are allowed to take the 3<sup>rd</sup> fruit for free.</li> <li>Take the 3<sup>rd</sup> fruit for free.</li> </ul> <p>Note that even though you could take the 2<sup>nd</sup> fruit for free as a reward of buying 1<sup>st</sup> fruit, you purchase it to receive its reward, which is more optimal.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [1,10,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 1</code> coin, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 3<sup>rd</sup> fruit for <code>prices[2] = 1</code> coin, you are allowed to take the 4<sup>th</sup> fruit for free.</li> <li>Take the 4<sup>t</sup><sup>h</sup> fruit for free.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">prices = [26,18,6,12,49,7,45,45]</span></p> <p><strong>Output:</strong> <span class="example-io">39</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Purchase the 1<sup>st</sup> fruit with <code>prices[0] = 26</code> coin, you are allowed to take the 2<sup>nd</sup> fruit for free.</li> <li>Take the 2<sup>nd</sup> fruit for free.</li> <li>Purchase the 3<sup>rd</sup> fruit for <code>prices[2] = 6</code> coin, you are allowed to take the 4<sup>th</sup>, 5<sup>th</sup> and 6<sup>th</sup> (the next three) fruits for free.</li> <li>Take the 4<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Take the 5<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Purchase the 6<sup>th</sup> fruit with <code>prices[5] = 7</code> coin, you are allowed to take the 8<sup>th</sup> and 9<sup>th</sup> fruit for free.</li> <li>Take the 7<sup>t</sup><sup>h</sup> fruit for free.</li> <li>Take the 8<sup>t</sup><sup>h</sup> fruit for free.</li> </ul> <p>Note that even though you could take the 6<sup>th</sup> fruit for free as a reward of buying 3<sup>rd</sup> fruit, you purchase it to receive its reward, which is more optimal.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= prices.length &lt;= 1000</code></li> <li><code>1 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li> </ul>
Queue; Array; Dynamic Programming; Monotonic Queue; Heap (Priority Queue)
TypeScript
function minimumCoins(prices: number[]): number { const n = prices.length; const f: number[] = Array(n + 1).fill(0); const dfs = (i: number): number => { if (i * 2 >= n) { return prices[i - 1]; } if (f[i] === 0) { f[i] = 1 << 30; for (let j = i + 1; j <= i * 2 + 1; ++j) { f[i] = Math.min(f[i], prices[i - 1] + dfs(j)); } } return f[i]; }; return dfs(1); }
2,945
Find Maximum Non-decreasing Array Length
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>You can perform any number of operations, where each operation involves selecting a <strong>subarray</strong> of the array and replacing it with the <strong>sum</strong> of its elements. For example, if the given array is <code>[1,3,5,6]</code> and you select subarray <code>[3,5]</code> the array will convert to <code>[1,8,6]</code>.</p> <p>Return <em>the </em><strong><em>maximum</em></strong><em> length of a </em><strong><em>non-decreasing</em></strong><em> array that can be made after applying operations.</em></p> <p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,2,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> This array with length 3 is not non-decreasing. We have two ways to make the array length two. First, choosing subarray [2,2] converts the array to [5,4]. Second, choosing subarray [5,2] converts the array to [7,2]. In these two ways the array is not non-decreasing. And if we choose subarray [5,2,2] and replace it with [9] it becomes non-decreasing. So the answer is 1. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> The array is non-decreasing. So the answer is 4. </pre> <p><strong>Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> Replacing [3,2] with [5] converts the given array to [4,5,6] that is non-decreasing. Because the given array is not non-decreasing, the maximum<!-- notionvc: 3447a505-d1ee-4411-8cae-e52162f53a55 --> possible answer is 3.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Queue; Array; Binary Search; Dynamic Programming; Monotonic Queue; Monotonic Stack
C++
class Solution { public: int findMaximumLength(vector<int>& nums) { int n = nums.size(); int f[n + 1]; int pre[n + 2]; long long s[n + 1]; for (int i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } memset(f, 0, sizeof(f)); memset(pre, 0, sizeof(pre)); for (int i = 1; i <= n; ++i) { pre[i] = max(pre[i], pre[i - 1]); f[i] = f[pre[i]] + 1; int j = lower_bound(s, s + n + 1, s[i] * 2 - s[pre[i]]) - s; pre[j] = i; } return f[n]; } };
2,945
Find Maximum Non-decreasing Array Length
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>You can perform any number of operations, where each operation involves selecting a <strong>subarray</strong> of the array and replacing it with the <strong>sum</strong> of its elements. For example, if the given array is <code>[1,3,5,6]</code> and you select subarray <code>[3,5]</code> the array will convert to <code>[1,8,6]</code>.</p> <p>Return <em>the </em><strong><em>maximum</em></strong><em> length of a </em><strong><em>non-decreasing</em></strong><em> array that can be made after applying operations.</em></p> <p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,2,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> This array with length 3 is not non-decreasing. We have two ways to make the array length two. First, choosing subarray [2,2] converts the array to [5,4]. Second, choosing subarray [5,2] converts the array to [7,2]. In these two ways the array is not non-decreasing. And if we choose subarray [5,2,2] and replace it with [9] it becomes non-decreasing. So the answer is 1. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> The array is non-decreasing. So the answer is 4. </pre> <p><strong>Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> Replacing [3,2] with [5] converts the given array to [4,5,6] that is non-decreasing. Because the given array is not non-decreasing, the maximum<!-- notionvc: 3447a505-d1ee-4411-8cae-e52162f53a55 --> possible answer is 3.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Queue; Array; Binary Search; Dynamic Programming; Monotonic Queue; Monotonic Stack
Go
func findMaximumLength(nums []int) int { n := len(nums) f := make([]int, n+1) pre := make([]int, n+2) s := make([]int, n+1) for i, x := range nums { s[i+1] = s[i] + x } for i := 1; i <= n; i++ { pre[i] = max(pre[i], pre[i-1]) f[i] = f[pre[i]] + 1 j := sort.SearchInts(s, s[i]*2-s[pre[i]]) pre[j] = max(pre[j], i) } return f[n] }
2,945
Find Maximum Non-decreasing Array Length
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>You can perform any number of operations, where each operation involves selecting a <strong>subarray</strong> of the array and replacing it with the <strong>sum</strong> of its elements. For example, if the given array is <code>[1,3,5,6]</code> and you select subarray <code>[3,5]</code> the array will convert to <code>[1,8,6]</code>.</p> <p>Return <em>the </em><strong><em>maximum</em></strong><em> length of a </em><strong><em>non-decreasing</em></strong><em> array that can be made after applying operations.</em></p> <p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,2,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> This array with length 3 is not non-decreasing. We have two ways to make the array length two. First, choosing subarray [2,2] converts the array to [5,4]. Second, choosing subarray [5,2] converts the array to [7,2]. In these two ways the array is not non-decreasing. And if we choose subarray [5,2,2] and replace it with [9] it becomes non-decreasing. So the answer is 1. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> The array is non-decreasing. So the answer is 4. </pre> <p><strong>Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> Replacing [3,2] with [5] converts the given array to [4,5,6] that is non-decreasing. Because the given array is not non-decreasing, the maximum<!-- notionvc: 3447a505-d1ee-4411-8cae-e52162f53a55 --> possible answer is 3.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Queue; Array; Binary Search; Dynamic Programming; Monotonic Queue; Monotonic Stack
Java
class Solution { public int findMaximumLength(int[] nums) { int n = nums.length; long[] s = new long[n + 1]; for (int i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } int[] f = new int[n + 1]; int[] pre = new int[n + 2]; for (int i = 1; i <= n; ++i) { pre[i] = Math.max(pre[i], pre[i - 1]); f[i] = f[pre[i]] + 1; int j = Arrays.binarySearch(s, s[i] * 2 - s[pre[i]]); pre[j < 0 ? -j - 1 : j] = i; } return f[n]; } }
2,945
Find Maximum Non-decreasing Array Length
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>You can perform any number of operations, where each operation involves selecting a <strong>subarray</strong> of the array and replacing it with the <strong>sum</strong> of its elements. For example, if the given array is <code>[1,3,5,6]</code> and you select subarray <code>[3,5]</code> the array will convert to <code>[1,8,6]</code>.</p> <p>Return <em>the </em><strong><em>maximum</em></strong><em> length of a </em><strong><em>non-decreasing</em></strong><em> array that can be made after applying operations.</em></p> <p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,2,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> This array with length 3 is not non-decreasing. We have two ways to make the array length two. First, choosing subarray [2,2] converts the array to [5,4]. Second, choosing subarray [5,2] converts the array to [7,2]. In these two ways the array is not non-decreasing. And if we choose subarray [5,2,2] and replace it with [9] it becomes non-decreasing. So the answer is 1. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> The array is non-decreasing. So the answer is 4. </pre> <p><strong>Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> Replacing [3,2] with [5] converts the given array to [4,5,6] that is non-decreasing. Because the given array is not non-decreasing, the maximum<!-- notionvc: 3447a505-d1ee-4411-8cae-e52162f53a55 --> possible answer is 3.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Queue; Array; Binary Search; Dynamic Programming; Monotonic Queue; Monotonic Stack
Python
class Solution: def findMaximumLength(self, nums: List[int]) -> int: n = len(nums) s = list(accumulate(nums, initial=0)) f = [0] * (n + 1) pre = [0] * (n + 2) for i in range(1, n + 1): pre[i] = max(pre[i], pre[i - 1]) f[i] = f[pre[i]] + 1 j = bisect_left(s, s[i] * 2 - s[pre[i]]) pre[j] = i return f[n]
2,945
Find Maximum Non-decreasing Array Length
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>.</p> <p>You can perform any number of operations, where each operation involves selecting a <strong>subarray</strong> of the array and replacing it with the <strong>sum</strong> of its elements. For example, if the given array is <code>[1,3,5,6]</code> and you select subarray <code>[3,5]</code> the array will convert to <code>[1,8,6]</code>.</p> <p>Return <em>the </em><strong><em>maximum</em></strong><em> length of a </em><strong><em>non-decreasing</em></strong><em> array that can be made after applying operations.</em></p> <p>A <strong>subarray</strong> is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [5,2,2] <strong>Output:</strong> 1 <strong>Explanation:</strong> This array with length 3 is not non-decreasing. We have two ways to make the array length two. First, choosing subarray [2,2] converts the array to [5,4]. Second, choosing subarray [5,2] converts the array to [7,2]. In these two ways the array is not non-decreasing. And if we choose subarray [5,2,2] and replace it with [9] it becomes non-decreasing. So the answer is 1. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> The array is non-decreasing. So the answer is 4. </pre> <p><strong>Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> Replacing [3,2] with [5] converts the given array to [4,5,6] that is non-decreasing. Because the given array is not non-decreasing, the maximum<!-- notionvc: 3447a505-d1ee-4411-8cae-e52162f53a55 --> possible answer is 3.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Queue; Array; Binary Search; Dynamic Programming; Monotonic Queue; Monotonic Stack
TypeScript
function findMaximumLength(nums: number[]): number { const n = nums.length; const f: number[] = Array(n + 1).fill(0); const pre: number[] = Array(n + 2).fill(0); const s: number[] = Array(n + 1).fill(0); for (let i = 1; i <= n; ++i) { s[i] = s[i - 1] + nums[i - 1]; } const search = (nums: number[], x: number): number => { let [l, r] = [0, nums.length]; while (l < r) { const mid = (l + r) >> 1; if (nums[mid] >= x) { r = mid; } else { l = mid + 1; } } return l; }; for (let i = 1; i <= n; ++i) { pre[i] = Math.max(pre[i], pre[i - 1]); f[i] = f[pre[i]] + 1; const j = search(s, s[i] * 2 - s[pre[i]]); pre[j] = i; } return f[n]; }
2,946
Matrix Similarity After Cyclic Shifts
Easy
<p>You are given an <code>m x n</code> integer matrix <code>mat</code> and an integer <code>k</code>. The matrix rows are 0-indexed.</p> <p>The following proccess happens <code>k</code> times:</p> <ul> <li><strong>Even-indexed</strong> rows (0, 2, 4, ...) are cyclically shifted to the left.</li> </ul> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/lshift.jpg" style="width: 283px; height: 90px;" /></p> <ul> <li><strong>Odd-indexed</strong> rows (1, 3, 5, ...) are cyclically shifted to the right.</li> </ul> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/rshift-stlone.jpg" style="width: 283px; height: 90px;" /></p> <p>Return <code>true</code> if the final modified matrix after <code>k</code> steps is identical to the original matrix, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[1,2,3],[4,5,6],[7,8,9]], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>In each step left shift is applied to rows 0 and 2 (even indices), and right shift to row 1 (odd index).</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/t1-2.jpg" style="width: 857px; height: 150px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[1,2,1,2],[5,5,5,5],[6,3,6,3]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/t1-3.jpg" style="width: 632px; height: 150px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[2,2],[2,2]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>As all the values are equal in the matrix, even after performing cyclic shifts the matrix will remain the same.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= mat.length &lt;= 25</code></li> <li><code>1 &lt;= mat[i].length &lt;= 25</code></li> <li><code>1 &lt;= mat[i][j] &lt;= 25</code></li> <li><code>1 &lt;= k &lt;= 50</code></li> </ul>
Array; Math; Matrix; Simulation
C++
class Solution { public: bool areSimilar(vector<vector<int>>& mat, int k) { int m = mat.size(), n = mat[0].size(); k %= n; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (i % 2 == 1 && mat[i][j] != mat[i][(j + k) % n]) { return false; } if (i % 2 == 0 && mat[i][j] != mat[i][(j - k + n) % n]) { return false; } } } return true; } };
2,946
Matrix Similarity After Cyclic Shifts
Easy
<p>You are given an <code>m x n</code> integer matrix <code>mat</code> and an integer <code>k</code>. The matrix rows are 0-indexed.</p> <p>The following proccess happens <code>k</code> times:</p> <ul> <li><strong>Even-indexed</strong> rows (0, 2, 4, ...) are cyclically shifted to the left.</li> </ul> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/lshift.jpg" style="width: 283px; height: 90px;" /></p> <ul> <li><strong>Odd-indexed</strong> rows (1, 3, 5, ...) are cyclically shifted to the right.</li> </ul> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/rshift-stlone.jpg" style="width: 283px; height: 90px;" /></p> <p>Return <code>true</code> if the final modified matrix after <code>k</code> steps is identical to the original matrix, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[1,2,3],[4,5,6],[7,8,9]], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>In each step left shift is applied to rows 0 and 2 (even indices), and right shift to row 1 (odd index).</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/t1-2.jpg" style="width: 857px; height: 150px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[1,2,1,2],[5,5,5,5],[6,3,6,3]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/t1-3.jpg" style="width: 632px; height: 150px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[2,2],[2,2]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>As all the values are equal in the matrix, even after performing cyclic shifts the matrix will remain the same.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= mat.length &lt;= 25</code></li> <li><code>1 &lt;= mat[i].length &lt;= 25</code></li> <li><code>1 &lt;= mat[i][j] &lt;= 25</code></li> <li><code>1 &lt;= k &lt;= 50</code></li> </ul>
Array; Math; Matrix; Simulation
Go
func areSimilar(mat [][]int, k int) bool { n := len(mat[0]) k %= n for i, row := range mat { for j, x := range row { if i%2 == 1 && x != mat[i][(j+k)%n] { return false } if i%2 == 0 && x != mat[i][(j-k+n)%n] { return false } } } return true }
2,946
Matrix Similarity After Cyclic Shifts
Easy
<p>You are given an <code>m x n</code> integer matrix <code>mat</code> and an integer <code>k</code>. The matrix rows are 0-indexed.</p> <p>The following proccess happens <code>k</code> times:</p> <ul> <li><strong>Even-indexed</strong> rows (0, 2, 4, ...) are cyclically shifted to the left.</li> </ul> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/lshift.jpg" style="width: 283px; height: 90px;" /></p> <ul> <li><strong>Odd-indexed</strong> rows (1, 3, 5, ...) are cyclically shifted to the right.</li> </ul> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/rshift-stlone.jpg" style="width: 283px; height: 90px;" /></p> <p>Return <code>true</code> if the final modified matrix after <code>k</code> steps is identical to the original matrix, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[1,2,3],[4,5,6],[7,8,9]], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>In each step left shift is applied to rows 0 and 2 (even indices), and right shift to row 1 (odd index).</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/t1-2.jpg" style="width: 857px; height: 150px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[1,2,1,2],[5,5,5,5],[6,3,6,3]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/t1-3.jpg" style="width: 632px; height: 150px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[2,2],[2,2]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>As all the values are equal in the matrix, even after performing cyclic shifts the matrix will remain the same.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= mat.length &lt;= 25</code></li> <li><code>1 &lt;= mat[i].length &lt;= 25</code></li> <li><code>1 &lt;= mat[i][j] &lt;= 25</code></li> <li><code>1 &lt;= k &lt;= 50</code></li> </ul>
Array; Math; Matrix; Simulation
Java
class Solution { public boolean areSimilar(int[][] mat, int k) { int m = mat.length, n = mat[0].length; k %= n; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (i % 2 == 1 && mat[i][j] != mat[i][(j + k) % n]) { return false; } if (i % 2 == 0 && mat[i][j] != mat[i][(j - k + n) % n]) { return false; } } } return true; } }
2,946
Matrix Similarity After Cyclic Shifts
Easy
<p>You are given an <code>m x n</code> integer matrix <code>mat</code> and an integer <code>k</code>. The matrix rows are 0-indexed.</p> <p>The following proccess happens <code>k</code> times:</p> <ul> <li><strong>Even-indexed</strong> rows (0, 2, 4, ...) are cyclically shifted to the left.</li> </ul> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/lshift.jpg" style="width: 283px; height: 90px;" /></p> <ul> <li><strong>Odd-indexed</strong> rows (1, 3, 5, ...) are cyclically shifted to the right.</li> </ul> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/rshift-stlone.jpg" style="width: 283px; height: 90px;" /></p> <p>Return <code>true</code> if the final modified matrix after <code>k</code> steps is identical to the original matrix, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[1,2,3],[4,5,6],[7,8,9]], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>In each step left shift is applied to rows 0 and 2 (even indices), and right shift to row 1 (odd index).</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/t1-2.jpg" style="width: 857px; height: 150px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[1,2,1,2],[5,5,5,5],[6,3,6,3]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/t1-3.jpg" style="width: 632px; height: 150px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[2,2],[2,2]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>As all the values are equal in the matrix, even after performing cyclic shifts the matrix will remain the same.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= mat.length &lt;= 25</code></li> <li><code>1 &lt;= mat[i].length &lt;= 25</code></li> <li><code>1 &lt;= mat[i][j] &lt;= 25</code></li> <li><code>1 &lt;= k &lt;= 50</code></li> </ul>
Array; Math; Matrix; Simulation
Python
class Solution: def areSimilar(self, mat: List[List[int]], k: int) -> bool: n = len(mat[0]) for i, row in enumerate(mat): for j, x in enumerate(row): if i % 2 == 1 and x != mat[i][(j + k) % n]: return False if i % 2 == 0 and x != mat[i][(j - k + n) % n]: return False return True
2,946
Matrix Similarity After Cyclic Shifts
Easy
<p>You are given an <code>m x n</code> integer matrix <code>mat</code> and an integer <code>k</code>. The matrix rows are 0-indexed.</p> <p>The following proccess happens <code>k</code> times:</p> <ul> <li><strong>Even-indexed</strong> rows (0, 2, 4, ...) are cyclically shifted to the left.</li> </ul> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/lshift.jpg" style="width: 283px; height: 90px;" /></p> <ul> <li><strong>Odd-indexed</strong> rows (1, 3, 5, ...) are cyclically shifted to the right.</li> </ul> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/rshift-stlone.jpg" style="width: 283px; height: 90px;" /></p> <p>Return <code>true</code> if the final modified matrix after <code>k</code> steps is identical to the original matrix, and <code>false</code> otherwise.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[1,2,3],[4,5,6],[7,8,9]], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>In each step left shift is applied to rows 0 and 2 (even indices), and right shift to row 1 (odd index).</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/t1-2.jpg" style="width: 857px; height: 150px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[1,2,1,2],[5,5,5,5],[6,3,6,3]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2946.Matrix%20Similarity%20After%20Cyclic%20Shifts/images/t1-3.jpg" style="width: 632px; height: 150px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">mat = [[2,2],[2,2]], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>As all the values are equal in the matrix, even after performing cyclic shifts the matrix will remain the same.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= mat.length &lt;= 25</code></li> <li><code>1 &lt;= mat[i].length &lt;= 25</code></li> <li><code>1 &lt;= mat[i][j] &lt;= 25</code></li> <li><code>1 &lt;= k &lt;= 50</code></li> </ul>
Array; Math; Matrix; Simulation
TypeScript
function areSimilar(mat: number[][], k: number): boolean { const m = mat.length; const n = mat[0].length; k %= n; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (i % 2 === 1 && mat[i][j] !== mat[i][(j + k) % n]) { return false; } if (i % 2 === 0 && mat[i][j] !== mat[i][(j - k + n) % n]) { return false; } } } return true; }
2,947
Count Beautiful Substrings I
Medium
<p>You are given a string <code>s</code> and a positive integer <code>k</code>.</p> <p>Let <code>vowels</code> and <code>consonants</code> be the number of vowels and consonants in a string.</p> <p>A string is <strong>beautiful</strong> if:</p> <ul> <li><code>vowels == consonants</code>.</li> <li><code>(vowels * consonants) % k == 0</code>, in other terms the multiplication of <code>vowels</code> and <code>consonants</code> is divisible by <code>k</code>.</li> </ul> <p>Return <em>the number of <strong>non-empty beautiful substrings</strong> in the given string</em> <code>s</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string.</p> <p><strong>Vowel letters</strong> in English are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>.</p> <p><strong>Consonant letters</strong> in English are every letter except vowels.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;baeyh&quot;, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are 2 beautiful substrings in the given string. - Substring &quot;b<u>aeyh</u>&quot;, vowels = 2 ([&quot;a&quot;,e&quot;]), consonants = 2 ([&quot;y&quot;,&quot;h&quot;]). You can see that string &quot;aeyh&quot; is beautiful as vowels == consonants and vowels * consonants % k == 0. - Substring &quot;<u>baey</u>h&quot;, vowels = 2 ([&quot;a&quot;,e&quot;]), consonants = 2 ([&quot;b&quot;,&quot;y&quot;]). You can see that string &quot;baey&quot; is beautiful as vowels == consonants and vowels * consonants % k == 0. It can be shown that there are only 2 beautiful substrings in the given string. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abba&quot;, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 beautiful substrings in the given string. - Substring &quot;<u>ab</u>ba&quot;, vowels = 1 ([&quot;a&quot;]), consonants = 1 ([&quot;b&quot;]). - Substring &quot;ab<u>ba</u>&quot;, vowels = 1 ([&quot;a&quot;]), consonants = 1 ([&quot;b&quot;]). - Substring &quot;<u>abba</u>&quot;, vowels = 2 ([&quot;a&quot;,&quot;a&quot;]), consonants = 2 ([&quot;b&quot;,&quot;b&quot;]). It can be shown that there are only 3 beautiful substrings in the given string. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;bcdf&quot;, k = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> There are no beautiful substrings in the given string. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 1000</code></li> <li><code>s</code> consists of only English lowercase letters.</li> </ul>
Hash Table; Math; String; Enumeration; Number Theory; Prefix Sum
C++
class Solution { public: int beautifulSubstrings(string s, int k) { int n = s.size(); int vs[26]{}; string t = "aeiou"; for (char c : t) { vs[c - 'a'] = 1; } int ans = 0; for (int i = 0; i < n; ++i) { int vowels = 0; for (int j = i; j < n; ++j) { vowels += vs[s[j] - 'a']; int consonants = j - i + 1 - vowels; if (vowels == consonants && vowels * consonants % k == 0) { ++ans; } } } return ans; } };
2,947
Count Beautiful Substrings I
Medium
<p>You are given a string <code>s</code> and a positive integer <code>k</code>.</p> <p>Let <code>vowels</code> and <code>consonants</code> be the number of vowels and consonants in a string.</p> <p>A string is <strong>beautiful</strong> if:</p> <ul> <li><code>vowels == consonants</code>.</li> <li><code>(vowels * consonants) % k == 0</code>, in other terms the multiplication of <code>vowels</code> and <code>consonants</code> is divisible by <code>k</code>.</li> </ul> <p>Return <em>the number of <strong>non-empty beautiful substrings</strong> in the given string</em> <code>s</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string.</p> <p><strong>Vowel letters</strong> in English are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>.</p> <p><strong>Consonant letters</strong> in English are every letter except vowels.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;baeyh&quot;, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are 2 beautiful substrings in the given string. - Substring &quot;b<u>aeyh</u>&quot;, vowels = 2 ([&quot;a&quot;,e&quot;]), consonants = 2 ([&quot;y&quot;,&quot;h&quot;]). You can see that string &quot;aeyh&quot; is beautiful as vowels == consonants and vowels * consonants % k == 0. - Substring &quot;<u>baey</u>h&quot;, vowels = 2 ([&quot;a&quot;,e&quot;]), consonants = 2 ([&quot;b&quot;,&quot;y&quot;]). You can see that string &quot;baey&quot; is beautiful as vowels == consonants and vowels * consonants % k == 0. It can be shown that there are only 2 beautiful substrings in the given string. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abba&quot;, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 beautiful substrings in the given string. - Substring &quot;<u>ab</u>ba&quot;, vowels = 1 ([&quot;a&quot;]), consonants = 1 ([&quot;b&quot;]). - Substring &quot;ab<u>ba</u>&quot;, vowels = 1 ([&quot;a&quot;]), consonants = 1 ([&quot;b&quot;]). - Substring &quot;<u>abba</u>&quot;, vowels = 2 ([&quot;a&quot;,&quot;a&quot;]), consonants = 2 ([&quot;b&quot;,&quot;b&quot;]). It can be shown that there are only 3 beautiful substrings in the given string. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;bcdf&quot;, k = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> There are no beautiful substrings in the given string. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 1000</code></li> <li><code>s</code> consists of only English lowercase letters.</li> </ul>
Hash Table; Math; String; Enumeration; Number Theory; Prefix Sum
Go
func beautifulSubstrings(s string, k int) (ans int) { n := len(s) vs := [26]int{} for _, c := range "aeiou" { vs[c-'a'] = 1 } for i := 0; i < n; i++ { vowels := 0 for j := i; j < n; j++ { vowels += vs[s[j]-'a'] consonants := j - i + 1 - vowels if vowels == consonants && vowels*consonants%k == 0 { ans++ } } } return }
2,947
Count Beautiful Substrings I
Medium
<p>You are given a string <code>s</code> and a positive integer <code>k</code>.</p> <p>Let <code>vowels</code> and <code>consonants</code> be the number of vowels and consonants in a string.</p> <p>A string is <strong>beautiful</strong> if:</p> <ul> <li><code>vowels == consonants</code>.</li> <li><code>(vowels * consonants) % k == 0</code>, in other terms the multiplication of <code>vowels</code> and <code>consonants</code> is divisible by <code>k</code>.</li> </ul> <p>Return <em>the number of <strong>non-empty beautiful substrings</strong> in the given string</em> <code>s</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string.</p> <p><strong>Vowel letters</strong> in English are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>.</p> <p><strong>Consonant letters</strong> in English are every letter except vowels.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;baeyh&quot;, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are 2 beautiful substrings in the given string. - Substring &quot;b<u>aeyh</u>&quot;, vowels = 2 ([&quot;a&quot;,e&quot;]), consonants = 2 ([&quot;y&quot;,&quot;h&quot;]). You can see that string &quot;aeyh&quot; is beautiful as vowels == consonants and vowels * consonants % k == 0. - Substring &quot;<u>baey</u>h&quot;, vowels = 2 ([&quot;a&quot;,e&quot;]), consonants = 2 ([&quot;b&quot;,&quot;y&quot;]). You can see that string &quot;baey&quot; is beautiful as vowels == consonants and vowels * consonants % k == 0. It can be shown that there are only 2 beautiful substrings in the given string. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abba&quot;, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 beautiful substrings in the given string. - Substring &quot;<u>ab</u>ba&quot;, vowels = 1 ([&quot;a&quot;]), consonants = 1 ([&quot;b&quot;]). - Substring &quot;ab<u>ba</u>&quot;, vowels = 1 ([&quot;a&quot;]), consonants = 1 ([&quot;b&quot;]). - Substring &quot;<u>abba</u>&quot;, vowels = 2 ([&quot;a&quot;,&quot;a&quot;]), consonants = 2 ([&quot;b&quot;,&quot;b&quot;]). It can be shown that there are only 3 beautiful substrings in the given string. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;bcdf&quot;, k = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> There are no beautiful substrings in the given string. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 1000</code></li> <li><code>s</code> consists of only English lowercase letters.</li> </ul>
Hash Table; Math; String; Enumeration; Number Theory; Prefix Sum
Java
class Solution { public int beautifulSubstrings(String s, int k) { int n = s.length(); int[] vs = new int[26]; for (char c : "aeiou".toCharArray()) { vs[c - 'a'] = 1; } int ans = 0; for (int i = 0; i < n; ++i) { int vowels = 0; for (int j = i; j < n; ++j) { vowels += vs[s.charAt(j) - 'a']; int consonants = j - i + 1 - vowels; if (vowels == consonants && vowels * consonants % k == 0) { ++ans; } } } return ans; } }
2,947
Count Beautiful Substrings I
Medium
<p>You are given a string <code>s</code> and a positive integer <code>k</code>.</p> <p>Let <code>vowels</code> and <code>consonants</code> be the number of vowels and consonants in a string.</p> <p>A string is <strong>beautiful</strong> if:</p> <ul> <li><code>vowels == consonants</code>.</li> <li><code>(vowels * consonants) % k == 0</code>, in other terms the multiplication of <code>vowels</code> and <code>consonants</code> is divisible by <code>k</code>.</li> </ul> <p>Return <em>the number of <strong>non-empty beautiful substrings</strong> in the given string</em> <code>s</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string.</p> <p><strong>Vowel letters</strong> in English are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>.</p> <p><strong>Consonant letters</strong> in English are every letter except vowels.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;baeyh&quot;, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are 2 beautiful substrings in the given string. - Substring &quot;b<u>aeyh</u>&quot;, vowels = 2 ([&quot;a&quot;,e&quot;]), consonants = 2 ([&quot;y&quot;,&quot;h&quot;]). You can see that string &quot;aeyh&quot; is beautiful as vowels == consonants and vowels * consonants % k == 0. - Substring &quot;<u>baey</u>h&quot;, vowels = 2 ([&quot;a&quot;,e&quot;]), consonants = 2 ([&quot;b&quot;,&quot;y&quot;]). You can see that string &quot;baey&quot; is beautiful as vowels == consonants and vowels * consonants % k == 0. It can be shown that there are only 2 beautiful substrings in the given string. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abba&quot;, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 beautiful substrings in the given string. - Substring &quot;<u>ab</u>ba&quot;, vowels = 1 ([&quot;a&quot;]), consonants = 1 ([&quot;b&quot;]). - Substring &quot;ab<u>ba</u>&quot;, vowels = 1 ([&quot;a&quot;]), consonants = 1 ([&quot;b&quot;]). - Substring &quot;<u>abba</u>&quot;, vowels = 2 ([&quot;a&quot;,&quot;a&quot;]), consonants = 2 ([&quot;b&quot;,&quot;b&quot;]). It can be shown that there are only 3 beautiful substrings in the given string. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;bcdf&quot;, k = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> There are no beautiful substrings in the given string. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 1000</code></li> <li><code>s</code> consists of only English lowercase letters.</li> </ul>
Hash Table; Math; String; Enumeration; Number Theory; Prefix Sum
Python
class Solution: def beautifulSubstrings(self, s: str, k: int) -> int: n = len(s) vs = set("aeiou") ans = 0 for i in range(n): vowels = 0 for j in range(i, n): vowels += s[j] in vs consonants = j - i + 1 - vowels if vowels == consonants and vowels * consonants % k == 0: ans += 1 return ans
2,947
Count Beautiful Substrings I
Medium
<p>You are given a string <code>s</code> and a positive integer <code>k</code>.</p> <p>Let <code>vowels</code> and <code>consonants</code> be the number of vowels and consonants in a string.</p> <p>A string is <strong>beautiful</strong> if:</p> <ul> <li><code>vowels == consonants</code>.</li> <li><code>(vowels * consonants) % k == 0</code>, in other terms the multiplication of <code>vowels</code> and <code>consonants</code> is divisible by <code>k</code>.</li> </ul> <p>Return <em>the number of <strong>non-empty beautiful substrings</strong> in the given string</em> <code>s</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string.</p> <p><strong>Vowel letters</strong> in English are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>.</p> <p><strong>Consonant letters</strong> in English are every letter except vowels.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;baeyh&quot;, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are 2 beautiful substrings in the given string. - Substring &quot;b<u>aeyh</u>&quot;, vowels = 2 ([&quot;a&quot;,e&quot;]), consonants = 2 ([&quot;y&quot;,&quot;h&quot;]). You can see that string &quot;aeyh&quot; is beautiful as vowels == consonants and vowels * consonants % k == 0. - Substring &quot;<u>baey</u>h&quot;, vowels = 2 ([&quot;a&quot;,e&quot;]), consonants = 2 ([&quot;b&quot;,&quot;y&quot;]). You can see that string &quot;baey&quot; is beautiful as vowels == consonants and vowels * consonants % k == 0. It can be shown that there are only 2 beautiful substrings in the given string. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abba&quot;, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 beautiful substrings in the given string. - Substring &quot;<u>ab</u>ba&quot;, vowels = 1 ([&quot;a&quot;]), consonants = 1 ([&quot;b&quot;]). - Substring &quot;ab<u>ba</u>&quot;, vowels = 1 ([&quot;a&quot;]), consonants = 1 ([&quot;b&quot;]). - Substring &quot;<u>abba</u>&quot;, vowels = 2 ([&quot;a&quot;,&quot;a&quot;]), consonants = 2 ([&quot;b&quot;,&quot;b&quot;]). It can be shown that there are only 3 beautiful substrings in the given string. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;bcdf&quot;, k = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> There are no beautiful substrings in the given string. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 1000</code></li> <li><code>s</code> consists of only English lowercase letters.</li> </ul>
Hash Table; Math; String; Enumeration; Number Theory; Prefix Sum
TypeScript
function beautifulSubstrings(s: string, k: number): number { const n = s.length; const vs: number[] = Array(26).fill(0); for (const c of 'aeiou') { vs[c.charCodeAt(0) - 'a'.charCodeAt(0)] = 1; } let ans = 0; for (let i = 0; i < n; ++i) { let vowels = 0; for (let j = i; j < n; ++j) { vowels += vs[s.charCodeAt(j) - 'a'.charCodeAt(0)]; const consonants = j - i + 1 - vowels; if (vowels === consonants && (vowels * consonants) % k === 0) { ++ans; } } } return ans; }
2,948
Make Lexicographically Smallest Array by Swapping Elements
Medium
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code> and a <strong>positive</strong> integer <code>limit</code>.</p> <p>In one operation, you can choose any two indices <code>i</code> and <code>j</code> and swap <code>nums[i]</code> and <code>nums[j]</code> <strong>if</strong> <code>|nums[i] - nums[j]| &lt;= limit</code>.</p> <p>Return <em>the <strong>lexicographically smallest array</strong> that can be obtained by performing the operation any number of times</em>.</p> <p>An array <code>a</code> is lexicographically smaller than an array <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, array <code>a</code> has an element that is less than the corresponding element in <code>b</code>. For example, the array <code>[2,10,3]</code> is lexicographically smaller than the array <code>[10,2,3]</code> because they differ at index <code>0</code> and <code>2 &lt; 10</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,3,9,8], limit = 2 <strong>Output:</strong> [1,3,5,8,9] <strong>Explanation:</strong> Apply the operation 2 times: - Swap nums[1] with nums[2]. The array becomes [1,3,5,9,8] - Swap nums[3] with nums[4]. The array becomes [1,3,5,8,9] We cannot obtain a lexicographically smaller array by applying any more operations. Note that it may be possible to get the same result by doing different operations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,6,18,2,1], limit = 3 <strong>Output:</strong> [1,6,7,18,1,2] <strong>Explanation:</strong> Apply the operation 3 times: - Swap nums[1] with nums[2]. The array becomes [1,6,7,18,2,1] - Swap nums[0] with nums[4]. The array becomes [2,6,7,18,1,1] - Swap nums[0] with nums[5]. The array becomes [1,6,7,18,1,2] We cannot obtain a lexicographically smaller array by applying any more operations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,28,19,10], limit = 3 <strong>Output:</strong> [1,7,28,19,10] <strong>Explanation:</strong> [1,7,28,19,10] is the lexicographically smallest array we can obtain because we cannot apply the operation on any two indices. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= limit &lt;= 10<sup>9</sup></code></li> </ul>
Union Find; Array; Sorting
C++
class Solution { public: vector<int> lexicographicallySmallestArray(vector<int>& nums, int limit) { int n = nums.size(); vector<int> idx(n); iota(idx.begin(), idx.end(), 0); sort(idx.begin(), idx.end(), [&](int i, int j) { return nums[i] < nums[j]; }); vector<int> ans(n); for (int i = 0; i < n;) { int j = i + 1; while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { ++j; } vector<int> t(idx.begin() + i, idx.begin() + j); sort(t.begin(), t.end()); for (int k = i; k < j; ++k) { ans[t[k - i]] = nums[idx[k]]; } i = j; } return ans; } };
2,948
Make Lexicographically Smallest Array by Swapping Elements
Medium
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code> and a <strong>positive</strong> integer <code>limit</code>.</p> <p>In one operation, you can choose any two indices <code>i</code> and <code>j</code> and swap <code>nums[i]</code> and <code>nums[j]</code> <strong>if</strong> <code>|nums[i] - nums[j]| &lt;= limit</code>.</p> <p>Return <em>the <strong>lexicographically smallest array</strong> that can be obtained by performing the operation any number of times</em>.</p> <p>An array <code>a</code> is lexicographically smaller than an array <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, array <code>a</code> has an element that is less than the corresponding element in <code>b</code>. For example, the array <code>[2,10,3]</code> is lexicographically smaller than the array <code>[10,2,3]</code> because they differ at index <code>0</code> and <code>2 &lt; 10</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,3,9,8], limit = 2 <strong>Output:</strong> [1,3,5,8,9] <strong>Explanation:</strong> Apply the operation 2 times: - Swap nums[1] with nums[2]. The array becomes [1,3,5,9,8] - Swap nums[3] with nums[4]. The array becomes [1,3,5,8,9] We cannot obtain a lexicographically smaller array by applying any more operations. Note that it may be possible to get the same result by doing different operations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,6,18,2,1], limit = 3 <strong>Output:</strong> [1,6,7,18,1,2] <strong>Explanation:</strong> Apply the operation 3 times: - Swap nums[1] with nums[2]. The array becomes [1,6,7,18,2,1] - Swap nums[0] with nums[4]. The array becomes [2,6,7,18,1,1] - Swap nums[0] with nums[5]. The array becomes [1,6,7,18,1,2] We cannot obtain a lexicographically smaller array by applying any more operations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,28,19,10], limit = 3 <strong>Output:</strong> [1,7,28,19,10] <strong>Explanation:</strong> [1,7,28,19,10] is the lexicographically smallest array we can obtain because we cannot apply the operation on any two indices. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= limit &lt;= 10<sup>9</sup></code></li> </ul>
Union Find; Array; Sorting
Go
func lexicographicallySmallestArray(nums []int, limit int) []int { n := len(nums) idx := make([]int, n) for i := range idx { idx[i] = i } slices.SortFunc(idx, func(i, j int) int { return nums[i] - nums[j] }) ans := make([]int, n) for i := 0; i < n; { j := i + 1 for j < n && nums[idx[j]]-nums[idx[j-1]] <= limit { j++ } t := slices.Clone(idx[i:j]) slices.Sort(t) for k := i; k < j; k++ { ans[t[k-i]] = nums[idx[k]] } i = j } return ans }
2,948
Make Lexicographically Smallest Array by Swapping Elements
Medium
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code> and a <strong>positive</strong> integer <code>limit</code>.</p> <p>In one operation, you can choose any two indices <code>i</code> and <code>j</code> and swap <code>nums[i]</code> and <code>nums[j]</code> <strong>if</strong> <code>|nums[i] - nums[j]| &lt;= limit</code>.</p> <p>Return <em>the <strong>lexicographically smallest array</strong> that can be obtained by performing the operation any number of times</em>.</p> <p>An array <code>a</code> is lexicographically smaller than an array <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, array <code>a</code> has an element that is less than the corresponding element in <code>b</code>. For example, the array <code>[2,10,3]</code> is lexicographically smaller than the array <code>[10,2,3]</code> because they differ at index <code>0</code> and <code>2 &lt; 10</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,3,9,8], limit = 2 <strong>Output:</strong> [1,3,5,8,9] <strong>Explanation:</strong> Apply the operation 2 times: - Swap nums[1] with nums[2]. The array becomes [1,3,5,9,8] - Swap nums[3] with nums[4]. The array becomes [1,3,5,8,9] We cannot obtain a lexicographically smaller array by applying any more operations. Note that it may be possible to get the same result by doing different operations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,6,18,2,1], limit = 3 <strong>Output:</strong> [1,6,7,18,1,2] <strong>Explanation:</strong> Apply the operation 3 times: - Swap nums[1] with nums[2]. The array becomes [1,6,7,18,2,1] - Swap nums[0] with nums[4]. The array becomes [2,6,7,18,1,1] - Swap nums[0] with nums[5]. The array becomes [1,6,7,18,1,2] We cannot obtain a lexicographically smaller array by applying any more operations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,28,19,10], limit = 3 <strong>Output:</strong> [1,7,28,19,10] <strong>Explanation:</strong> [1,7,28,19,10] is the lexicographically smallest array we can obtain because we cannot apply the operation on any two indices. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= limit &lt;= 10<sup>9</sup></code></li> </ul>
Union Find; Array; Sorting
Java
class Solution { public int[] lexicographicallySmallestArray(int[] nums, int limit) { int n = nums.length; Integer[] idx = new Integer[n]; Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); int[] ans = new int[n]; for (int i = 0; i < n;) { int j = i + 1; while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { ++j; } Integer[] t = Arrays.copyOfRange(idx, i, j); Arrays.sort(t, (x, y) -> x - y); for (int k = i; k < j; ++k) { ans[t[k - i]] = nums[idx[k]]; } i = j; } return ans; } }
2,948
Make Lexicographically Smallest Array by Swapping Elements
Medium
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code> and a <strong>positive</strong> integer <code>limit</code>.</p> <p>In one operation, you can choose any two indices <code>i</code> and <code>j</code> and swap <code>nums[i]</code> and <code>nums[j]</code> <strong>if</strong> <code>|nums[i] - nums[j]| &lt;= limit</code>.</p> <p>Return <em>the <strong>lexicographically smallest array</strong> that can be obtained by performing the operation any number of times</em>.</p> <p>An array <code>a</code> is lexicographically smaller than an array <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, array <code>a</code> has an element that is less than the corresponding element in <code>b</code>. For example, the array <code>[2,10,3]</code> is lexicographically smaller than the array <code>[10,2,3]</code> because they differ at index <code>0</code> and <code>2 &lt; 10</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,3,9,8], limit = 2 <strong>Output:</strong> [1,3,5,8,9] <strong>Explanation:</strong> Apply the operation 2 times: - Swap nums[1] with nums[2]. The array becomes [1,3,5,9,8] - Swap nums[3] with nums[4]. The array becomes [1,3,5,8,9] We cannot obtain a lexicographically smaller array by applying any more operations. Note that it may be possible to get the same result by doing different operations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,6,18,2,1], limit = 3 <strong>Output:</strong> [1,6,7,18,1,2] <strong>Explanation:</strong> Apply the operation 3 times: - Swap nums[1] with nums[2]. The array becomes [1,6,7,18,2,1] - Swap nums[0] with nums[4]. The array becomes [2,6,7,18,1,1] - Swap nums[0] with nums[5]. The array becomes [1,6,7,18,1,2] We cannot obtain a lexicographically smaller array by applying any more operations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,28,19,10], limit = 3 <strong>Output:</strong> [1,7,28,19,10] <strong>Explanation:</strong> [1,7,28,19,10] is the lexicographically smallest array we can obtain because we cannot apply the operation on any two indices. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= limit &lt;= 10<sup>9</sup></code></li> </ul>
Union Find; Array; Sorting
Python
class Solution: def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]: n = len(nums) arr = sorted(zip(nums, range(n))) ans = [0] * n i = 0 while i < n: j = i + 1 while j < n and arr[j][0] - arr[j - 1][0] <= limit: j += 1 idx = sorted(k for _, k in arr[i:j]) for k, (x, _) in zip(idx, arr[i:j]): ans[k] = x i = j return ans
2,948
Make Lexicographically Smallest Array by Swapping Elements
Medium
<p>You are given a <strong>0-indexed</strong> array of <strong>positive</strong> integers <code>nums</code> and a <strong>positive</strong> integer <code>limit</code>.</p> <p>In one operation, you can choose any two indices <code>i</code> and <code>j</code> and swap <code>nums[i]</code> and <code>nums[j]</code> <strong>if</strong> <code>|nums[i] - nums[j]| &lt;= limit</code>.</p> <p>Return <em>the <strong>lexicographically smallest array</strong> that can be obtained by performing the operation any number of times</em>.</p> <p>An array <code>a</code> is lexicographically smaller than an array <code>b</code> if in the first position where <code>a</code> and <code>b</code> differ, array <code>a</code> has an element that is less than the corresponding element in <code>b</code>. For example, the array <code>[2,10,3]</code> is lexicographically smaller than the array <code>[10,2,3]</code> because they differ at index <code>0</code> and <code>2 &lt; 10</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,3,9,8], limit = 2 <strong>Output:</strong> [1,3,5,8,9] <strong>Explanation:</strong> Apply the operation 2 times: - Swap nums[1] with nums[2]. The array becomes [1,3,5,9,8] - Swap nums[3] with nums[4]. The array becomes [1,3,5,8,9] We cannot obtain a lexicographically smaller array by applying any more operations. Note that it may be possible to get the same result by doing different operations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,6,18,2,1], limit = 3 <strong>Output:</strong> [1,6,7,18,1,2] <strong>Explanation:</strong> Apply the operation 3 times: - Swap nums[1] with nums[2]. The array becomes [1,6,7,18,2,1] - Swap nums[0] with nums[4]. The array becomes [2,6,7,18,1,1] - Swap nums[0] with nums[5]. The array becomes [1,6,7,18,1,2] We cannot obtain a lexicographically smaller array by applying any more operations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,7,28,19,10], limit = 3 <strong>Output:</strong> [1,7,28,19,10] <strong>Explanation:</strong> [1,7,28,19,10] is the lexicographically smallest array we can obtain because we cannot apply the operation on any two indices. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= limit &lt;= 10<sup>9</sup></code></li> </ul>
Union Find; Array; Sorting
TypeScript
function lexicographicallySmallestArray(nums: number[], limit: number): number[] { const n: number = nums.length; const idx: number[] = Array.from({ length: n }, (_, i) => i); idx.sort((i, j) => nums[i] - nums[j]); const ans: number[] = Array(n).fill(0); for (let i = 0; i < n; ) { let j = i + 1; while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { j++; } const t: number[] = idx.slice(i, j).sort((a, b) => a - b); for (let k: number = i; k < j; k++) { ans[t[k - i]] = nums[idx[k]]; } i = j; } return ans; }
2,949
Count Beautiful Substrings II
Hard
<p>You are given a string <code>s</code> and a positive integer <code>k</code>.</p> <p>Let <code>vowels</code> and <code>consonants</code> be the number of vowels and consonants in a string.</p> <p>A string is <strong>beautiful</strong> if:</p> <ul> <li><code>vowels == consonants</code>.</li> <li><code>(vowels * consonants) % k == 0</code>, in other terms the multiplication of <code>vowels</code> and <code>consonants</code> is divisible by <code>k</code>.</li> </ul> <p>Return <em>the number of <strong>non-empty beautiful substrings</strong> in the given string</em> <code>s</code>.</p> <p>A <strong>substring</strong> is a contiguous sequence of characters in a string.</p> <p><strong>Vowel letters</strong> in English are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>.</p> <p><strong>Consonant letters</strong> in English are every letter except vowels.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;baeyh&quot;, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> There are 2 beautiful substrings in the given string. - Substring &quot;b<u>aeyh</u>&quot;, vowels = 2 ([&quot;a&quot;,e&quot;]), consonants = 2 ([&quot;y&quot;,&quot;h&quot;]). You can see that string &quot;aeyh&quot; is beautiful as vowels == consonants and vowels * consonants % k == 0. - Substring &quot;<u>baey</u>h&quot;, vowels = 2 ([&quot;a&quot;,e&quot;]), consonants = 2 ([&quot;b&quot;,&quot;y&quot;]). You can see that string &quot;baey&quot; is beautiful as vowels == consonants and vowels * consonants % k == 0. It can be shown that there are only 2 beautiful substrings in the given string. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abba&quot;, k = 1 <strong>Output:</strong> 3 <strong>Explanation:</strong> There are 3 beautiful substrings in the given string. - Substring &quot;<u>ab</u>ba&quot;, vowels = 1 ([&quot;a&quot;]), consonants = 1 ([&quot;b&quot;]). - Substring &quot;ab<u>ba</u>&quot;, vowels = 1 ([&quot;a&quot;]), consonants = 1 ([&quot;b&quot;]). - Substring &quot;<u>abba</u>&quot;, vowels = 2 ([&quot;a&quot;,&quot;a&quot;]), consonants = 2 ([&quot;b&quot;,&quot;b&quot;]). It can be shown that there are only 3 beautiful substrings in the given string. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;bcdf&quot;, k = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> There are no beautiful substrings in the given string. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>1 &lt;= k &lt;= 1000</code></li> <li><code>s</code> consists of only English lowercase letters.</li> </ul>
Hash Table; Math; String; Number Theory; Prefix Sum
TypeScript
function beautifulSubstrings(s: string, k: number): number { const l = pSqrt(k * 4); const n = s.length; let sum = n; let ans = 0; const counter = new Map(); counter.set(((l - 1) << 17) | sum, 1); for (let i = 0; i < n; i++) { const char = s[i]; const bit = (AEIOU_MASK >> (char.charCodeAt(0) - 'a'.charCodeAt(0))) & 1; sum += bit * 2 - 1; // 1 -> 1 0 -> -1 const key = (i % l << 17) | sum; ans += counter.get(key) || 0; // ans += cnt[(i%k,sum)]++ counter.set(key, (counter.get(key) ?? 0) + 1); } return ans; } const AEIOU_MASK = 1065233; function pSqrt(n: number) { let res = 1; for (let i = 2; i * i <= n; i++) { let i2 = i * i; while (n % i2 == 0) { res *= i; n /= i2; } if (n % i == 0) { res *= i; n /= i; } } if (n > 1) { res *= n; } return res; }
2,950
Number of Divisible Substrings
Medium
<p>Each character of the English alphabet has been mapped to a digit as shown below.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2950.Number%20of%20Divisible%20Substrings/images/old_phone_digits.png" style="padding: 10px; width: 200px; height: 200px;" /></p> <p>A string is <strong>divisible</strong> if the sum of the mapped values of its characters is divisible by its length.</p> <p>Given a string <code>s</code>, return <em>the number of <strong>divisible substrings</strong> of</em> <code>s</code>.</p> <p>A <strong>substring</strong> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <th style="padding: 5px; border: 1px solid black;">Substring</th> <th style="padding: 5px; border: 1px solid black;">Mapped</th> <th style="padding: 5px; border: 1px solid black;">Sum</th> <th style="padding: 5px; border: 1px solid black;">Length</th> <th style="padding: 5px; border: 1px solid black;">Divisible?</th> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">a</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">s</td> <td style="padding: 5px; border: 1px solid black;">7</td> <td style="padding: 5px; border: 1px solid black;">7</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">d</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">f</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">as</td> <td style="padding: 5px; border: 1px solid black;">1, 7</td> <td style="padding: 5px; border: 1px solid black;">8</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">sd</td> <td style="padding: 5px; border: 1px solid black;">7, 2</td> <td style="padding: 5px; border: 1px solid black;">9</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">df</td> <td style="padding: 5px; border: 1px solid black;">2, 3</td> <td style="padding: 5px; border: 1px solid black;">5</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">asd</td> <td style="padding: 5px; border: 1px solid black;">1, 7, 2</td> <td style="padding: 5px; border: 1px solid black;">10</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">sdf</td> <td style="padding: 5px; border: 1px solid black;">7, 2, 3</td> <td style="padding: 5px; border: 1px solid black;">12</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">asdf</td> <td style="padding: 5px; border: 1px solid black;">1, 7, 2, 3</td> <td style="padding: 5px; border: 1px solid black;">13</td> <td style="padding: 5px; border: 1px solid black;">4</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> </tbody> </table> <pre> <strong>Input:</strong> word = &quot;asdf&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The table above contains the details about every substring of word, and we can see that 6 of them are divisible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;bdh&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The 4 divisible substrings are: &quot;b&quot;, &quot;d&quot;, &quot;h&quot;, &quot;bdh&quot;. It can be shown that there are no other substrings of word that are divisible. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcd&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The 6 divisible substrings are: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;ab&quot;, &quot;cd&quot;. It can be shown that there are no other substrings of word that are divisible. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 2000</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Counting; Prefix Sum
C++
class Solution { public: int countDivisibleSubstrings(string word) { string d[9] = {"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"}; int mp[26]{}; for (int i = 0; i < 9; ++i) { for (char& c : d[i]) { mp[c - 'a'] = i + 1; } } int ans = 0; int n = word.size(); for (int i = 0; i < n; ++i) { int s = 0; for (int j = i; j < n; ++j) { s += mp[word[j] - 'a']; ans += s % (j - i + 1) == 0 ? 1 : 0; } } return ans; } };
2,950
Number of Divisible Substrings
Medium
<p>Each character of the English alphabet has been mapped to a digit as shown below.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2950.Number%20of%20Divisible%20Substrings/images/old_phone_digits.png" style="padding: 10px; width: 200px; height: 200px;" /></p> <p>A string is <strong>divisible</strong> if the sum of the mapped values of its characters is divisible by its length.</p> <p>Given a string <code>s</code>, return <em>the number of <strong>divisible substrings</strong> of</em> <code>s</code>.</p> <p>A <strong>substring</strong> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <th style="padding: 5px; border: 1px solid black;">Substring</th> <th style="padding: 5px; border: 1px solid black;">Mapped</th> <th style="padding: 5px; border: 1px solid black;">Sum</th> <th style="padding: 5px; border: 1px solid black;">Length</th> <th style="padding: 5px; border: 1px solid black;">Divisible?</th> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">a</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">s</td> <td style="padding: 5px; border: 1px solid black;">7</td> <td style="padding: 5px; border: 1px solid black;">7</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">d</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">f</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">as</td> <td style="padding: 5px; border: 1px solid black;">1, 7</td> <td style="padding: 5px; border: 1px solid black;">8</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">sd</td> <td style="padding: 5px; border: 1px solid black;">7, 2</td> <td style="padding: 5px; border: 1px solid black;">9</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">df</td> <td style="padding: 5px; border: 1px solid black;">2, 3</td> <td style="padding: 5px; border: 1px solid black;">5</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">asd</td> <td style="padding: 5px; border: 1px solid black;">1, 7, 2</td> <td style="padding: 5px; border: 1px solid black;">10</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">sdf</td> <td style="padding: 5px; border: 1px solid black;">7, 2, 3</td> <td style="padding: 5px; border: 1px solid black;">12</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">asdf</td> <td style="padding: 5px; border: 1px solid black;">1, 7, 2, 3</td> <td style="padding: 5px; border: 1px solid black;">13</td> <td style="padding: 5px; border: 1px solid black;">4</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> </tbody> </table> <pre> <strong>Input:</strong> word = &quot;asdf&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The table above contains the details about every substring of word, and we can see that 6 of them are divisible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;bdh&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The 4 divisible substrings are: &quot;b&quot;, &quot;d&quot;, &quot;h&quot;, &quot;bdh&quot;. It can be shown that there are no other substrings of word that are divisible. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcd&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The 6 divisible substrings are: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;ab&quot;, &quot;cd&quot;. It can be shown that there are no other substrings of word that are divisible. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 2000</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Counting; Prefix Sum
Go
func countDivisibleSubstrings(word string) (ans int) { d := []string{"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"} mp := [26]int{} for i, s := range d { for _, c := range s { mp[c-'a'] = i + 1 } } n := len(word) for i := 0; i < n; i++ { s := 0 for j := i; j < n; j++ { s += mp[word[j]-'a'] if s%(j-i+1) == 0 { ans++ } } } return }
2,950
Number of Divisible Substrings
Medium
<p>Each character of the English alphabet has been mapped to a digit as shown below.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2950.Number%20of%20Divisible%20Substrings/images/old_phone_digits.png" style="padding: 10px; width: 200px; height: 200px;" /></p> <p>A string is <strong>divisible</strong> if the sum of the mapped values of its characters is divisible by its length.</p> <p>Given a string <code>s</code>, return <em>the number of <strong>divisible substrings</strong> of</em> <code>s</code>.</p> <p>A <strong>substring</strong> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <th style="padding: 5px; border: 1px solid black;">Substring</th> <th style="padding: 5px; border: 1px solid black;">Mapped</th> <th style="padding: 5px; border: 1px solid black;">Sum</th> <th style="padding: 5px; border: 1px solid black;">Length</th> <th style="padding: 5px; border: 1px solid black;">Divisible?</th> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">a</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">s</td> <td style="padding: 5px; border: 1px solid black;">7</td> <td style="padding: 5px; border: 1px solid black;">7</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">d</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">f</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">as</td> <td style="padding: 5px; border: 1px solid black;">1, 7</td> <td style="padding: 5px; border: 1px solid black;">8</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">sd</td> <td style="padding: 5px; border: 1px solid black;">7, 2</td> <td style="padding: 5px; border: 1px solid black;">9</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">df</td> <td style="padding: 5px; border: 1px solid black;">2, 3</td> <td style="padding: 5px; border: 1px solid black;">5</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">asd</td> <td style="padding: 5px; border: 1px solid black;">1, 7, 2</td> <td style="padding: 5px; border: 1px solid black;">10</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">sdf</td> <td style="padding: 5px; border: 1px solid black;">7, 2, 3</td> <td style="padding: 5px; border: 1px solid black;">12</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">asdf</td> <td style="padding: 5px; border: 1px solid black;">1, 7, 2, 3</td> <td style="padding: 5px; border: 1px solid black;">13</td> <td style="padding: 5px; border: 1px solid black;">4</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> </tbody> </table> <pre> <strong>Input:</strong> word = &quot;asdf&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The table above contains the details about every substring of word, and we can see that 6 of them are divisible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;bdh&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The 4 divisible substrings are: &quot;b&quot;, &quot;d&quot;, &quot;h&quot;, &quot;bdh&quot;. It can be shown that there are no other substrings of word that are divisible. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcd&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The 6 divisible substrings are: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;ab&quot;, &quot;cd&quot;. It can be shown that there are no other substrings of word that are divisible. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 2000</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Counting; Prefix Sum
Java
class Solution { public int countDivisibleSubstrings(String word) { String[] d = {"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"}; int[] mp = new int[26]; for (int i = 0; i < d.length; ++i) { for (char c : d[i].toCharArray()) { mp[c - 'a'] = i + 1; } } int ans = 0; int n = word.length(); for (int i = 0; i < n; ++i) { int s = 0; for (int j = i; j < n; ++j) { s += mp[word.charAt(j) - 'a']; ans += s % (j - i + 1) == 0 ? 1 : 0; } } return ans; } }
2,950
Number of Divisible Substrings
Medium
<p>Each character of the English alphabet has been mapped to a digit as shown below.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2950.Number%20of%20Divisible%20Substrings/images/old_phone_digits.png" style="padding: 10px; width: 200px; height: 200px;" /></p> <p>A string is <strong>divisible</strong> if the sum of the mapped values of its characters is divisible by its length.</p> <p>Given a string <code>s</code>, return <em>the number of <strong>divisible substrings</strong> of</em> <code>s</code>.</p> <p>A <strong>substring</strong> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <th style="padding: 5px; border: 1px solid black;">Substring</th> <th style="padding: 5px; border: 1px solid black;">Mapped</th> <th style="padding: 5px; border: 1px solid black;">Sum</th> <th style="padding: 5px; border: 1px solid black;">Length</th> <th style="padding: 5px; border: 1px solid black;">Divisible?</th> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">a</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">s</td> <td style="padding: 5px; border: 1px solid black;">7</td> <td style="padding: 5px; border: 1px solid black;">7</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">d</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">f</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">as</td> <td style="padding: 5px; border: 1px solid black;">1, 7</td> <td style="padding: 5px; border: 1px solid black;">8</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">sd</td> <td style="padding: 5px; border: 1px solid black;">7, 2</td> <td style="padding: 5px; border: 1px solid black;">9</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">df</td> <td style="padding: 5px; border: 1px solid black;">2, 3</td> <td style="padding: 5px; border: 1px solid black;">5</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">asd</td> <td style="padding: 5px; border: 1px solid black;">1, 7, 2</td> <td style="padding: 5px; border: 1px solid black;">10</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">sdf</td> <td style="padding: 5px; border: 1px solid black;">7, 2, 3</td> <td style="padding: 5px; border: 1px solid black;">12</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">asdf</td> <td style="padding: 5px; border: 1px solid black;">1, 7, 2, 3</td> <td style="padding: 5px; border: 1px solid black;">13</td> <td style="padding: 5px; border: 1px solid black;">4</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> </tbody> </table> <pre> <strong>Input:</strong> word = &quot;asdf&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The table above contains the details about every substring of word, and we can see that 6 of them are divisible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;bdh&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The 4 divisible substrings are: &quot;b&quot;, &quot;d&quot;, &quot;h&quot;, &quot;bdh&quot;. It can be shown that there are no other substrings of word that are divisible. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcd&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The 6 divisible substrings are: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;ab&quot;, &quot;cd&quot;. It can be shown that there are no other substrings of word that are divisible. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 2000</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Counting; Prefix Sum
Python
class Solution: def countDivisibleSubstrings(self, word: str) -> int: d = ["ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"] mp = {} for i, s in enumerate(d, 1): for c in s: mp[c] = i ans = 0 n = len(word) for i in range(n): s = 0 for j in range(i, n): s += mp[word[j]] ans += s % (j - i + 1) == 0 return ans
2,950
Number of Divisible Substrings
Medium
<p>Each character of the English alphabet has been mapped to a digit as shown below.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2950.Number%20of%20Divisible%20Substrings/images/old_phone_digits.png" style="padding: 10px; width: 200px; height: 200px;" /></p> <p>A string is <strong>divisible</strong> if the sum of the mapped values of its characters is divisible by its length.</p> <p>Given a string <code>s</code>, return <em>the number of <strong>divisible substrings</strong> of</em> <code>s</code>.</p> <p>A <strong>substring</strong> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <th style="padding: 5px; border: 1px solid black;">Substring</th> <th style="padding: 5px; border: 1px solid black;">Mapped</th> <th style="padding: 5px; border: 1px solid black;">Sum</th> <th style="padding: 5px; border: 1px solid black;">Length</th> <th style="padding: 5px; border: 1px solid black;">Divisible?</th> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">a</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">s</td> <td style="padding: 5px; border: 1px solid black;">7</td> <td style="padding: 5px; border: 1px solid black;">7</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">d</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">f</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">as</td> <td style="padding: 5px; border: 1px solid black;">1, 7</td> <td style="padding: 5px; border: 1px solid black;">8</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">sd</td> <td style="padding: 5px; border: 1px solid black;">7, 2</td> <td style="padding: 5px; border: 1px solid black;">9</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">df</td> <td style="padding: 5px; border: 1px solid black;">2, 3</td> <td style="padding: 5px; border: 1px solid black;">5</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">asd</td> <td style="padding: 5px; border: 1px solid black;">1, 7, 2</td> <td style="padding: 5px; border: 1px solid black;">10</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">sdf</td> <td style="padding: 5px; border: 1px solid black;">7, 2, 3</td> <td style="padding: 5px; border: 1px solid black;">12</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">asdf</td> <td style="padding: 5px; border: 1px solid black;">1, 7, 2, 3</td> <td style="padding: 5px; border: 1px solid black;">13</td> <td style="padding: 5px; border: 1px solid black;">4</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> </tbody> </table> <pre> <strong>Input:</strong> word = &quot;asdf&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The table above contains the details about every substring of word, and we can see that 6 of them are divisible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;bdh&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The 4 divisible substrings are: &quot;b&quot;, &quot;d&quot;, &quot;h&quot;, &quot;bdh&quot;. It can be shown that there are no other substrings of word that are divisible. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcd&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The 6 divisible substrings are: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;ab&quot;, &quot;cd&quot;. It can be shown that there are no other substrings of word that are divisible. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 2000</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Counting; Prefix Sum
Rust
impl Solution { pub fn count_divisible_substrings(word: String) -> i32 { let d = vec!["ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"]; let mut mp = vec![0; 26]; for (i, s) in d.iter().enumerate() { s.chars().for_each(|c| { mp[(c as usize) - ('a' as usize)] = (i + 1) as i32; }); } let mut ans = 0; let n = word.len(); for i in 0..n { let mut s = 0; for j in i..n { s += mp[(word.as_bytes()[j] as usize) - ('a' as usize)]; ans += (s % ((j - i + 1) as i32) == 0) as i32; } } ans } }
2,950
Number of Divisible Substrings
Medium
<p>Each character of the English alphabet has been mapped to a digit as shown below.</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2950.Number%20of%20Divisible%20Substrings/images/old_phone_digits.png" style="padding: 10px; width: 200px; height: 200px;" /></p> <p>A string is <strong>divisible</strong> if the sum of the mapped values of its characters is divisible by its length.</p> <p>Given a string <code>s</code>, return <em>the number of <strong>divisible substrings</strong> of</em> <code>s</code>.</p> <p>A <strong>substring</strong> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <table border="1" cellspacing="3" style="border-collapse: separate; text-align: center;"> <tbody> <tr> <th style="padding: 5px; border: 1px solid black;">Substring</th> <th style="padding: 5px; border: 1px solid black;">Mapped</th> <th style="padding: 5px; border: 1px solid black;">Sum</th> <th style="padding: 5px; border: 1px solid black;">Length</th> <th style="padding: 5px; border: 1px solid black;">Divisible?</th> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">a</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">s</td> <td style="padding: 5px; border: 1px solid black;">7</td> <td style="padding: 5px; border: 1px solid black;">7</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">d</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">f</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">1</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">as</td> <td style="padding: 5px; border: 1px solid black;">1, 7</td> <td style="padding: 5px; border: 1px solid black;">8</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">sd</td> <td style="padding: 5px; border: 1px solid black;">7, 2</td> <td style="padding: 5px; border: 1px solid black;">9</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">df</td> <td style="padding: 5px; border: 1px solid black;">2, 3</td> <td style="padding: 5px; border: 1px solid black;">5</td> <td style="padding: 5px; border: 1px solid black;">2</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">asd</td> <td style="padding: 5px; border: 1px solid black;">1, 7, 2</td> <td style="padding: 5px; border: 1px solid black;">10</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">sdf</td> <td style="padding: 5px; border: 1px solid black;">7, 2, 3</td> <td style="padding: 5px; border: 1px solid black;">12</td> <td style="padding: 5px; border: 1px solid black;">3</td> <td style="padding: 5px; border: 1px solid black;">Yes</td> </tr> <tr> <td style="padding: 5px; border: 1px solid black;">asdf</td> <td style="padding: 5px; border: 1px solid black;">1, 7, 2, 3</td> <td style="padding: 5px; border: 1px solid black;">13</td> <td style="padding: 5px; border: 1px solid black;">4</td> <td style="padding: 5px; border: 1px solid black;">No</td> </tr> </tbody> </table> <pre> <strong>Input:</strong> word = &quot;asdf&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The table above contains the details about every substring of word, and we can see that 6 of them are divisible. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;bdh&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The 4 divisible substrings are: &quot;b&quot;, &quot;d&quot;, &quot;h&quot;, &quot;bdh&quot;. It can be shown that there are no other substrings of word that are divisible. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;abcd&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The 6 divisible substrings are: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;ab&quot;, &quot;cd&quot;. It can be shown that there are no other substrings of word that are divisible. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 2000</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Counting; Prefix Sum
TypeScript
function countDivisibleSubstrings(word: string): number { const d: string[] = ['ab', 'cde', 'fgh', 'ijk', 'lmn', 'opq', 'rst', 'uvw', 'xyz']; const mp: number[] = Array(26).fill(0); for (let i = 0; i < d.length; ++i) { for (const c of d[i]) { mp[c.charCodeAt(0) - 'a'.charCodeAt(0)] = i + 1; } } const n = word.length; let ans = 0; for (let i = 0; i < n; ++i) { let s = 0; for (let j = i; j < n; ++j) { s += mp[word.charCodeAt(j) - 'a'.charCodeAt(0)]; if (s % (j - i + 1) === 0) { ++ans; } } } return ans; }
2,951
Find the Peaks
Easy
<p>You are given a <strong>0-indexed</strong> array <code>mountain</code>. Your task is to find all the <strong>peaks</strong> in the <code>mountain</code> array.</p> <p>Return <em>an array that consists of </em>indices<!-- notionvc: c9879de8-88bd-43b0-8224-40c4bee71cd6 --><em> of <strong>peaks</strong> in the given array in <strong>any order</strong>.</em></p> <p><strong>Notes:</strong></p> <ul> <li>A <strong>peak</strong> is defined as an element that is <strong>strictly greater</strong> than its neighboring elements.</li> <li>The first and last elements of the array are <strong>not</strong> a peak.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> mountain = [2,4,4] <strong>Output:</strong> [] <strong>Explanation:</strong> mountain[0] and mountain[2] can not be a peak because they are first and last elements of the array. mountain[1] also can not be a peak because it is not strictly greater than mountain[2]. So the answer is []. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mountain = [1,4,3,8,5] <strong>Output:</strong> [1,3] <strong>Explanation:</strong> mountain[0] and mountain[4] can not be a peak because they are first and last elements of the array. mountain[2] also can not be a peak because it is not strictly greater than mountain[3] and mountain[1]. But mountain [1] and mountain[3] are strictly greater than their neighboring elements. So the answer is [1,3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= mountain.length &lt;= 100</code></li> <li><code>1 &lt;= mountain[i] &lt;= 100</code></li> </ul>
Array; Enumeration
C++
class Solution { public: vector<int> findPeaks(vector<int>& mountain) { vector<int> ans; for (int i = 1; i < mountain.size() - 1; ++i) { if (mountain[i - 1] < mountain[i] && mountain[i + 1] < mountain[i]) { ans.push_back(i); } } return ans; } };
2,951
Find the Peaks
Easy
<p>You are given a <strong>0-indexed</strong> array <code>mountain</code>. Your task is to find all the <strong>peaks</strong> in the <code>mountain</code> array.</p> <p>Return <em>an array that consists of </em>indices<!-- notionvc: c9879de8-88bd-43b0-8224-40c4bee71cd6 --><em> of <strong>peaks</strong> in the given array in <strong>any order</strong>.</em></p> <p><strong>Notes:</strong></p> <ul> <li>A <strong>peak</strong> is defined as an element that is <strong>strictly greater</strong> than its neighboring elements.</li> <li>The first and last elements of the array are <strong>not</strong> a peak.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> mountain = [2,4,4] <strong>Output:</strong> [] <strong>Explanation:</strong> mountain[0] and mountain[2] can not be a peak because they are first and last elements of the array. mountain[1] also can not be a peak because it is not strictly greater than mountain[2]. So the answer is []. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mountain = [1,4,3,8,5] <strong>Output:</strong> [1,3] <strong>Explanation:</strong> mountain[0] and mountain[4] can not be a peak because they are first and last elements of the array. mountain[2] also can not be a peak because it is not strictly greater than mountain[3] and mountain[1]. But mountain [1] and mountain[3] are strictly greater than their neighboring elements. So the answer is [1,3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= mountain.length &lt;= 100</code></li> <li><code>1 &lt;= mountain[i] &lt;= 100</code></li> </ul>
Array; Enumeration
Go
func findPeaks(mountain []int) (ans []int) { for i := 1; i < len(mountain)-1; i++ { if mountain[i-1] < mountain[i] && mountain[i+1] < mountain[i] { ans = append(ans, i) } } return }
2,951
Find the Peaks
Easy
<p>You are given a <strong>0-indexed</strong> array <code>mountain</code>. Your task is to find all the <strong>peaks</strong> in the <code>mountain</code> array.</p> <p>Return <em>an array that consists of </em>indices<!-- notionvc: c9879de8-88bd-43b0-8224-40c4bee71cd6 --><em> of <strong>peaks</strong> in the given array in <strong>any order</strong>.</em></p> <p><strong>Notes:</strong></p> <ul> <li>A <strong>peak</strong> is defined as an element that is <strong>strictly greater</strong> than its neighboring elements.</li> <li>The first and last elements of the array are <strong>not</strong> a peak.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> mountain = [2,4,4] <strong>Output:</strong> [] <strong>Explanation:</strong> mountain[0] and mountain[2] can not be a peak because they are first and last elements of the array. mountain[1] also can not be a peak because it is not strictly greater than mountain[2]. So the answer is []. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mountain = [1,4,3,8,5] <strong>Output:</strong> [1,3] <strong>Explanation:</strong> mountain[0] and mountain[4] can not be a peak because they are first and last elements of the array. mountain[2] also can not be a peak because it is not strictly greater than mountain[3] and mountain[1]. But mountain [1] and mountain[3] are strictly greater than their neighboring elements. So the answer is [1,3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= mountain.length &lt;= 100</code></li> <li><code>1 &lt;= mountain[i] &lt;= 100</code></li> </ul>
Array; Enumeration
Java
class Solution { public List<Integer> findPeaks(int[] mountain) { List<Integer> ans = new ArrayList<>(); for (int i = 1; i < mountain.length - 1; ++i) { if (mountain[i - 1] < mountain[i] && mountain[i + 1] < mountain[i]) { ans.add(i); } } return ans; } }
2,951
Find the Peaks
Easy
<p>You are given a <strong>0-indexed</strong> array <code>mountain</code>. Your task is to find all the <strong>peaks</strong> in the <code>mountain</code> array.</p> <p>Return <em>an array that consists of </em>indices<!-- notionvc: c9879de8-88bd-43b0-8224-40c4bee71cd6 --><em> of <strong>peaks</strong> in the given array in <strong>any order</strong>.</em></p> <p><strong>Notes:</strong></p> <ul> <li>A <strong>peak</strong> is defined as an element that is <strong>strictly greater</strong> than its neighboring elements.</li> <li>The first and last elements of the array are <strong>not</strong> a peak.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> mountain = [2,4,4] <strong>Output:</strong> [] <strong>Explanation:</strong> mountain[0] and mountain[2] can not be a peak because they are first and last elements of the array. mountain[1] also can not be a peak because it is not strictly greater than mountain[2]. So the answer is []. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mountain = [1,4,3,8,5] <strong>Output:</strong> [1,3] <strong>Explanation:</strong> mountain[0] and mountain[4] can not be a peak because they are first and last elements of the array. mountain[2] also can not be a peak because it is not strictly greater than mountain[3] and mountain[1]. But mountain [1] and mountain[3] are strictly greater than their neighboring elements. So the answer is [1,3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= mountain.length &lt;= 100</code></li> <li><code>1 &lt;= mountain[i] &lt;= 100</code></li> </ul>
Array; Enumeration
Python
class Solution: def findPeaks(self, mountain: List[int]) -> List[int]: return [ i for i in range(1, len(mountain) - 1) if mountain[i - 1] < mountain[i] > mountain[i + 1] ]
2,951
Find the Peaks
Easy
<p>You are given a <strong>0-indexed</strong> array <code>mountain</code>. Your task is to find all the <strong>peaks</strong> in the <code>mountain</code> array.</p> <p>Return <em>an array that consists of </em>indices<!-- notionvc: c9879de8-88bd-43b0-8224-40c4bee71cd6 --><em> of <strong>peaks</strong> in the given array in <strong>any order</strong>.</em></p> <p><strong>Notes:</strong></p> <ul> <li>A <strong>peak</strong> is defined as an element that is <strong>strictly greater</strong> than its neighboring elements.</li> <li>The first and last elements of the array are <strong>not</strong> a peak.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> mountain = [2,4,4] <strong>Output:</strong> [] <strong>Explanation:</strong> mountain[0] and mountain[2] can not be a peak because they are first and last elements of the array. mountain[1] also can not be a peak because it is not strictly greater than mountain[2]. So the answer is []. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> mountain = [1,4,3,8,5] <strong>Output:</strong> [1,3] <strong>Explanation:</strong> mountain[0] and mountain[4] can not be a peak because they are first and last elements of the array. mountain[2] also can not be a peak because it is not strictly greater than mountain[3] and mountain[1]. But mountain [1] and mountain[3] are strictly greater than their neighboring elements. So the answer is [1,3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= mountain.length &lt;= 100</code></li> <li><code>1 &lt;= mountain[i] &lt;= 100</code></li> </ul>
Array; Enumeration
TypeScript
function findPeaks(mountain: number[]): number[] { const ans: number[] = []; for (let i = 1; i < mountain.length - 1; ++i) { if (mountain[i - 1] < mountain[i] && mountain[i + 1] < mountain[i]) { ans.push(i); } } return ans; }
2,952
Minimum Number of Coins to be Added
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>coins</code>, representing the values of the coins available, and an integer <code>target</code>.</p> <p>An integer <code>x</code> is <strong>obtainable</strong> if there exists a subsequence of <code>coins</code> that sums to <code>x</code>.</p> <p>Return <em>the<strong> minimum</strong> number of coins <strong>of any value</strong> that need to be added to the array so that every integer in the range</em> <code>[1, target]</code><em> is <strong>obtainable</strong></em>.</p> <p>A <strong>subsequence</strong> of an array is a new <strong>non-empty</strong> array that is formed from the original array by deleting some (<strong>possibly none</strong>) of the elements without disturbing the relative positions of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> coins = [1,4,10], target = 19 <strong>Output:</strong> 2 <strong>Explanation:</strong> We need to add coins 2 and 8. The resulting array will be [1,2,4,8,10]. It can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 2 is the minimum number of coins that need to be added to the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> coins = [1,4,10,5,7,19], target = 19 <strong>Output:</strong> 1 <strong>Explanation:</strong> We only need to add the coin 2. The resulting array will be [1,2,4,5,7,10,19]. It can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 1 is the minimum number of coins that need to be added to the array. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> coins = [1,1,1], target = 20 <strong>Output:</strong> 3 <strong>Explanation:</strong> We need to add coins 4, 8, and 16. The resulting array will be [1,1,1,4,8,16]. It can be shown that all integers from 1 to 20 are obtainable from the resulting array, and that 3 is the minimum number of coins that need to be added to the array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coins.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coins[i] &lt;= target</code></li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: int minimumAddedCoins(vector<int>& coins, int target) { sort(coins.begin(), coins.end()); int ans = 0; for (int i = 0, s = 1; s <= target;) { if (i < coins.size() && coins[i] <= s) { s += coins[i++]; } else { s <<= 1; ++ans; } } return ans; } };
2,952
Minimum Number of Coins to be Added
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>coins</code>, representing the values of the coins available, and an integer <code>target</code>.</p> <p>An integer <code>x</code> is <strong>obtainable</strong> if there exists a subsequence of <code>coins</code> that sums to <code>x</code>.</p> <p>Return <em>the<strong> minimum</strong> number of coins <strong>of any value</strong> that need to be added to the array so that every integer in the range</em> <code>[1, target]</code><em> is <strong>obtainable</strong></em>.</p> <p>A <strong>subsequence</strong> of an array is a new <strong>non-empty</strong> array that is formed from the original array by deleting some (<strong>possibly none</strong>) of the elements without disturbing the relative positions of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> coins = [1,4,10], target = 19 <strong>Output:</strong> 2 <strong>Explanation:</strong> We need to add coins 2 and 8. The resulting array will be [1,2,4,8,10]. It can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 2 is the minimum number of coins that need to be added to the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> coins = [1,4,10,5,7,19], target = 19 <strong>Output:</strong> 1 <strong>Explanation:</strong> We only need to add the coin 2. The resulting array will be [1,2,4,5,7,10,19]. It can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 1 is the minimum number of coins that need to be added to the array. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> coins = [1,1,1], target = 20 <strong>Output:</strong> 3 <strong>Explanation:</strong> We need to add coins 4, 8, and 16. The resulting array will be [1,1,1,4,8,16]. It can be shown that all integers from 1 to 20 are obtainable from the resulting array, and that 3 is the minimum number of coins that need to be added to the array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coins.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coins[i] &lt;= target</code></li> </ul>
Greedy; Array; Sorting
Go
func minimumAddedCoins(coins []int, target int) (ans int) { slices.Sort(coins) for i, s := 0, 1; s <= target; { if i < len(coins) && coins[i] <= s { s += coins[i] i++ } else { s <<= 1 ans++ } } return }
2,952
Minimum Number of Coins to be Added
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>coins</code>, representing the values of the coins available, and an integer <code>target</code>.</p> <p>An integer <code>x</code> is <strong>obtainable</strong> if there exists a subsequence of <code>coins</code> that sums to <code>x</code>.</p> <p>Return <em>the<strong> minimum</strong> number of coins <strong>of any value</strong> that need to be added to the array so that every integer in the range</em> <code>[1, target]</code><em> is <strong>obtainable</strong></em>.</p> <p>A <strong>subsequence</strong> of an array is a new <strong>non-empty</strong> array that is formed from the original array by deleting some (<strong>possibly none</strong>) of the elements without disturbing the relative positions of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> coins = [1,4,10], target = 19 <strong>Output:</strong> 2 <strong>Explanation:</strong> We need to add coins 2 and 8. The resulting array will be [1,2,4,8,10]. It can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 2 is the minimum number of coins that need to be added to the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> coins = [1,4,10,5,7,19], target = 19 <strong>Output:</strong> 1 <strong>Explanation:</strong> We only need to add the coin 2. The resulting array will be [1,2,4,5,7,10,19]. It can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 1 is the minimum number of coins that need to be added to the array. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> coins = [1,1,1], target = 20 <strong>Output:</strong> 3 <strong>Explanation:</strong> We need to add coins 4, 8, and 16. The resulting array will be [1,1,1,4,8,16]. It can be shown that all integers from 1 to 20 are obtainable from the resulting array, and that 3 is the minimum number of coins that need to be added to the array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coins.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coins[i] &lt;= target</code></li> </ul>
Greedy; Array; Sorting
Java
class Solution { public int minimumAddedCoins(int[] coins, int target) { Arrays.sort(coins); int ans = 0; for (int i = 0, s = 1; s <= target;) { if (i < coins.length && coins[i] <= s) { s += coins[i++]; } else { s <<= 1; ++ans; } } return ans; } }
2,952
Minimum Number of Coins to be Added
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>coins</code>, representing the values of the coins available, and an integer <code>target</code>.</p> <p>An integer <code>x</code> is <strong>obtainable</strong> if there exists a subsequence of <code>coins</code> that sums to <code>x</code>.</p> <p>Return <em>the<strong> minimum</strong> number of coins <strong>of any value</strong> that need to be added to the array so that every integer in the range</em> <code>[1, target]</code><em> is <strong>obtainable</strong></em>.</p> <p>A <strong>subsequence</strong> of an array is a new <strong>non-empty</strong> array that is formed from the original array by deleting some (<strong>possibly none</strong>) of the elements without disturbing the relative positions of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> coins = [1,4,10], target = 19 <strong>Output:</strong> 2 <strong>Explanation:</strong> We need to add coins 2 and 8. The resulting array will be [1,2,4,8,10]. It can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 2 is the minimum number of coins that need to be added to the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> coins = [1,4,10,5,7,19], target = 19 <strong>Output:</strong> 1 <strong>Explanation:</strong> We only need to add the coin 2. The resulting array will be [1,2,4,5,7,10,19]. It can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 1 is the minimum number of coins that need to be added to the array. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> coins = [1,1,1], target = 20 <strong>Output:</strong> 3 <strong>Explanation:</strong> We need to add coins 4, 8, and 16. The resulting array will be [1,1,1,4,8,16]. It can be shown that all integers from 1 to 20 are obtainable from the resulting array, and that 3 is the minimum number of coins that need to be added to the array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coins.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coins[i] &lt;= target</code></li> </ul>
Greedy; Array; Sorting
Python
class Solution: def minimumAddedCoins(self, coins: List[int], target: int) -> int: coins.sort() s = 1 ans = i = 0 while s <= target: if i < len(coins) and coins[i] <= s: s += coins[i] i += 1 else: s <<= 1 ans += 1 return ans
2,952
Minimum Number of Coins to be Added
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>coins</code>, representing the values of the coins available, and an integer <code>target</code>.</p> <p>An integer <code>x</code> is <strong>obtainable</strong> if there exists a subsequence of <code>coins</code> that sums to <code>x</code>.</p> <p>Return <em>the<strong> minimum</strong> number of coins <strong>of any value</strong> that need to be added to the array so that every integer in the range</em> <code>[1, target]</code><em> is <strong>obtainable</strong></em>.</p> <p>A <strong>subsequence</strong> of an array is a new <strong>non-empty</strong> array that is formed from the original array by deleting some (<strong>possibly none</strong>) of the elements without disturbing the relative positions of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> coins = [1,4,10], target = 19 <strong>Output:</strong> 2 <strong>Explanation:</strong> We need to add coins 2 and 8. The resulting array will be [1,2,4,8,10]. It can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 2 is the minimum number of coins that need to be added to the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> coins = [1,4,10,5,7,19], target = 19 <strong>Output:</strong> 1 <strong>Explanation:</strong> We only need to add the coin 2. The resulting array will be [1,2,4,5,7,10,19]. It can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 1 is the minimum number of coins that need to be added to the array. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> coins = [1,1,1], target = 20 <strong>Output:</strong> 3 <strong>Explanation:</strong> We need to add coins 4, 8, and 16. The resulting array will be [1,1,1,4,8,16]. It can be shown that all integers from 1 to 20 are obtainable from the resulting array, and that 3 is the minimum number of coins that need to be added to the array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= target &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coins.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= coins[i] &lt;= target</code></li> </ul>
Greedy; Array; Sorting
TypeScript
function minimumAddedCoins(coins: number[], target: number): number { coins.sort((a, b) => a - b); let ans = 0; for (let i = 0, s = 1; s <= target; ) { if (i < coins.length && coins[i] <= s) { s += coins[i++]; } else { s <<= 1; ++ans; } } return ans; }
2,953
Count Complete Substrings
Hard
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p> <p>A substring <code>s</code> of <code>word</code> is <strong>complete</strong> if:</p> <ul> <li>Each character in <code>s</code> occurs <strong>exactly</strong> <code>k</code> times.</li> <li>The difference between two adjacent characters is <strong>at most</strong> <code>2</code>. That is, for any two adjacent characters <code>c1</code> and <code>c2</code> in <code>s</code>, the absolute difference in their positions in the alphabet is <strong>at most</strong> <code>2</code>.</li> </ul> <p>Return <em>the number of <strong>complete </strong>substrings of</em> <code>word</code>.</p> <p>A <strong>substring</strong> is a <strong>non-empty</strong> contiguous sequence of characters in a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;igigee&quot;, k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The complete substrings where each character appears exactly twice and the difference between adjacent characters is at most 2 are: <u><strong>igig</strong></u>ee, igig<u><strong>ee</strong></u>, <u><strong>igigee</strong></u>. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaabbbccc&quot;, k = 3 <strong>Output:</strong> 6 <strong>Explanation:</strong> The complete substrings where each character appears exactly three times and the difference between adjacent characters is at most 2 are: <strong><u>aaa</u></strong>bbbccc, aaa<u><strong>bbb</strong></u>ccc, aaabbb<u><strong>ccc</strong></u>, <strong><u>aaabbb</u></strong>ccc, aaa<u><strong>bbbccc</strong></u>, <u><strong>aaabbbccc</strong></u>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= k &lt;= word.length</code></li> </ul>
Hash Table; String; Sliding Window
C++
class Solution { public: int countCompleteSubstrings(string word, int k) { int n = word.length(); int ans = 0; auto f = [&](string s) { int m = s.length(); int ans = 0; for (int i = 1; i <= 26 && i * k <= m; ++i) { int l = i * k; int cnt[26]{}; for (int j = 0; j < l; ++j) { ++cnt[s[j] - 'a']; } unordered_map<int, int> freq; for (int x : cnt) { if (x > 0) { freq[x]++; } } if (freq[k] == i) { ++ans; } for (int j = l; j < m; ++j) { int a = s[j] - 'a'; int b = s[j - l] - 'a'; freq[cnt[a]]--; cnt[a]++; freq[cnt[a]]++; freq[cnt[b]]--; cnt[b]--; freq[cnt[b]]++; if (freq[k] == i) { ++ans; } } } return ans; }; for (int i = 0; i < n;) { int j = i + 1; while (j < n && abs(word[j] - word[j - 1]) <= 2) { ++j; } ans += f(word.substr(i, j - i)); i = j; } return ans; } };
2,953
Count Complete Substrings
Hard
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p> <p>A substring <code>s</code> of <code>word</code> is <strong>complete</strong> if:</p> <ul> <li>Each character in <code>s</code> occurs <strong>exactly</strong> <code>k</code> times.</li> <li>The difference between two adjacent characters is <strong>at most</strong> <code>2</code>. That is, for any two adjacent characters <code>c1</code> and <code>c2</code> in <code>s</code>, the absolute difference in their positions in the alphabet is <strong>at most</strong> <code>2</code>.</li> </ul> <p>Return <em>the number of <strong>complete </strong>substrings of</em> <code>word</code>.</p> <p>A <strong>substring</strong> is a <strong>non-empty</strong> contiguous sequence of characters in a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;igigee&quot;, k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The complete substrings where each character appears exactly twice and the difference between adjacent characters is at most 2 are: <u><strong>igig</strong></u>ee, igig<u><strong>ee</strong></u>, <u><strong>igigee</strong></u>. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaabbbccc&quot;, k = 3 <strong>Output:</strong> 6 <strong>Explanation:</strong> The complete substrings where each character appears exactly three times and the difference between adjacent characters is at most 2 are: <strong><u>aaa</u></strong>bbbccc, aaa<u><strong>bbb</strong></u>ccc, aaabbb<u><strong>ccc</strong></u>, <strong><u>aaabbb</u></strong>ccc, aaa<u><strong>bbbccc</strong></u>, <u><strong>aaabbbccc</strong></u>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= k &lt;= word.length</code></li> </ul>
Hash Table; String; Sliding Window
Go
func countCompleteSubstrings(word string, k int) (ans int) { n := len(word) f := func(s string) (ans int) { m := len(s) for i := 1; i <= 26 && i*k <= m; i++ { l := i * k cnt := [26]int{} for j := 0; j < l; j++ { cnt[int(s[j]-'a')]++ } freq := map[int]int{} for _, x := range cnt { if x > 0 { freq[x]++ } } if freq[k] == i { ans++ } for j := l; j < m; j++ { a := int(s[j] - 'a') b := int(s[j-l] - 'a') freq[cnt[a]]-- cnt[a]++ freq[cnt[a]]++ freq[cnt[b]]-- cnt[b]-- freq[cnt[b]]++ if freq[k] == i { ans++ } } } return } for i := 0; i < n; { j := i + 1 for j < n && abs(int(word[j])-int(word[j-1])) <= 2 { j++ } ans += f(word[i:j]) i = j } return } func abs(x int) int { if x < 0 { return -x } return x }
2,953
Count Complete Substrings
Hard
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p> <p>A substring <code>s</code> of <code>word</code> is <strong>complete</strong> if:</p> <ul> <li>Each character in <code>s</code> occurs <strong>exactly</strong> <code>k</code> times.</li> <li>The difference between two adjacent characters is <strong>at most</strong> <code>2</code>. That is, for any two adjacent characters <code>c1</code> and <code>c2</code> in <code>s</code>, the absolute difference in their positions in the alphabet is <strong>at most</strong> <code>2</code>.</li> </ul> <p>Return <em>the number of <strong>complete </strong>substrings of</em> <code>word</code>.</p> <p>A <strong>substring</strong> is a <strong>non-empty</strong> contiguous sequence of characters in a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;igigee&quot;, k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The complete substrings where each character appears exactly twice and the difference between adjacent characters is at most 2 are: <u><strong>igig</strong></u>ee, igig<u><strong>ee</strong></u>, <u><strong>igigee</strong></u>. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaabbbccc&quot;, k = 3 <strong>Output:</strong> 6 <strong>Explanation:</strong> The complete substrings where each character appears exactly three times and the difference between adjacent characters is at most 2 are: <strong><u>aaa</u></strong>bbbccc, aaa<u><strong>bbb</strong></u>ccc, aaabbb<u><strong>ccc</strong></u>, <strong><u>aaabbb</u></strong>ccc, aaa<u><strong>bbbccc</strong></u>, <u><strong>aaabbbccc</strong></u>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= k &lt;= word.length</code></li> </ul>
Hash Table; String; Sliding Window
Java
class Solution { public int countCompleteSubstrings(String word, int k) { int n = word.length(); int ans = 0; for (int i = 0; i < n;) { int j = i + 1; while (j < n && Math.abs(word.charAt(j) - word.charAt(j - 1)) <= 2) { ++j; } ans += f(word.substring(i, j), k); i = j; } return ans; } private int f(String s, int k) { int m = s.length(); int ans = 0; for (int i = 1; i <= 26 && i * k <= m; ++i) { int l = i * k; int[] cnt = new int[26]; for (int j = 0; j < l; ++j) { ++cnt[s.charAt(j) - 'a']; } Map<Integer, Integer> freq = new HashMap<>(); for (int x : cnt) { if (x > 0) { freq.merge(x, 1, Integer::sum); } } if (freq.getOrDefault(k, 0) == i) { ++ans; } for (int j = l; j < m; ++j) { int a = s.charAt(j) - 'a'; int b = s.charAt(j - l) - 'a'; freq.merge(cnt[a], -1, Integer::sum); ++cnt[a]; freq.merge(cnt[a], 1, Integer::sum); freq.merge(cnt[b], -1, Integer::sum); --cnt[b]; freq.merge(cnt[b], 1, Integer::sum); if (freq.getOrDefault(k, 0) == i) { ++ans; } } } return ans; } }
2,953
Count Complete Substrings
Hard
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p> <p>A substring <code>s</code> of <code>word</code> is <strong>complete</strong> if:</p> <ul> <li>Each character in <code>s</code> occurs <strong>exactly</strong> <code>k</code> times.</li> <li>The difference between two adjacent characters is <strong>at most</strong> <code>2</code>. That is, for any two adjacent characters <code>c1</code> and <code>c2</code> in <code>s</code>, the absolute difference in their positions in the alphabet is <strong>at most</strong> <code>2</code>.</li> </ul> <p>Return <em>the number of <strong>complete </strong>substrings of</em> <code>word</code>.</p> <p>A <strong>substring</strong> is a <strong>non-empty</strong> contiguous sequence of characters in a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;igigee&quot;, k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The complete substrings where each character appears exactly twice and the difference between adjacent characters is at most 2 are: <u><strong>igig</strong></u>ee, igig<u><strong>ee</strong></u>, <u><strong>igigee</strong></u>. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaabbbccc&quot;, k = 3 <strong>Output:</strong> 6 <strong>Explanation:</strong> The complete substrings where each character appears exactly three times and the difference between adjacent characters is at most 2 are: <strong><u>aaa</u></strong>bbbccc, aaa<u><strong>bbb</strong></u>ccc, aaabbb<u><strong>ccc</strong></u>, <strong><u>aaabbb</u></strong>ccc, aaa<u><strong>bbbccc</strong></u>, <u><strong>aaabbbccc</strong></u>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= k &lt;= word.length</code></li> </ul>
Hash Table; String; Sliding Window
Python
class Solution: def countCompleteSubstrings(self, word: str, k: int) -> int: def f(s: str) -> int: m = len(s) ans = 0 for i in range(1, 27): l = i * k if l > m: break cnt = Counter(s[:l]) freq = Counter(cnt.values()) ans += freq[k] == i for j in range(l, m): freq[cnt[s[j]]] -= 1 cnt[s[j]] += 1 freq[cnt[s[j]]] += 1 freq[cnt[s[j - l]]] -= 1 cnt[s[j - l]] -= 1 freq[cnt[s[j - l]]] += 1 ans += freq[k] == i return ans n = len(word) ans = i = 0 while i < n: j = i + 1 while j < n and abs(ord(word[j]) - ord(word[j - 1])) <= 2: j += 1 ans += f(word[i:j]) i = j return ans
2,953
Count Complete Substrings
Hard
<p>You are given a string <code>word</code> and an integer <code>k</code>.</p> <p>A substring <code>s</code> of <code>word</code> is <strong>complete</strong> if:</p> <ul> <li>Each character in <code>s</code> occurs <strong>exactly</strong> <code>k</code> times.</li> <li>The difference between two adjacent characters is <strong>at most</strong> <code>2</code>. That is, for any two adjacent characters <code>c1</code> and <code>c2</code> in <code>s</code>, the absolute difference in their positions in the alphabet is <strong>at most</strong> <code>2</code>.</li> </ul> <p>Return <em>the number of <strong>complete </strong>substrings of</em> <code>word</code>.</p> <p>A <strong>substring</strong> is a <strong>non-empty</strong> contiguous sequence of characters in a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;igigee&quot;, k = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> The complete substrings where each character appears exactly twice and the difference between adjacent characters is at most 2 are: <u><strong>igig</strong></u>ee, igig<u><strong>ee</strong></u>, <u><strong>igigee</strong></u>. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaabbbccc&quot;, k = 3 <strong>Output:</strong> 6 <strong>Explanation:</strong> The complete substrings where each character appears exactly three times and the difference between adjacent characters is at most 2 are: <strong><u>aaa</u></strong>bbbccc, aaa<u><strong>bbb</strong></u>ccc, aaabbb<u><strong>ccc</strong></u>, <strong><u>aaabbb</u></strong>ccc, aaa<u><strong>bbbccc</strong></u>, <u><strong>aaabbbccc</strong></u>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 10<sup>5</sup></code></li> <li><code>word</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= k &lt;= word.length</code></li> </ul>
Hash Table; String; Sliding Window
TypeScript
function countCompleteSubstrings(word: string, k: number): number { const f = (s: string): number => { const m = s.length; let ans = 0; for (let i = 1; i <= 26 && i * k <= m; i++) { const l = i * k; const cnt: number[] = new Array(26).fill(0); for (let j = 0; j < l; j++) { cnt[s.charCodeAt(j) - 'a'.charCodeAt(0)]++; } const freq: { [key: number]: number } = {}; for (const x of cnt) { if (x > 0) { freq[x] = (freq[x] || 0) + 1; } } if (freq[k] === i) { ans++; } for (let j = l; j < m; j++) { const a = s.charCodeAt(j) - 'a'.charCodeAt(0); const b = s.charCodeAt(j - l) - 'a'.charCodeAt(0); freq[cnt[a]]--; cnt[a]++; freq[cnt[a]] = (freq[cnt[a]] || 0) + 1; freq[cnt[b]]--; cnt[b]--; freq[cnt[b]] = (freq[cnt[b]] || 0) + 1; if (freq[k] === i) { ans++; } } } return ans; }; let n = word.length; let ans = 0; for (let i = 0; i < n; ) { let j = i + 1; while (j < n && Math.abs(word.charCodeAt(j) - word.charCodeAt(j - 1)) <= 2) { j++; } ans += f(word.substring(i, j)); i = j; } return ans; }
2,954
Count the Number of Infection Sequences
Hard
<p>You are given an integer <code>n</code> and an array <code>sick</code> sorted in increasing order, representing positions of infected people in a line of <code>n</code> people.</p> <p>At each step, <strong>one </strong>uninfected person <strong>adjacent</strong> to an infected person gets infected. This process continues until everyone is infected.</p> <p>An <strong>infection sequence</strong> is the order in which uninfected people become infected, excluding those initially infected.</p> <p>Return the number of different infection sequences possible, modulo <code>10<sup>9</sup>+7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, sick = [0,4]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There is a total of 6 different sequences overall.</p> <ul> <li>Valid infection sequences are <code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[3,2,1]</code> and <code>[3,1,2]</code>.</li> <li><code>[2,3,1]</code> and <code>[2,1,3]</code> are not valid infection sequences because the person at index 2 cannot be infected at the first step.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, sick = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>There is a total of 6 different sequences overall.</p> <ul> <li>Valid infection sequences are <code>[0,2,3]</code>, <code>[2,0,3]</code> and <code>[2,3,0]</code>.</li> <li><code>[3,2,0]</code>, <code>[3,0,2]</code>, and <code>[0,3,2]</code> are not valid infection sequences because the infection starts at the person at index 1, then the order of infection is 2, then 3, and hence 3 cannot be infected earlier than 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= sick.length &lt;= n - 1</code></li> <li><code>0 &lt;= sick[i] &lt;= n - 1</code></li> <li><code>sick</code> is sorted in increasing order.</li> </ul>
Array; Math; Combinatorics
C++
const int MX = 1e5; const int MOD = 1e9 + 7; int fac[MX + 1]; auto init = [] { fac[0] = 1; for (int i = 1; i <= MX; ++i) { fac[i] = 1LL * fac[i - 1] * i % MOD; } return 0; }(); int qpow(long long a, long long n) { long long ans = 1; for (; n > 0; n >>= 1) { if (n & 1) { ans = (ans * a) % MOD; } a = (a * a) % MOD; } return ans; } class Solution { public: int numberOfSequence(int n, vector<int>& sick) { int m = sick.size(); vector<int> nums(m + 1); nums[0] = sick[0]; nums[m] = n - sick[m - 1] - 1; for (int i = 1; i < m; i++) { nums[i] = sick[i] - sick[i - 1] - 1; } int s = accumulate(nums.begin(), nums.end(), 0); long long ans = fac[s]; for (int x : nums) { if (x > 0) { ans = ans * qpow(fac[x], MOD - 2) % MOD; } } for (int i = 1; i < nums.size() - 1; ++i) { if (nums[i] > 1) { ans = ans * qpow(2, nums[i] - 1) % MOD; } } return ans; } };
2,954
Count the Number of Infection Sequences
Hard
<p>You are given an integer <code>n</code> and an array <code>sick</code> sorted in increasing order, representing positions of infected people in a line of <code>n</code> people.</p> <p>At each step, <strong>one </strong>uninfected person <strong>adjacent</strong> to an infected person gets infected. This process continues until everyone is infected.</p> <p>An <strong>infection sequence</strong> is the order in which uninfected people become infected, excluding those initially infected.</p> <p>Return the number of different infection sequences possible, modulo <code>10<sup>9</sup>+7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, sick = [0,4]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There is a total of 6 different sequences overall.</p> <ul> <li>Valid infection sequences are <code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[3,2,1]</code> and <code>[3,1,2]</code>.</li> <li><code>[2,3,1]</code> and <code>[2,1,3]</code> are not valid infection sequences because the person at index 2 cannot be infected at the first step.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, sick = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>There is a total of 6 different sequences overall.</p> <ul> <li>Valid infection sequences are <code>[0,2,3]</code>, <code>[2,0,3]</code> and <code>[2,3,0]</code>.</li> <li><code>[3,2,0]</code>, <code>[3,0,2]</code>, and <code>[0,3,2]</code> are not valid infection sequences because the infection starts at the person at index 1, then the order of infection is 2, then 3, and hence 3 cannot be infected earlier than 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= sick.length &lt;= n - 1</code></li> <li><code>0 &lt;= sick[i] &lt;= n - 1</code></li> <li><code>sick</code> is sorted in increasing order.</li> </ul>
Array; Math; Combinatorics
Go
const MX = 1e5 const MOD = 1e9 + 7 var fac [MX + 1]int func init() { fac[0] = 1 for i := 1; i <= MX; i++ { fac[i] = fac[i-1] * i % MOD } } func qpow(a, n int) int { ans := 1 for n > 0 { if n&1 == 1 { ans = (ans * a) % MOD } a = (a * a) % MOD n >>= 1 } return ans } func numberOfSequence(n int, sick []int) int { m := len(sick) nums := make([]int, m+1) nums[0] = sick[0] nums[m] = n - sick[m-1] - 1 for i := 1; i < m; i++ { nums[i] = sick[i] - sick[i-1] - 1 } s := 0 for _, x := range nums { s += x } ans := fac[s] for _, x := range nums { if x > 0 { ans = ans * qpow(fac[x], MOD-2) % MOD } } for i := 1; i < len(nums)-1; i++ { if nums[i] > 1 { ans = ans * qpow(2, nums[i]-1) % MOD } } return ans }
2,954
Count the Number of Infection Sequences
Hard
<p>You are given an integer <code>n</code> and an array <code>sick</code> sorted in increasing order, representing positions of infected people in a line of <code>n</code> people.</p> <p>At each step, <strong>one </strong>uninfected person <strong>adjacent</strong> to an infected person gets infected. This process continues until everyone is infected.</p> <p>An <strong>infection sequence</strong> is the order in which uninfected people become infected, excluding those initially infected.</p> <p>Return the number of different infection sequences possible, modulo <code>10<sup>9</sup>+7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, sick = [0,4]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There is a total of 6 different sequences overall.</p> <ul> <li>Valid infection sequences are <code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[3,2,1]</code> and <code>[3,1,2]</code>.</li> <li><code>[2,3,1]</code> and <code>[2,1,3]</code> are not valid infection sequences because the person at index 2 cannot be infected at the first step.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, sick = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>There is a total of 6 different sequences overall.</p> <ul> <li>Valid infection sequences are <code>[0,2,3]</code>, <code>[2,0,3]</code> and <code>[2,3,0]</code>.</li> <li><code>[3,2,0]</code>, <code>[3,0,2]</code>, and <code>[0,3,2]</code> are not valid infection sequences because the infection starts at the person at index 1, then the order of infection is 2, then 3, and hence 3 cannot be infected earlier than 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= sick.length &lt;= n - 1</code></li> <li><code>0 &lt;= sick[i] &lt;= n - 1</code></li> <li><code>sick</code> is sorted in increasing order.</li> </ul>
Array; Math; Combinatorics
Java
class Solution { private static final int MOD = (int) (1e9 + 7); private static final int MX = 100000; private static final int[] FAC = new int[MX + 1]; static { FAC[0] = 1; for (int i = 1; i <= MX; i++) { FAC[i] = (int) ((long) FAC[i - 1] * i % MOD); } } public int numberOfSequence(int n, int[] sick) { int m = sick.length; int[] nums = new int[m + 1]; nums[0] = sick[0]; nums[m] = n - sick[m - 1] - 1; for (int i = 1; i < m; i++) { nums[i] = sick[i] - sick[i - 1] - 1; } int s = 0; for (int x : nums) { s += x; } int ans = FAC[s]; for (int x : nums) { if (x > 0) { ans = (int) ((long) ans * qpow(FAC[x], MOD - 2) % MOD); } } for (int i = 1; i < nums.length - 1; ++i) { if (nums[i] > 1) { ans = (int) ((long) ans * qpow(2, nums[i] - 1) % MOD); } } return ans; } private int qpow(long a, long n) { long ans = 1; for (; n > 0; n >>= 1) { if ((n & 1) == 1) { ans = ans * a % MOD; } a = a * a % MOD; } return (int) ans; } }
2,954
Count the Number of Infection Sequences
Hard
<p>You are given an integer <code>n</code> and an array <code>sick</code> sorted in increasing order, representing positions of infected people in a line of <code>n</code> people.</p> <p>At each step, <strong>one </strong>uninfected person <strong>adjacent</strong> to an infected person gets infected. This process continues until everyone is infected.</p> <p>An <strong>infection sequence</strong> is the order in which uninfected people become infected, excluding those initially infected.</p> <p>Return the number of different infection sequences possible, modulo <code>10<sup>9</sup>+7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, sick = [0,4]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There is a total of 6 different sequences overall.</p> <ul> <li>Valid infection sequences are <code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[3,2,1]</code> and <code>[3,1,2]</code>.</li> <li><code>[2,3,1]</code> and <code>[2,1,3]</code> are not valid infection sequences because the person at index 2 cannot be infected at the first step.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, sick = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>There is a total of 6 different sequences overall.</p> <ul> <li>Valid infection sequences are <code>[0,2,3]</code>, <code>[2,0,3]</code> and <code>[2,3,0]</code>.</li> <li><code>[3,2,0]</code>, <code>[3,0,2]</code>, and <code>[0,3,2]</code> are not valid infection sequences because the infection starts at the person at index 1, then the order of infection is 2, then 3, and hence 3 cannot be infected earlier than 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= sick.length &lt;= n - 1</code></li> <li><code>0 &lt;= sick[i] &lt;= n - 1</code></li> <li><code>sick</code> is sorted in increasing order.</li> </ul>
Array; Math; Combinatorics
Python
mod = 10**9 + 7 mx = 10**5 fac = [1] * (mx + 1) for i in range(2, mx + 1): fac[i] = fac[i - 1] * i % mod class Solution: def numberOfSequence(self, n: int, sick: List[int]) -> int: nums = [b - a - 1 for a, b in pairwise([-1] + sick + [n])] ans = 1 s = sum(nums) ans = fac[s] for x in nums: if x: ans = ans * pow(fac[x], mod - 2, mod) % mod for x in nums[1:-1]: if x > 1: ans = ans * pow(2, x - 1, mod) % mod return ans
2,954
Count the Number of Infection Sequences
Hard
<p>You are given an integer <code>n</code> and an array <code>sick</code> sorted in increasing order, representing positions of infected people in a line of <code>n</code> people.</p> <p>At each step, <strong>one </strong>uninfected person <strong>adjacent</strong> to an infected person gets infected. This process continues until everyone is infected.</p> <p>An <strong>infection sequence</strong> is the order in which uninfected people become infected, excluding those initially infected.</p> <p>Return the number of different infection sequences possible, modulo <code>10<sup>9</sup>+7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, sick = [0,4]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There is a total of 6 different sequences overall.</p> <ul> <li>Valid infection sequences are <code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[3,2,1]</code> and <code>[3,1,2]</code>.</li> <li><code>[2,3,1]</code> and <code>[2,1,3]</code> are not valid infection sequences because the person at index 2 cannot be infected at the first step.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, sick = [1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>There is a total of 6 different sequences overall.</p> <ul> <li>Valid infection sequences are <code>[0,2,3]</code>, <code>[2,0,3]</code> and <code>[2,3,0]</code>.</li> <li><code>[3,2,0]</code>, <code>[3,0,2]</code>, and <code>[0,3,2]</code> are not valid infection sequences because the infection starts at the person at index 1, then the order of infection is 2, then 3, and hence 3 cannot be infected earlier than 2.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= sick.length &lt;= n - 1</code></li> <li><code>0 &lt;= sick[i] &lt;= n - 1</code></li> <li><code>sick</code> is sorted in increasing order.</li> </ul>
Array; Math; Combinatorics
TypeScript
const MX = 1e5; const MOD: bigint = BigInt(1e9 + 7); const fac: bigint[] = Array(MX + 1); const init = (() => { fac[0] = 1n; for (let i = 1; i <= MX; ++i) { fac[i] = (fac[i - 1] * BigInt(i)) % MOD; } return 0; })(); function qpow(a: bigint, n: number): bigint { let ans = 1n; for (; n > 0; n >>= 1) { if (n & 1) { ans = (ans * a) % MOD; } a = (a * a) % MOD; } return ans; } function numberOfSequence(n: number, sick: number[]): number { const m = sick.length; const nums: number[] = Array(m + 1); nums[0] = sick[0]; nums[m] = n - sick[m - 1] - 1; for (let i = 1; i < m; i++) { nums[i] = sick[i] - sick[i - 1] - 1; } const s = nums.reduce((acc, x) => acc + x, 0); let ans = fac[s]; for (let x of nums) { if (x > 0) { ans = (ans * qpow(fac[x], Number(MOD) - 2)) % MOD; } } for (let i = 1; i < nums.length - 1; ++i) { if (nums[i] > 1) { ans = (ans * qpow(2n, nums[i] - 1)) % MOD; } } return Number(ans); }
2,955
Number of Same-End Substrings
Medium
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, and a 2D array of integers <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> indicates a substring of <code>s</code> starting from the index <code>l<sub>i</sub></code> and ending at the index <code>r<sub>i</sub></code> (both <strong>inclusive</strong>), i.e. <code>s[l<sub>i</sub>..r<sub>i</sub>]</code>.</p> <p>Return <em>an array </em><code>ans</code><em> where</em> <code>ans[i]</code> <em>is the number of <strong>same-end</strong> substrings of</em> <code>queries[i]</code>.</p> <p>A <strong>0-indexed</strong> string <code>t</code> of length <code>n</code> is called <strong>same-end</strong> if it has the same character at both of its ends, i.e., <code>t[0] == t[n - 1]</code>.</p> <p>A <b>substring</b> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcaab&quot;, queries = [[0,0],[1,4],[2,5],[0,5]] <strong>Output:</strong> [1,5,5,10] <strong>Explanation:</strong> Here is the same-end substrings of each query: 1<sup>st</sup> query: s[0..0] is &quot;a&quot; which has 1 same-end substring: &quot;<strong><u>a</u></strong>&quot;. 2<sup>nd</sup> query: s[1..4] is &quot;bcaa&quot; which has 5 same-end substrings: &quot;<strong><u>b</u></strong>caa&quot;, &quot;b<strong><u>c</u></strong>aa&quot;, &quot;bc<strong><u>a</u></strong>a&quot;, &quot;bca<strong><u>a</u></strong>&quot;, &quot;bc<strong><u>aa</u></strong>&quot;. 3<sup>rd</sup> query: s[2..5] is &quot;caab&quot; which has 5 same-end substrings: &quot;<strong><u>c</u></strong>aab&quot;, &quot;c<strong><u>a</u></strong>ab&quot;, &quot;ca<strong><u>a</u></strong>b&quot;, &quot;caa<strong><u>b</u></strong>&quot;, &quot;c<strong><u>aa</u></strong>b&quot;. 4<sup>th</sup> query: s[0..5] is &quot;abcaab&quot; which has 10 same-end substrings: &quot;<strong><u>a</u></strong>bcaab&quot;, &quot;a<strong><u>b</u></strong>caab&quot;, &quot;ab<strong><u>c</u></strong>aab&quot;, &quot;abc<strong><u>a</u></strong>ab&quot;, &quot;abca<strong><u>a</u></strong>b&quot;, &quot;abcaa<strong><u>b</u></strong>&quot;, &quot;abc<strong><u>aa</u></strong>b&quot;, &quot;<strong><u>abca</u></strong>ab&quot;, &quot;<strong><u>abcaa</u></strong>b&quot;, &quot;a<strong><u>bcaab</u></strong>&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, queries = [[0,3]] <strong>Output:</strong> [4] <strong>Explanation:</strong> The only query is s[0..3] which is &quot;abcd&quot;. It has 4 same-end substrings: &quot;<strong><u>a</u></strong>bcd&quot;, &quot;a<strong><u>b</u></strong>cd&quot;, &quot;ab<strong><u>c</u></strong>d&quot;, &quot;abc<strong><u>d</u></strong>&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= queries.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; s.length</code></li> </ul>
Array; Hash Table; String; Counting; Prefix Sum
C++
class Solution { public: vector<int> sameEndSubstringCount(string s, vector<vector<int>>& queries) { int n = s.size(); int cnt[26][n + 1]; memset(cnt, 0, sizeof(cnt)); for (int j = 1; j <= n; ++j) { for (int i = 0; i < 26; ++i) { cnt[i][j] = cnt[i][j - 1]; } cnt[s[j - 1] - 'a'][j]++; } vector<int> ans; for (auto& q : queries) { int l = q[0], r = q[1]; ans.push_back(r - l + 1); for (int i = 0; i < 26; ++i) { int x = cnt[i][r + 1] - cnt[i][l]; ans.back() += x * (x - 1) / 2; } } return ans; } };
2,955
Number of Same-End Substrings
Medium
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, and a 2D array of integers <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> indicates a substring of <code>s</code> starting from the index <code>l<sub>i</sub></code> and ending at the index <code>r<sub>i</sub></code> (both <strong>inclusive</strong>), i.e. <code>s[l<sub>i</sub>..r<sub>i</sub>]</code>.</p> <p>Return <em>an array </em><code>ans</code><em> where</em> <code>ans[i]</code> <em>is the number of <strong>same-end</strong> substrings of</em> <code>queries[i]</code>.</p> <p>A <strong>0-indexed</strong> string <code>t</code> of length <code>n</code> is called <strong>same-end</strong> if it has the same character at both of its ends, i.e., <code>t[0] == t[n - 1]</code>.</p> <p>A <b>substring</b> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcaab&quot;, queries = [[0,0],[1,4],[2,5],[0,5]] <strong>Output:</strong> [1,5,5,10] <strong>Explanation:</strong> Here is the same-end substrings of each query: 1<sup>st</sup> query: s[0..0] is &quot;a&quot; which has 1 same-end substring: &quot;<strong><u>a</u></strong>&quot;. 2<sup>nd</sup> query: s[1..4] is &quot;bcaa&quot; which has 5 same-end substrings: &quot;<strong><u>b</u></strong>caa&quot;, &quot;b<strong><u>c</u></strong>aa&quot;, &quot;bc<strong><u>a</u></strong>a&quot;, &quot;bca<strong><u>a</u></strong>&quot;, &quot;bc<strong><u>aa</u></strong>&quot;. 3<sup>rd</sup> query: s[2..5] is &quot;caab&quot; which has 5 same-end substrings: &quot;<strong><u>c</u></strong>aab&quot;, &quot;c<strong><u>a</u></strong>ab&quot;, &quot;ca<strong><u>a</u></strong>b&quot;, &quot;caa<strong><u>b</u></strong>&quot;, &quot;c<strong><u>aa</u></strong>b&quot;. 4<sup>th</sup> query: s[0..5] is &quot;abcaab&quot; which has 10 same-end substrings: &quot;<strong><u>a</u></strong>bcaab&quot;, &quot;a<strong><u>b</u></strong>caab&quot;, &quot;ab<strong><u>c</u></strong>aab&quot;, &quot;abc<strong><u>a</u></strong>ab&quot;, &quot;abca<strong><u>a</u></strong>b&quot;, &quot;abcaa<strong><u>b</u></strong>&quot;, &quot;abc<strong><u>aa</u></strong>b&quot;, &quot;<strong><u>abca</u></strong>ab&quot;, &quot;<strong><u>abcaa</u></strong>b&quot;, &quot;a<strong><u>bcaab</u></strong>&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, queries = [[0,3]] <strong>Output:</strong> [4] <strong>Explanation:</strong> The only query is s[0..3] which is &quot;abcd&quot;. It has 4 same-end substrings: &quot;<strong><u>a</u></strong>bcd&quot;, &quot;a<strong><u>b</u></strong>cd&quot;, &quot;ab<strong><u>c</u></strong>d&quot;, &quot;abc<strong><u>d</u></strong>&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= queries.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; s.length</code></li> </ul>
Array; Hash Table; String; Counting; Prefix Sum
Go
func sameEndSubstringCount(s string, queries [][]int) []int { n := len(s) cnt := make([][]int, 26) for i := 0; i < 26; i++ { cnt[i] = make([]int, n+1) } for j := 1; j <= n; j++ { for i := 0; i < 26; i++ { cnt[i][j] = cnt[i][j-1] } cnt[s[j-1]-'a'][j]++ } var ans []int for _, q := range queries { l, r := q[0], q[1] ans = append(ans, r-l+1) for i := 0; i < 26; i++ { x := cnt[i][r+1] - cnt[i][l] ans[len(ans)-1] += x * (x - 1) / 2 } } return ans }
2,955
Number of Same-End Substrings
Medium
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, and a 2D array of integers <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> indicates a substring of <code>s</code> starting from the index <code>l<sub>i</sub></code> and ending at the index <code>r<sub>i</sub></code> (both <strong>inclusive</strong>), i.e. <code>s[l<sub>i</sub>..r<sub>i</sub>]</code>.</p> <p>Return <em>an array </em><code>ans</code><em> where</em> <code>ans[i]</code> <em>is the number of <strong>same-end</strong> substrings of</em> <code>queries[i]</code>.</p> <p>A <strong>0-indexed</strong> string <code>t</code> of length <code>n</code> is called <strong>same-end</strong> if it has the same character at both of its ends, i.e., <code>t[0] == t[n - 1]</code>.</p> <p>A <b>substring</b> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcaab&quot;, queries = [[0,0],[1,4],[2,5],[0,5]] <strong>Output:</strong> [1,5,5,10] <strong>Explanation:</strong> Here is the same-end substrings of each query: 1<sup>st</sup> query: s[0..0] is &quot;a&quot; which has 1 same-end substring: &quot;<strong><u>a</u></strong>&quot;. 2<sup>nd</sup> query: s[1..4] is &quot;bcaa&quot; which has 5 same-end substrings: &quot;<strong><u>b</u></strong>caa&quot;, &quot;b<strong><u>c</u></strong>aa&quot;, &quot;bc<strong><u>a</u></strong>a&quot;, &quot;bca<strong><u>a</u></strong>&quot;, &quot;bc<strong><u>aa</u></strong>&quot;. 3<sup>rd</sup> query: s[2..5] is &quot;caab&quot; which has 5 same-end substrings: &quot;<strong><u>c</u></strong>aab&quot;, &quot;c<strong><u>a</u></strong>ab&quot;, &quot;ca<strong><u>a</u></strong>b&quot;, &quot;caa<strong><u>b</u></strong>&quot;, &quot;c<strong><u>aa</u></strong>b&quot;. 4<sup>th</sup> query: s[0..5] is &quot;abcaab&quot; which has 10 same-end substrings: &quot;<strong><u>a</u></strong>bcaab&quot;, &quot;a<strong><u>b</u></strong>caab&quot;, &quot;ab<strong><u>c</u></strong>aab&quot;, &quot;abc<strong><u>a</u></strong>ab&quot;, &quot;abca<strong><u>a</u></strong>b&quot;, &quot;abcaa<strong><u>b</u></strong>&quot;, &quot;abc<strong><u>aa</u></strong>b&quot;, &quot;<strong><u>abca</u></strong>ab&quot;, &quot;<strong><u>abcaa</u></strong>b&quot;, &quot;a<strong><u>bcaab</u></strong>&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, queries = [[0,3]] <strong>Output:</strong> [4] <strong>Explanation:</strong> The only query is s[0..3] which is &quot;abcd&quot;. It has 4 same-end substrings: &quot;<strong><u>a</u></strong>bcd&quot;, &quot;a<strong><u>b</u></strong>cd&quot;, &quot;ab<strong><u>c</u></strong>d&quot;, &quot;abc<strong><u>d</u></strong>&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= queries.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; s.length</code></li> </ul>
Array; Hash Table; String; Counting; Prefix Sum
Java
class Solution { public int[] sameEndSubstringCount(String s, int[][] queries) { int n = s.length(); int[][] cnt = new int[26][n + 1]; for (int j = 1; j <= n; ++j) { for (int i = 0; i < 26; ++i) { cnt[i][j] = cnt[i][j - 1]; } cnt[s.charAt(j - 1) - 'a'][j]++; } int m = queries.length; int[] ans = new int[m]; for (int k = 0; k < m; ++k) { int l = queries[k][0], r = queries[k][1]; ans[k] = r - l + 1; for (int i = 0; i < 26; ++i) { int x = cnt[i][r + 1] - cnt[i][l]; ans[k] += x * (x - 1) / 2; } } return ans; } }
2,955
Number of Same-End Substrings
Medium
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, and a 2D array of integers <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> indicates a substring of <code>s</code> starting from the index <code>l<sub>i</sub></code> and ending at the index <code>r<sub>i</sub></code> (both <strong>inclusive</strong>), i.e. <code>s[l<sub>i</sub>..r<sub>i</sub>]</code>.</p> <p>Return <em>an array </em><code>ans</code><em> where</em> <code>ans[i]</code> <em>is the number of <strong>same-end</strong> substrings of</em> <code>queries[i]</code>.</p> <p>A <strong>0-indexed</strong> string <code>t</code> of length <code>n</code> is called <strong>same-end</strong> if it has the same character at both of its ends, i.e., <code>t[0] == t[n - 1]</code>.</p> <p>A <b>substring</b> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcaab&quot;, queries = [[0,0],[1,4],[2,5],[0,5]] <strong>Output:</strong> [1,5,5,10] <strong>Explanation:</strong> Here is the same-end substrings of each query: 1<sup>st</sup> query: s[0..0] is &quot;a&quot; which has 1 same-end substring: &quot;<strong><u>a</u></strong>&quot;. 2<sup>nd</sup> query: s[1..4] is &quot;bcaa&quot; which has 5 same-end substrings: &quot;<strong><u>b</u></strong>caa&quot;, &quot;b<strong><u>c</u></strong>aa&quot;, &quot;bc<strong><u>a</u></strong>a&quot;, &quot;bca<strong><u>a</u></strong>&quot;, &quot;bc<strong><u>aa</u></strong>&quot;. 3<sup>rd</sup> query: s[2..5] is &quot;caab&quot; which has 5 same-end substrings: &quot;<strong><u>c</u></strong>aab&quot;, &quot;c<strong><u>a</u></strong>ab&quot;, &quot;ca<strong><u>a</u></strong>b&quot;, &quot;caa<strong><u>b</u></strong>&quot;, &quot;c<strong><u>aa</u></strong>b&quot;. 4<sup>th</sup> query: s[0..5] is &quot;abcaab&quot; which has 10 same-end substrings: &quot;<strong><u>a</u></strong>bcaab&quot;, &quot;a<strong><u>b</u></strong>caab&quot;, &quot;ab<strong><u>c</u></strong>aab&quot;, &quot;abc<strong><u>a</u></strong>ab&quot;, &quot;abca<strong><u>a</u></strong>b&quot;, &quot;abcaa<strong><u>b</u></strong>&quot;, &quot;abc<strong><u>aa</u></strong>b&quot;, &quot;<strong><u>abca</u></strong>ab&quot;, &quot;<strong><u>abcaa</u></strong>b&quot;, &quot;a<strong><u>bcaab</u></strong>&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, queries = [[0,3]] <strong>Output:</strong> [4] <strong>Explanation:</strong> The only query is s[0..3] which is &quot;abcd&quot;. It has 4 same-end substrings: &quot;<strong><u>a</u></strong>bcd&quot;, &quot;a<strong><u>b</u></strong>cd&quot;, &quot;ab<strong><u>c</u></strong>d&quot;, &quot;abc<strong><u>d</u></strong>&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= queries.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; s.length</code></li> </ul>
Array; Hash Table; String; Counting; Prefix Sum
Python
class Solution: def sameEndSubstringCount(self, s: str, queries: List[List[int]]) -> List[int]: n = len(s) cs = set(s) cnt = {c: [0] * (n + 1) for c in cs} for i, a in enumerate(s, 1): for c in cs: cnt[c][i] = cnt[c][i - 1] cnt[a][i] += 1 ans = [] for l, r in queries: t = r - l + 1 for c in cs: x = cnt[c][r + 1] - cnt[c][l] t += x * (x - 1) // 2 ans.append(t) return ans
2,955
Number of Same-End Substrings
Medium
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, and a 2D array of integers <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> indicates a substring of <code>s</code> starting from the index <code>l<sub>i</sub></code> and ending at the index <code>r<sub>i</sub></code> (both <strong>inclusive</strong>), i.e. <code>s[l<sub>i</sub>..r<sub>i</sub>]</code>.</p> <p>Return <em>an array </em><code>ans</code><em> where</em> <code>ans[i]</code> <em>is the number of <strong>same-end</strong> substrings of</em> <code>queries[i]</code>.</p> <p>A <strong>0-indexed</strong> string <code>t</code> of length <code>n</code> is called <strong>same-end</strong> if it has the same character at both of its ends, i.e., <code>t[0] == t[n - 1]</code>.</p> <p>A <b>substring</b> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcaab&quot;, queries = [[0,0],[1,4],[2,5],[0,5]] <strong>Output:</strong> [1,5,5,10] <strong>Explanation:</strong> Here is the same-end substrings of each query: 1<sup>st</sup> query: s[0..0] is &quot;a&quot; which has 1 same-end substring: &quot;<strong><u>a</u></strong>&quot;. 2<sup>nd</sup> query: s[1..4] is &quot;bcaa&quot; which has 5 same-end substrings: &quot;<strong><u>b</u></strong>caa&quot;, &quot;b<strong><u>c</u></strong>aa&quot;, &quot;bc<strong><u>a</u></strong>a&quot;, &quot;bca<strong><u>a</u></strong>&quot;, &quot;bc<strong><u>aa</u></strong>&quot;. 3<sup>rd</sup> query: s[2..5] is &quot;caab&quot; which has 5 same-end substrings: &quot;<strong><u>c</u></strong>aab&quot;, &quot;c<strong><u>a</u></strong>ab&quot;, &quot;ca<strong><u>a</u></strong>b&quot;, &quot;caa<strong><u>b</u></strong>&quot;, &quot;c<strong><u>aa</u></strong>b&quot;. 4<sup>th</sup> query: s[0..5] is &quot;abcaab&quot; which has 10 same-end substrings: &quot;<strong><u>a</u></strong>bcaab&quot;, &quot;a<strong><u>b</u></strong>caab&quot;, &quot;ab<strong><u>c</u></strong>aab&quot;, &quot;abc<strong><u>a</u></strong>ab&quot;, &quot;abca<strong><u>a</u></strong>b&quot;, &quot;abcaa<strong><u>b</u></strong>&quot;, &quot;abc<strong><u>aa</u></strong>b&quot;, &quot;<strong><u>abca</u></strong>ab&quot;, &quot;<strong><u>abcaa</u></strong>b&quot;, &quot;a<strong><u>bcaab</u></strong>&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, queries = [[0,3]] <strong>Output:</strong> [4] <strong>Explanation:</strong> The only query is s[0..3] which is &quot;abcd&quot;. It has 4 same-end substrings: &quot;<strong><u>a</u></strong>bcd&quot;, &quot;a<strong><u>b</u></strong>cd&quot;, &quot;ab<strong><u>c</u></strong>d&quot;, &quot;abc<strong><u>d</u></strong>&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= queries.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; s.length</code></li> </ul>
Array; Hash Table; String; Counting; Prefix Sum
Rust
impl Solution { pub fn same_end_substring_count(s: String, queries: Vec<Vec<i32>>) -> Vec<i32> { let n = s.len(); let mut cnt: Vec<Vec<i32>> = vec![vec![0; n + 1]; 26]; for j in 1..=n { for i in 0..26 { cnt[i][j] = cnt[i][j - 1]; } cnt[(s.as_bytes()[j - 1] as usize) - (b'a' as usize)][j] += 1; } let mut ans: Vec<i32> = Vec::new(); for q in queries.iter() { let l = q[0] as usize; let r = q[1] as usize; let mut t = (r - l + 1) as i32; for i in 0..26 { let x = cnt[i][r + 1] - cnt[i][l]; t += (x * (x - 1)) / 2; } ans.push(t); } ans } }
2,955
Number of Same-End Substrings
Medium
<p>You are given a <strong>0-indexed</strong> string <code>s</code>, and a 2D array of integers <code>queries</code>, where <code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code> indicates a substring of <code>s</code> starting from the index <code>l<sub>i</sub></code> and ending at the index <code>r<sub>i</sub></code> (both <strong>inclusive</strong>), i.e. <code>s[l<sub>i</sub>..r<sub>i</sub>]</code>.</p> <p>Return <em>an array </em><code>ans</code><em> where</em> <code>ans[i]</code> <em>is the number of <strong>same-end</strong> substrings of</em> <code>queries[i]</code>.</p> <p>A <strong>0-indexed</strong> string <code>t</code> of length <code>n</code> is called <strong>same-end</strong> if it has the same character at both of its ends, i.e., <code>t[0] == t[n - 1]</code>.</p> <p>A <b>substring</b> is a contiguous non-empty sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcaab&quot;, queries = [[0,0],[1,4],[2,5],[0,5]] <strong>Output:</strong> [1,5,5,10] <strong>Explanation:</strong> Here is the same-end substrings of each query: 1<sup>st</sup> query: s[0..0] is &quot;a&quot; which has 1 same-end substring: &quot;<strong><u>a</u></strong>&quot;. 2<sup>nd</sup> query: s[1..4] is &quot;bcaa&quot; which has 5 same-end substrings: &quot;<strong><u>b</u></strong>caa&quot;, &quot;b<strong><u>c</u></strong>aa&quot;, &quot;bc<strong><u>a</u></strong>a&quot;, &quot;bca<strong><u>a</u></strong>&quot;, &quot;bc<strong><u>aa</u></strong>&quot;. 3<sup>rd</sup> query: s[2..5] is &quot;caab&quot; which has 5 same-end substrings: &quot;<strong><u>c</u></strong>aab&quot;, &quot;c<strong><u>a</u></strong>ab&quot;, &quot;ca<strong><u>a</u></strong>b&quot;, &quot;caa<strong><u>b</u></strong>&quot;, &quot;c<strong><u>aa</u></strong>b&quot;. 4<sup>th</sup> query: s[0..5] is &quot;abcaab&quot; which has 10 same-end substrings: &quot;<strong><u>a</u></strong>bcaab&quot;, &quot;a<strong><u>b</u></strong>caab&quot;, &quot;ab<strong><u>c</u></strong>aab&quot;, &quot;abc<strong><u>a</u></strong>ab&quot;, &quot;abca<strong><u>a</u></strong>b&quot;, &quot;abcaa<strong><u>b</u></strong>&quot;, &quot;abc<strong><u>aa</u></strong>b&quot;, &quot;<strong><u>abca</u></strong>ab&quot;, &quot;<strong><u>abcaa</u></strong>b&quot;, &quot;a<strong><u>bcaab</u></strong>&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, queries = [[0,3]] <strong>Output:</strong> [4] <strong>Explanation:</strong> The only query is s[0..3] which is &quot;abcd&quot;. It has 4 same-end substrings: &quot;<strong><u>a</u></strong>bcd&quot;, &quot;a<strong><u>b</u></strong>cd&quot;, &quot;ab<strong><u>c</u></strong>d&quot;, &quot;abc<strong><u>d</u></strong>&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> <li><code>1 &lt;= queries.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code></li> <li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt; s.length</code></li> </ul>
Array; Hash Table; String; Counting; Prefix Sum
TypeScript
function sameEndSubstringCount(s: string, queries: number[][]): number[] { const n: number = s.length; const cnt: number[][] = Array.from({ length: 26 }, () => Array(n + 1).fill(0)); for (let j = 1; j <= n; j++) { for (let i = 0; i < 26; i++) { cnt[i][j] = cnt[i][j - 1]; } cnt[s.charCodeAt(j - 1) - 'a'.charCodeAt(0)][j]++; } const ans: number[] = []; for (const [l, r] of queries) { ans.push(r - l + 1); for (let i = 0; i < 26; i++) { const x: number = cnt[i][r + 1] - cnt[i][l]; ans[ans.length - 1] += (x * (x - 1)) / 2; } } return ans; }
2,956
Find Common Elements Between Two Arrays
Easy
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of sizes <code>n</code> and <code>m</code>, respectively. Calculate the following values:</p> <ul> <li><code>answer1</code> : the number of indices <code>i</code> such that <code>nums1[i]</code> exists in <code>nums2</code>.</li> <li><code>answer2</code> : the number of indices <code>i</code> such that <code>nums2[i]</code> exists in <code>nums1</code>.</li> </ul> <p>Return <code>[answer1,answer2]</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">nums1 = [2,3,2], nums2 = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1]</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2956.Find%20Common%20Elements%20Between%20Two%20Arrays/images/3488_find_common_elements_between_two_arrays-t1.gif" style="width: 225px; height: 150px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [4,3,2,3,1], nums2 = [2,2,5,2,3,6]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4]</span></p> <p><strong>Explanation:</strong></p> <p>The elements at indices 1, 2, and 3 in <code>nums1</code> exist in <code>nums2</code> as well. So <code>answer1</code> is 3.</p> <p>The elements at indices 0, 1, 3, and 4 in <code>nums2</code> exist in <code>nums1</code>. So <code>answer2</code> is 4.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [3,4,2,3], nums2 = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0]</span></p> <p><strong>Explanation:</strong></p> <p>No numbers are common between <code>nums1</code> and <code>nums2</code>, so answer is [0,0].</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length</code></li> <li><code>m == nums2.length</code></li> <li><code>1 &lt;= n, m &lt;= 100</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 100</code></li> </ul>
Array; Hash Table
C++
class Solution { public: vector<int> findIntersectionValues(vector<int>& nums1, vector<int>& nums2) { int s1[101]{}; int s2[101]{}; for (int& x : nums1) { s1[x] = 1; } for (int& x : nums2) { s2[x] = 1; } vector<int> ans(2); for (int& x : nums1) { ans[0] += s2[x]; } for (int& x : nums2) { ans[1] += s1[x]; } return ans; } };
2,956
Find Common Elements Between Two Arrays
Easy
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of sizes <code>n</code> and <code>m</code>, respectively. Calculate the following values:</p> <ul> <li><code>answer1</code> : the number of indices <code>i</code> such that <code>nums1[i]</code> exists in <code>nums2</code>.</li> <li><code>answer2</code> : the number of indices <code>i</code> such that <code>nums2[i]</code> exists in <code>nums1</code>.</li> </ul> <p>Return <code>[answer1,answer2]</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">nums1 = [2,3,2], nums2 = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1]</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2956.Find%20Common%20Elements%20Between%20Two%20Arrays/images/3488_find_common_elements_between_two_arrays-t1.gif" style="width: 225px; height: 150px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [4,3,2,3,1], nums2 = [2,2,5,2,3,6]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4]</span></p> <p><strong>Explanation:</strong></p> <p>The elements at indices 1, 2, and 3 in <code>nums1</code> exist in <code>nums2</code> as well. So <code>answer1</code> is 3.</p> <p>The elements at indices 0, 1, 3, and 4 in <code>nums2</code> exist in <code>nums1</code>. So <code>answer2</code> is 4.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [3,4,2,3], nums2 = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0]</span></p> <p><strong>Explanation:</strong></p> <p>No numbers are common between <code>nums1</code> and <code>nums2</code>, so answer is [0,0].</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length</code></li> <li><code>m == nums2.length</code></li> <li><code>1 &lt;= n, m &lt;= 100</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 100</code></li> </ul>
Array; Hash Table
Go
func findIntersectionValues(nums1 []int, nums2 []int) []int { s1 := [101]int{} s2 := [101]int{} for _, x := range nums1 { s1[x] = 1 } for _, x := range nums2 { s2[x] = 1 } ans := make([]int, 2) for _, x := range nums1 { ans[0] += s2[x] } for _, x := range nums2 { ans[1] += s1[x] } return ans }
2,956
Find Common Elements Between Two Arrays
Easy
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of sizes <code>n</code> and <code>m</code>, respectively. Calculate the following values:</p> <ul> <li><code>answer1</code> : the number of indices <code>i</code> such that <code>nums1[i]</code> exists in <code>nums2</code>.</li> <li><code>answer2</code> : the number of indices <code>i</code> such that <code>nums2[i]</code> exists in <code>nums1</code>.</li> </ul> <p>Return <code>[answer1,answer2]</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">nums1 = [2,3,2], nums2 = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1]</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2956.Find%20Common%20Elements%20Between%20Two%20Arrays/images/3488_find_common_elements_between_two_arrays-t1.gif" style="width: 225px; height: 150px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [4,3,2,3,1], nums2 = [2,2,5,2,3,6]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4]</span></p> <p><strong>Explanation:</strong></p> <p>The elements at indices 1, 2, and 3 in <code>nums1</code> exist in <code>nums2</code> as well. So <code>answer1</code> is 3.</p> <p>The elements at indices 0, 1, 3, and 4 in <code>nums2</code> exist in <code>nums1</code>. So <code>answer2</code> is 4.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [3,4,2,3], nums2 = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0]</span></p> <p><strong>Explanation:</strong></p> <p>No numbers are common between <code>nums1</code> and <code>nums2</code>, so answer is [0,0].</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length</code></li> <li><code>m == nums2.length</code></li> <li><code>1 &lt;= n, m &lt;= 100</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 100</code></li> </ul>
Array; Hash Table
Java
class Solution { public int[] findIntersectionValues(int[] nums1, int[] nums2) { int[] s1 = new int[101]; int[] s2 = new int[101]; for (int x : nums1) { s1[x] = 1; } for (int x : nums2) { s2[x] = 1; } int[] ans = new int[2]; for (int x : nums1) { ans[0] += s2[x]; } for (int x : nums2) { ans[1] += s1[x]; } return ans; } }
2,956
Find Common Elements Between Two Arrays
Easy
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of sizes <code>n</code> and <code>m</code>, respectively. Calculate the following values:</p> <ul> <li><code>answer1</code> : the number of indices <code>i</code> such that <code>nums1[i]</code> exists in <code>nums2</code>.</li> <li><code>answer2</code> : the number of indices <code>i</code> such that <code>nums2[i]</code> exists in <code>nums1</code>.</li> </ul> <p>Return <code>[answer1,answer2]</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">nums1 = [2,3,2], nums2 = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1]</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2956.Find%20Common%20Elements%20Between%20Two%20Arrays/images/3488_find_common_elements_between_two_arrays-t1.gif" style="width: 225px; height: 150px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [4,3,2,3,1], nums2 = [2,2,5,2,3,6]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4]</span></p> <p><strong>Explanation:</strong></p> <p>The elements at indices 1, 2, and 3 in <code>nums1</code> exist in <code>nums2</code> as well. So <code>answer1</code> is 3.</p> <p>The elements at indices 0, 1, 3, and 4 in <code>nums2</code> exist in <code>nums1</code>. So <code>answer2</code> is 4.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [3,4,2,3], nums2 = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0]</span></p> <p><strong>Explanation:</strong></p> <p>No numbers are common between <code>nums1</code> and <code>nums2</code>, so answer is [0,0].</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length</code></li> <li><code>m == nums2.length</code></li> <li><code>1 &lt;= n, m &lt;= 100</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 100</code></li> </ul>
Array; Hash Table
Python
class Solution: def findIntersectionValues(self, nums1: List[int], nums2: List[int]) -> List[int]: s1, s2 = set(nums1), set(nums2) return [sum(x in s2 for x in nums1), sum(x in s1 for x in nums2)]
2,956
Find Common Elements Between Two Arrays
Easy
<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of sizes <code>n</code> and <code>m</code>, respectively. Calculate the following values:</p> <ul> <li><code>answer1</code> : the number of indices <code>i</code> such that <code>nums1[i]</code> exists in <code>nums2</code>.</li> <li><code>answer2</code> : the number of indices <code>i</code> such that <code>nums2[i]</code> exists in <code>nums1</code>.</li> </ul> <p>Return <code>[answer1,answer2]</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">nums1 = [2,3,2], nums2 = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,1]</span></p> <p><strong>Explanation:</strong></p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2956.Find%20Common%20Elements%20Between%20Two%20Arrays/images/3488_find_common_elements_between_two_arrays-t1.gif" style="width: 225px; height: 150px;" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [4,3,2,3,1], nums2 = [2,2,5,2,3,6]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4]</span></p> <p><strong>Explanation:</strong></p> <p>The elements at indices 1, 2, and 3 in <code>nums1</code> exist in <code>nums2</code> as well. So <code>answer1</code> is 3.</p> <p>The elements at indices 0, 1, 3, and 4 in <code>nums2</code> exist in <code>nums1</code>. So <code>answer2</code> is 4.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums1 = [3,4,2,3], nums2 = [1,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0]</span></p> <p><strong>Explanation:</strong></p> <p>No numbers are common between <code>nums1</code> and <code>nums2</code>, so answer is [0,0].</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length</code></li> <li><code>m == nums2.length</code></li> <li><code>1 &lt;= n, m &lt;= 100</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 100</code></li> </ul>
Array; Hash Table
TypeScript
function findIntersectionValues(nums1: number[], nums2: number[]): number[] { const s1: number[] = Array(101).fill(0); const s2: number[] = Array(101).fill(0); for (const x of nums1) { s1[x] = 1; } for (const x of nums2) { s2[x] = 1; } const ans: number[] = Array(2).fill(0); for (const x of nums1) { ans[0] += s2[x]; } for (const x of nums2) { ans[1] += s1[x]; } return ans; }
2,957
Remove Adjacent Almost-Equal Characters
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>word</code> and change <code>word[i]</code> to any lowercase English letter.</p> <p>Return <em>the <strong>minimum</strong> number of operations needed to remove all adjacent <strong>almost-equal</strong> characters from</em> <code>word</code>.</p> <p>Two characters <code>a</code> and <code>b</code> are <strong>almost-equal</strong> if <code>a == b</code> or <code>a</code> and <code>b</code> are adjacent in the alphabet.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaaaa&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can change word into &quot;a<strong><u>c</u></strong>a<u><strong>c</strong></u>a&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abddez&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can change word into &quot;<strong><u>y</u></strong>bd<u><strong>o</strong></u>ez&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;zyxyxyz&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> We can change word into &quot;z<u><strong>a</strong></u>x<u><strong>a</strong></u>x<strong><u>a</u></strong>z&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Greedy; String; Dynamic Programming
C++
class Solution { public: int removeAlmostEqualCharacters(string word) { int ans = 0, n = word.size(); for (int i = 1; i < n; ++i) { if (abs(word[i] - word[i - 1]) < 2) { ++ans; ++i; } } return ans; } };
2,957
Remove Adjacent Almost-Equal Characters
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>word</code> and change <code>word[i]</code> to any lowercase English letter.</p> <p>Return <em>the <strong>minimum</strong> number of operations needed to remove all adjacent <strong>almost-equal</strong> characters from</em> <code>word</code>.</p> <p>Two characters <code>a</code> and <code>b</code> are <strong>almost-equal</strong> if <code>a == b</code> or <code>a</code> and <code>b</code> are adjacent in the alphabet.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaaaa&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can change word into &quot;a<strong><u>c</u></strong>a<u><strong>c</strong></u>a&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abddez&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can change word into &quot;<strong><u>y</u></strong>bd<u><strong>o</strong></u>ez&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;zyxyxyz&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> We can change word into &quot;z<u><strong>a</strong></u>x<u><strong>a</strong></u>x<strong><u>a</u></strong>z&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Greedy; String; Dynamic Programming
Go
func removeAlmostEqualCharacters(word string) (ans int) { for i := 1; i < len(word); i++ { if abs(int(word[i])-int(word[i-1])) < 2 { ans++ i++ } } return } func abs(x int) int { if x < 0 { return -x } return x }
2,957
Remove Adjacent Almost-Equal Characters
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>word</code> and change <code>word[i]</code> to any lowercase English letter.</p> <p>Return <em>the <strong>minimum</strong> number of operations needed to remove all adjacent <strong>almost-equal</strong> characters from</em> <code>word</code>.</p> <p>Two characters <code>a</code> and <code>b</code> are <strong>almost-equal</strong> if <code>a == b</code> or <code>a</code> and <code>b</code> are adjacent in the alphabet.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaaaa&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can change word into &quot;a<strong><u>c</u></strong>a<u><strong>c</strong></u>a&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abddez&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can change word into &quot;<strong><u>y</u></strong>bd<u><strong>o</strong></u>ez&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;zyxyxyz&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> We can change word into &quot;z<u><strong>a</strong></u>x<u><strong>a</strong></u>x<strong><u>a</u></strong>z&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Greedy; String; Dynamic Programming
Java
class Solution { public int removeAlmostEqualCharacters(String word) { int ans = 0, n = word.length(); for (int i = 1; i < n; ++i) { if (Math.abs(word.charAt(i) - word.charAt(i - 1)) < 2) { ++ans; ++i; } } return ans; } }
2,957
Remove Adjacent Almost-Equal Characters
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>word</code> and change <code>word[i]</code> to any lowercase English letter.</p> <p>Return <em>the <strong>minimum</strong> number of operations needed to remove all adjacent <strong>almost-equal</strong> characters from</em> <code>word</code>.</p> <p>Two characters <code>a</code> and <code>b</code> are <strong>almost-equal</strong> if <code>a == b</code> or <code>a</code> and <code>b</code> are adjacent in the alphabet.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaaaa&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can change word into &quot;a<strong><u>c</u></strong>a<u><strong>c</strong></u>a&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abddez&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can change word into &quot;<strong><u>y</u></strong>bd<u><strong>o</strong></u>ez&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;zyxyxyz&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> We can change word into &quot;z<u><strong>a</strong></u>x<u><strong>a</strong></u>x<strong><u>a</u></strong>z&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Greedy; String; Dynamic Programming
Python
class Solution: def removeAlmostEqualCharacters(self, word: str) -> int: ans = 0 i, n = 1, len(word) while i < n: if abs(ord(word[i]) - ord(word[i - 1])) < 2: ans += 1 i += 2 else: i += 1 return ans
2,957
Remove Adjacent Almost-Equal Characters
Medium
<p>You are given a <strong>0-indexed</strong> string <code>word</code>.</p> <p>In one operation, you can pick any index <code>i</code> of <code>word</code> and change <code>word[i]</code> to any lowercase English letter.</p> <p>Return <em>the <strong>minimum</strong> number of operations needed to remove all adjacent <strong>almost-equal</strong> characters from</em> <code>word</code>.</p> <p>Two characters <code>a</code> and <code>b</code> are <strong>almost-equal</strong> if <code>a == b</code> or <code>a</code> and <code>b</code> are adjacent in the alphabet.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> word = &quot;aaaaa&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can change word into &quot;a<strong><u>c</u></strong>a<u><strong>c</strong></u>a&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> word = &quot;abddez&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can change word into &quot;<strong><u>y</u></strong>bd<u><strong>o</strong></u>ez&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> word = &quot;zyxyxyz&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> We can change word into &quot;z<u><strong>a</strong></u>x<u><strong>a</strong></u>x<strong><u>a</u></strong>z&quot; which does not have any adjacent almost-equal characters. It can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= word.length &lt;= 100</code></li> <li><code>word</code> consists only of lowercase English letters.</li> </ul>
Greedy; String; Dynamic Programming
TypeScript
function removeAlmostEqualCharacters(word: string): number { let ans = 0; for (let i = 1; i < word.length; ++i) { if (Math.abs(word.charCodeAt(i) - word.charCodeAt(i - 1)) < 2) { ++ans; ++i; } } return ans; }
2,958
Length of Longest Subarray With at Most K Frequency
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>The <strong>frequency</strong> of an element <code>x</code> is the number of times it occurs in an array.</p> <p>An array is called <strong>good</strong> if the frequency of each element in this array is <strong>less than or equal</strong> to <code>k</code>.</p> <p>Return <em>the length of the <strong>longest</strong> <strong>good</strong> subarray of</em> <code>nums</code><em>.</em></p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1,2,3,1,2], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> The longest possible good subarray is [1,2,3,1,2,3] since the values 1, 2, and 3 occur at most twice in this subarray. Note that the subarrays [2,3,1,2,3,1] and [3,1,2,3,1,2] are also good. It can be shown that there are no good subarrays with length more than 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1,2], k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest possible good subarray is [1,2] since the values 1 and 2 occur at most once in this subarray. Note that the subarray [2,1] is also good. It can be shown that there are no good subarrays with length more than 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5,5,5,5,5], k = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest possible good subarray is [5,5,5,5] since the value 5 occurs 4 times in this subarray. It can be shown that there are no good subarrays with length more than 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Sliding Window
C++
class Solution { public: int maxSubarrayLength(vector<int>& nums, int k) { unordered_map<int, int> cnt; int ans = 0; for (int i = 0, j = 0; i < nums.size(); ++i) { ++cnt[nums[i]]; while (cnt[nums[i]] > k) { --cnt[nums[j++]]; } ans = max(ans, i - j + 1); } return ans; } };
2,958
Length of Longest Subarray With at Most K Frequency
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>The <strong>frequency</strong> of an element <code>x</code> is the number of times it occurs in an array.</p> <p>An array is called <strong>good</strong> if the frequency of each element in this array is <strong>less than or equal</strong> to <code>k</code>.</p> <p>Return <em>the length of the <strong>longest</strong> <strong>good</strong> subarray of</em> <code>nums</code><em>.</em></p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1,2,3,1,2], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> The longest possible good subarray is [1,2,3,1,2,3] since the values 1, 2, and 3 occur at most twice in this subarray. Note that the subarrays [2,3,1,2,3,1] and [3,1,2,3,1,2] are also good. It can be shown that there are no good subarrays with length more than 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1,2], k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest possible good subarray is [1,2] since the values 1 and 2 occur at most once in this subarray. Note that the subarray [2,1] is also good. It can be shown that there are no good subarrays with length more than 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5,5,5,5,5], k = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest possible good subarray is [5,5,5,5] since the value 5 occurs 4 times in this subarray. It can be shown that there are no good subarrays with length more than 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Sliding Window
Go
func maxSubarrayLength(nums []int, k int) (ans int) { cnt := map[int]int{} for i, j, n := 0, 0, len(nums); i < n; i++ { cnt[nums[i]]++ for ; cnt[nums[i]] > k; j++ { cnt[nums[j]]-- } ans = max(ans, i-j+1) } return }
2,958
Length of Longest Subarray With at Most K Frequency
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>The <strong>frequency</strong> of an element <code>x</code> is the number of times it occurs in an array.</p> <p>An array is called <strong>good</strong> if the frequency of each element in this array is <strong>less than or equal</strong> to <code>k</code>.</p> <p>Return <em>the length of the <strong>longest</strong> <strong>good</strong> subarray of</em> <code>nums</code><em>.</em></p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1,2,3,1,2], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> The longest possible good subarray is [1,2,3,1,2,3] since the values 1, 2, and 3 occur at most twice in this subarray. Note that the subarrays [2,3,1,2,3,1] and [3,1,2,3,1,2] are also good. It can be shown that there are no good subarrays with length more than 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1,2], k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest possible good subarray is [1,2] since the values 1 and 2 occur at most once in this subarray. Note that the subarray [2,1] is also good. It can be shown that there are no good subarrays with length more than 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5,5,5,5,5], k = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest possible good subarray is [5,5,5,5] since the value 5 occurs 4 times in this subarray. It can be shown that there are no good subarrays with length more than 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Sliding Window
Java
class Solution { public int maxSubarrayLength(int[] nums, int k) { Map<Integer, Integer> cnt = new HashMap<>(); int ans = 0; for (int i = 0, j = 0; i < nums.length; ++i) { cnt.merge(nums[i], 1, Integer::sum); while (cnt.get(nums[i]) > k) { cnt.merge(nums[j++], -1, Integer::sum); } ans = Math.max(ans, i - j + 1); } return ans; } }
2,958
Length of Longest Subarray With at Most K Frequency
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>The <strong>frequency</strong> of an element <code>x</code> is the number of times it occurs in an array.</p> <p>An array is called <strong>good</strong> if the frequency of each element in this array is <strong>less than or equal</strong> to <code>k</code>.</p> <p>Return <em>the length of the <strong>longest</strong> <strong>good</strong> subarray of</em> <code>nums</code><em>.</em></p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1,2,3,1,2], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> The longest possible good subarray is [1,2,3,1,2,3] since the values 1, 2, and 3 occur at most twice in this subarray. Note that the subarrays [2,3,1,2,3,1] and [3,1,2,3,1,2] are also good. It can be shown that there are no good subarrays with length more than 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1,2], k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest possible good subarray is [1,2] since the values 1 and 2 occur at most once in this subarray. Note that the subarray [2,1] is also good. It can be shown that there are no good subarrays with length more than 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5,5,5,5,5], k = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest possible good subarray is [5,5,5,5] since the value 5 occurs 4 times in this subarray. It can be shown that there are no good subarrays with length more than 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Sliding Window
Python
class Solution: def maxSubarrayLength(self, nums: List[int], k: int) -> int: cnt = defaultdict(int) ans = j = 0 for i, x in enumerate(nums): cnt[x] += 1 while cnt[x] > k: cnt[nums[j]] -= 1 j += 1 ans = max(ans, i - j + 1) return ans
2,958
Length of Longest Subarray With at Most K Frequency
Medium
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p> <p>The <strong>frequency</strong> of an element <code>x</code> is the number of times it occurs in an array.</p> <p>An array is called <strong>good</strong> if the frequency of each element in this array is <strong>less than or equal</strong> to <code>k</code>.</p> <p>Return <em>the length of the <strong>longest</strong> <strong>good</strong> subarray of</em> <code>nums</code><em>.</em></p> <p>A <strong>subarray</strong> is a contiguous non-empty sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1,2,3,1,2], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> The longest possible good subarray is [1,2,3,1,2,3] since the values 1, 2, and 3 occur at most twice in this subarray. Note that the subarrays [2,3,1,2,3,1] and [3,1,2,3,1,2] are also good. It can be shown that there are no good subarrays with length more than 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,2,1,2,1,2], k = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest possible good subarray is [1,2] since the values 1 and 2 occur at most once in this subarray. Note that the subarray [2,1] is also good. It can be shown that there are no good subarrays with length more than 2. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5,5,5,5,5], k = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest possible good subarray is [5,5,5,5] since the value 5 occurs 4 times in this subarray. It can be shown that there are no good subarrays with length more than 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= nums.length</code></li> </ul>
Array; Hash Table; Sliding Window
TypeScript
function maxSubarrayLength(nums: number[], k: number): number { const cnt: Map<number, number> = new Map(); let ans = 0; for (let i = 0, j = 0; i < nums.length; ++i) { cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); for (; cnt.get(nums[i])! > k; ++j) { cnt.set(nums[j], cnt.get(nums[j])! - 1); } ans = Math.max(ans, i - j + 1); } return ans; }
2,959
Number of Possible Sets of Closing Branches
Hard
<p>There is a company with <code>n</code> branches across the country, some of which are connected by roads. Initially, all branches are reachable from each other by traveling some roads.</p> <p>The company has realized that they are spending an excessive amount of time traveling between their branches. As a result, they have decided to close down some of these branches (<strong>possibly none</strong>). However, they want to ensure that the remaining branches have a distance of at most <code>maxDistance</code> from each other.</p> <p>The <strong>distance</strong> between two branches is the <strong>minimum</strong> total traveled length needed to reach one branch from another.</p> <p>You are given integers <code>n</code>, <code>maxDistance</code>, and a <strong>0-indexed</strong> 2D array <code>roads</code>, where <code>roads[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> represents the <strong>undirected</strong> road between branches <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with length <code>w<sub>i</sub></code>.</p> <p>Return <em>the number of possible sets of closing branches, so that any branch has a distance of at most </em><code>maxDistance</code><em> from any other</em>.</p> <p><strong>Note</strong> that, after closing a branch, the company will no longer have access to any roads connected to it.</p> <p><strong>Note</strong> that, multiple roads are allowed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2959.Number%20of%20Possible%20Sets%20of%20Closing%20Branches/images/example11.png" style="width: 221px; height: 191px;" /> <pre> <strong>Input:</strong> n = 3, maxDistance = 5, roads = [[0,1,2],[1,2,10],[0,2,10]] <strong>Output:</strong> 5 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [2], after closing, active branches are [0,1] and they are reachable to each other within distance 2. - The set [0,1], after closing, the active branch is [2]. - The set [1,2], after closing, the active branch is [0]. - The set [0,2], after closing, the active branch is [1]. - The set [0,1,2], after closing, there are no active branches. It can be proven, that there are only 5 possible sets of closing branches. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2959.Number%20of%20Possible%20Sets%20of%20Closing%20Branches/images/example22.png" style="width: 221px; height: 241px;" /> <pre> <strong>Input:</strong> n = 3, maxDistance = 5, roads = [[0,1,20],[0,1,10],[1,2,2],[0,2,2]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [], after closing, active branches are [0,1,2] and they are reachable to each other within distance 4. - The set [0], after closing, active branches are [1,2] and they are reachable to each other within distance 2. - The set [1], after closing, active branches are [0,2] and they are reachable to each other within distance 2. - The set [0,1], after closing, the active branch is [2]. - The set [1,2], after closing, the active branch is [0]. - The set [0,2], after closing, the active branch is [1]. - The set [0,1,2], after closing, there are no active branches. It can be proven, that there are only 7 possible sets of closing branches. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1, maxDistance = 10, roads = [] <strong>Output:</strong> 2 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [], after closing, the active branch is [0]. - The set [0], after closing, there are no active branches. It can be proven, that there are only 2 possible sets of closing branches. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10</code></li> <li><code>1 &lt;= maxDistance &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= roads.length &lt;= 1000</code></li> <li><code>roads[i].length == 3</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n - 1</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li><code>1 &lt;= w<sub>i</sub> &lt;= 1000</code></li> <li>All branches are reachable from each other by traveling some roads.</li> </ul>
Bit Manipulation; Graph; Enumeration; Shortest Path; Heap (Priority Queue)
C++
class Solution { public: int numberOfSets(int n, int maxDistance, vector<vector<int>>& roads) { int ans = 0; for (int mask = 0; mask < 1 << n; ++mask) { int g[n][n]; memset(g, 0x3f, sizeof(g)); for (auto& e : roads) { int u = e[0], v = e[1], w = e[2]; if ((mask >> u & 1) & (mask >> v & 1)) { g[u][v] = min(g[u][v], w); g[v][u] = min(g[v][u], w); } } for (int k = 0; k < n; ++k) { if (mask >> k & 1) { g[k][k] = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { g[i][j] = min(g[i][j], g[i][k] + g[k][j]); } } } } int ok = 1; for (int i = 0; i < n && ok == 1; ++i) { for (int j = 0; j < n && ok == 1; ++j) { if ((mask >> i & 1) & (mask >> j & 1) && g[i][j] > maxDistance) { ok = 0; } } } ans += ok; } return ans; } };
2,959
Number of Possible Sets of Closing Branches
Hard
<p>There is a company with <code>n</code> branches across the country, some of which are connected by roads. Initially, all branches are reachable from each other by traveling some roads.</p> <p>The company has realized that they are spending an excessive amount of time traveling between their branches. As a result, they have decided to close down some of these branches (<strong>possibly none</strong>). However, they want to ensure that the remaining branches have a distance of at most <code>maxDistance</code> from each other.</p> <p>The <strong>distance</strong> between two branches is the <strong>minimum</strong> total traveled length needed to reach one branch from another.</p> <p>You are given integers <code>n</code>, <code>maxDistance</code>, and a <strong>0-indexed</strong> 2D array <code>roads</code>, where <code>roads[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> represents the <strong>undirected</strong> road between branches <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with length <code>w<sub>i</sub></code>.</p> <p>Return <em>the number of possible sets of closing branches, so that any branch has a distance of at most </em><code>maxDistance</code><em> from any other</em>.</p> <p><strong>Note</strong> that, after closing a branch, the company will no longer have access to any roads connected to it.</p> <p><strong>Note</strong> that, multiple roads are allowed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2959.Number%20of%20Possible%20Sets%20of%20Closing%20Branches/images/example11.png" style="width: 221px; height: 191px;" /> <pre> <strong>Input:</strong> n = 3, maxDistance = 5, roads = [[0,1,2],[1,2,10],[0,2,10]] <strong>Output:</strong> 5 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [2], after closing, active branches are [0,1] and they are reachable to each other within distance 2. - The set [0,1], after closing, the active branch is [2]. - The set [1,2], after closing, the active branch is [0]. - The set [0,2], after closing, the active branch is [1]. - The set [0,1,2], after closing, there are no active branches. It can be proven, that there are only 5 possible sets of closing branches. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2959.Number%20of%20Possible%20Sets%20of%20Closing%20Branches/images/example22.png" style="width: 221px; height: 241px;" /> <pre> <strong>Input:</strong> n = 3, maxDistance = 5, roads = [[0,1,20],[0,1,10],[1,2,2],[0,2,2]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [], after closing, active branches are [0,1,2] and they are reachable to each other within distance 4. - The set [0], after closing, active branches are [1,2] and they are reachable to each other within distance 2. - The set [1], after closing, active branches are [0,2] and they are reachable to each other within distance 2. - The set [0,1], after closing, the active branch is [2]. - The set [1,2], after closing, the active branch is [0]. - The set [0,2], after closing, the active branch is [1]. - The set [0,1,2], after closing, there are no active branches. It can be proven, that there are only 7 possible sets of closing branches. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1, maxDistance = 10, roads = [] <strong>Output:</strong> 2 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [], after closing, the active branch is [0]. - The set [0], after closing, there are no active branches. It can be proven, that there are only 2 possible sets of closing branches. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10</code></li> <li><code>1 &lt;= maxDistance &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= roads.length &lt;= 1000</code></li> <li><code>roads[i].length == 3</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n - 1</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li><code>1 &lt;= w<sub>i</sub> &lt;= 1000</code></li> <li>All branches are reachable from each other by traveling some roads.</li> </ul>
Bit Manipulation; Graph; Enumeration; Shortest Path; Heap (Priority Queue)
Go
func numberOfSets(n int, maxDistance int, roads [][]int) (ans int) { for mask := 0; mask < 1<<n; mask++ { g := make([][]int, n) for i := range g { g[i] = make([]int, n) for j := range g[i] { g[i][j] = 1 << 29 } } for _, e := range roads { u, v, w := e[0], e[1], e[2] if mask>>u&1 == 1 && mask>>v&1 == 1 { g[u][v] = min(g[u][v], w) g[v][u] = min(g[v][u], w) } } for k := 0; k < n; k++ { if mask>>k&1 == 1 { g[k][k] = 0 for i := 0; i < n; i++ { for j := 0; j < n; j++ { g[i][j] = min(g[i][j], g[i][k]+g[k][j]) } } } } ok := 1 for i := 0; i < n && ok == 1; i++ { for j := 0; j < n && ok == 1; j++ { if mask>>i&1 == 1 && mask>>j&1 == 1 && g[i][j] > maxDistance { ok = 0 } } } ans += ok } return }
2,959
Number of Possible Sets of Closing Branches
Hard
<p>There is a company with <code>n</code> branches across the country, some of which are connected by roads. Initially, all branches are reachable from each other by traveling some roads.</p> <p>The company has realized that they are spending an excessive amount of time traveling between their branches. As a result, they have decided to close down some of these branches (<strong>possibly none</strong>). However, they want to ensure that the remaining branches have a distance of at most <code>maxDistance</code> from each other.</p> <p>The <strong>distance</strong> between two branches is the <strong>minimum</strong> total traveled length needed to reach one branch from another.</p> <p>You are given integers <code>n</code>, <code>maxDistance</code>, and a <strong>0-indexed</strong> 2D array <code>roads</code>, where <code>roads[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> represents the <strong>undirected</strong> road between branches <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with length <code>w<sub>i</sub></code>.</p> <p>Return <em>the number of possible sets of closing branches, so that any branch has a distance of at most </em><code>maxDistance</code><em> from any other</em>.</p> <p><strong>Note</strong> that, after closing a branch, the company will no longer have access to any roads connected to it.</p> <p><strong>Note</strong> that, multiple roads are allowed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2959.Number%20of%20Possible%20Sets%20of%20Closing%20Branches/images/example11.png" style="width: 221px; height: 191px;" /> <pre> <strong>Input:</strong> n = 3, maxDistance = 5, roads = [[0,1,2],[1,2,10],[0,2,10]] <strong>Output:</strong> 5 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [2], after closing, active branches are [0,1] and they are reachable to each other within distance 2. - The set [0,1], after closing, the active branch is [2]. - The set [1,2], after closing, the active branch is [0]. - The set [0,2], after closing, the active branch is [1]. - The set [0,1,2], after closing, there are no active branches. It can be proven, that there are only 5 possible sets of closing branches. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2959.Number%20of%20Possible%20Sets%20of%20Closing%20Branches/images/example22.png" style="width: 221px; height: 241px;" /> <pre> <strong>Input:</strong> n = 3, maxDistance = 5, roads = [[0,1,20],[0,1,10],[1,2,2],[0,2,2]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [], after closing, active branches are [0,1,2] and they are reachable to each other within distance 4. - The set [0], after closing, active branches are [1,2] and they are reachable to each other within distance 2. - The set [1], after closing, active branches are [0,2] and they are reachable to each other within distance 2. - The set [0,1], after closing, the active branch is [2]. - The set [1,2], after closing, the active branch is [0]. - The set [0,2], after closing, the active branch is [1]. - The set [0,1,2], after closing, there are no active branches. It can be proven, that there are only 7 possible sets of closing branches. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1, maxDistance = 10, roads = [] <strong>Output:</strong> 2 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [], after closing, the active branch is [0]. - The set [0], after closing, there are no active branches. It can be proven, that there are only 2 possible sets of closing branches. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10</code></li> <li><code>1 &lt;= maxDistance &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= roads.length &lt;= 1000</code></li> <li><code>roads[i].length == 3</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n - 1</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li><code>1 &lt;= w<sub>i</sub> &lt;= 1000</code></li> <li>All branches are reachable from each other by traveling some roads.</li> </ul>
Bit Manipulation; Graph; Enumeration; Shortest Path; Heap (Priority Queue)
Java
class Solution { public int numberOfSets(int n, int maxDistance, int[][] roads) { int ans = 0; for (int mask = 0; mask < 1 << n; ++mask) { int[][] g = new int[n][n]; for (var e : g) { Arrays.fill(e, 1 << 29); } for (var e : roads) { int u = e[0], v = e[1], w = e[2]; if ((mask >> u & 1) == 1 && (mask >> v & 1) == 1) { g[u][v] = Math.min(g[u][v], w); g[v][u] = Math.min(g[v][u], w); } } for (int k = 0; k < n; ++k) { if ((mask >> k & 1) == 1) { g[k][k] = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); } } } } int ok = 1; for (int i = 0; i < n && ok == 1; ++i) { for (int j = 0; j < n && ok == 1; ++j) { if ((mask >> i & 1) == 1 && (mask >> j & 1) == 1) { if (g[i][j] > maxDistance) { ok = 0; } } } } ans += ok; } return ans; } }
2,959
Number of Possible Sets of Closing Branches
Hard
<p>There is a company with <code>n</code> branches across the country, some of which are connected by roads. Initially, all branches are reachable from each other by traveling some roads.</p> <p>The company has realized that they are spending an excessive amount of time traveling between their branches. As a result, they have decided to close down some of these branches (<strong>possibly none</strong>). However, they want to ensure that the remaining branches have a distance of at most <code>maxDistance</code> from each other.</p> <p>The <strong>distance</strong> between two branches is the <strong>minimum</strong> total traveled length needed to reach one branch from another.</p> <p>You are given integers <code>n</code>, <code>maxDistance</code>, and a <strong>0-indexed</strong> 2D array <code>roads</code>, where <code>roads[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> represents the <strong>undirected</strong> road between branches <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with length <code>w<sub>i</sub></code>.</p> <p>Return <em>the number of possible sets of closing branches, so that any branch has a distance of at most </em><code>maxDistance</code><em> from any other</em>.</p> <p><strong>Note</strong> that, after closing a branch, the company will no longer have access to any roads connected to it.</p> <p><strong>Note</strong> that, multiple roads are allowed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2959.Number%20of%20Possible%20Sets%20of%20Closing%20Branches/images/example11.png" style="width: 221px; height: 191px;" /> <pre> <strong>Input:</strong> n = 3, maxDistance = 5, roads = [[0,1,2],[1,2,10],[0,2,10]] <strong>Output:</strong> 5 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [2], after closing, active branches are [0,1] and they are reachable to each other within distance 2. - The set [0,1], after closing, the active branch is [2]. - The set [1,2], after closing, the active branch is [0]. - The set [0,2], after closing, the active branch is [1]. - The set [0,1,2], after closing, there are no active branches. It can be proven, that there are only 5 possible sets of closing branches. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2959.Number%20of%20Possible%20Sets%20of%20Closing%20Branches/images/example22.png" style="width: 221px; height: 241px;" /> <pre> <strong>Input:</strong> n = 3, maxDistance = 5, roads = [[0,1,20],[0,1,10],[1,2,2],[0,2,2]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [], after closing, active branches are [0,1,2] and they are reachable to each other within distance 4. - The set [0], after closing, active branches are [1,2] and they are reachable to each other within distance 2. - The set [1], after closing, active branches are [0,2] and they are reachable to each other within distance 2. - The set [0,1], after closing, the active branch is [2]. - The set [1,2], after closing, the active branch is [0]. - The set [0,2], after closing, the active branch is [1]. - The set [0,1,2], after closing, there are no active branches. It can be proven, that there are only 7 possible sets of closing branches. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1, maxDistance = 10, roads = [] <strong>Output:</strong> 2 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [], after closing, the active branch is [0]. - The set [0], after closing, there are no active branches. It can be proven, that there are only 2 possible sets of closing branches. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10</code></li> <li><code>1 &lt;= maxDistance &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= roads.length &lt;= 1000</code></li> <li><code>roads[i].length == 3</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n - 1</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li><code>1 &lt;= w<sub>i</sub> &lt;= 1000</code></li> <li>All branches are reachable from each other by traveling some roads.</li> </ul>
Bit Manipulation; Graph; Enumeration; Shortest Path; Heap (Priority Queue)
Python
class Solution: def numberOfSets(self, n: int, maxDistance: int, roads: List[List[int]]) -> int: ans = 0 for mask in range(1 << n): g = [[inf] * n for _ in range(n)] for u, v, w in roads: if mask >> u & 1 and mask >> v & 1: g[u][v] = min(g[u][v], w) g[v][u] = min(g[v][u], w) for k in range(n): if mask >> k & 1: g[k][k] = 0 for i in range(n): for j in range(n): # g[i][j] = min(g[i][j], g[i][k] + g[k][j]) if g[i][k] + g[k][j] < g[i][j]: g[i][j] = g[i][k] + g[k][j] if all( g[i][j] <= maxDistance for i in range(n) for j in range(n) if mask >> i & 1 and mask >> j & 1 ): ans += 1 return ans
2,959
Number of Possible Sets of Closing Branches
Hard
<p>There is a company with <code>n</code> branches across the country, some of which are connected by roads. Initially, all branches are reachable from each other by traveling some roads.</p> <p>The company has realized that they are spending an excessive amount of time traveling between their branches. As a result, they have decided to close down some of these branches (<strong>possibly none</strong>). However, they want to ensure that the remaining branches have a distance of at most <code>maxDistance</code> from each other.</p> <p>The <strong>distance</strong> between two branches is the <strong>minimum</strong> total traveled length needed to reach one branch from another.</p> <p>You are given integers <code>n</code>, <code>maxDistance</code>, and a <strong>0-indexed</strong> 2D array <code>roads</code>, where <code>roads[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> represents the <strong>undirected</strong> road between branches <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with length <code>w<sub>i</sub></code>.</p> <p>Return <em>the number of possible sets of closing branches, so that any branch has a distance of at most </em><code>maxDistance</code><em> from any other</em>.</p> <p><strong>Note</strong> that, after closing a branch, the company will no longer have access to any roads connected to it.</p> <p><strong>Note</strong> that, multiple roads are allowed.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2959.Number%20of%20Possible%20Sets%20of%20Closing%20Branches/images/example11.png" style="width: 221px; height: 191px;" /> <pre> <strong>Input:</strong> n = 3, maxDistance = 5, roads = [[0,1,2],[1,2,10],[0,2,10]] <strong>Output:</strong> 5 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [2], after closing, active branches are [0,1] and they are reachable to each other within distance 2. - The set [0,1], after closing, the active branch is [2]. - The set [1,2], after closing, the active branch is [0]. - The set [0,2], after closing, the active branch is [1]. - The set [0,1,2], after closing, there are no active branches. It can be proven, that there are only 5 possible sets of closing branches. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2900-2999/2959.Number%20of%20Possible%20Sets%20of%20Closing%20Branches/images/example22.png" style="width: 221px; height: 241px;" /> <pre> <strong>Input:</strong> n = 3, maxDistance = 5, roads = [[0,1,20],[0,1,10],[1,2,2],[0,2,2]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [], after closing, active branches are [0,1,2] and they are reachable to each other within distance 4. - The set [0], after closing, active branches are [1,2] and they are reachable to each other within distance 2. - The set [1], after closing, active branches are [0,2] and they are reachable to each other within distance 2. - The set [0,1], after closing, the active branch is [2]. - The set [1,2], after closing, the active branch is [0]. - The set [0,2], after closing, the active branch is [1]. - The set [0,1,2], after closing, there are no active branches. It can be proven, that there are only 7 possible sets of closing branches. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 1, maxDistance = 10, roads = [] <strong>Output:</strong> 2 <strong>Explanation:</strong> The possible sets of closing branches are: - The set [], after closing, the active branch is [0]. - The set [0], after closing, there are no active branches. It can be proven, that there are only 2 possible sets of closing branches. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10</code></li> <li><code>1 &lt;= maxDistance &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= roads.length &lt;= 1000</code></li> <li><code>roads[i].length == 3</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n - 1</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li><code>1 &lt;= w<sub>i</sub> &lt;= 1000</code></li> <li>All branches are reachable from each other by traveling some roads.</li> </ul>
Bit Manipulation; Graph; Enumeration; Shortest Path; Heap (Priority Queue)
TypeScript
function numberOfSets(n: number, maxDistance: number, roads: number[][]): number { let ans = 0; for (let mask = 0; mask < 1 << n; ++mask) { const g: number[][] = Array.from({ length: n }, () => Array(n).fill(Infinity)); for (const [u, v, w] of roads) { if ((mask >> u) & 1 && (mask >> v) & 1) { g[u][v] = Math.min(g[u][v], w); g[v][u] = Math.min(g[v][u], w); } } for (let k = 0; k < n; ++k) { if ((mask >> k) & 1) { g[k][k] = 0; for (let i = 0; i < n; ++i) { for (let j = 0; j < n; ++j) { g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); } } } } let ok = 1; for (let i = 0; i < n && ok; ++i) { for (let j = 0; j < n && ok; ++j) { if ((mask >> i) & 1 && (mask >> j) & 1 && g[i][j] > maxDistance) { ok = 0; } } } ans += ok; } return ans; }
2,960
Count Tested Devices After Test Operations
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>batteryPercentages</code> having length <code>n</code>, denoting the battery percentages of <code>n</code> <strong>0-indexed</strong> devices.</p> <p>Your task is to test each device <code>i</code> <strong>in order</strong> from <code>0</code> to <code>n - 1</code>, by performing the following test operations:</p> <ul> <li>If <code>batteryPercentages[i]</code> is <strong>greater</strong> than <code>0</code>: <ul> <li><strong>Increment</strong> the count of tested devices.</li> <li><strong>Decrease</strong> the battery percentage of all devices with indices <code>j</code> in the range <code>[i + 1, n - 1]</code> by <code>1</code>, ensuring their battery percentage <strong>never goes below</strong> <code>0</code>, i.e, <code>batteryPercentages[j] = max(0, batteryPercentages[j] - 1)</code>.</li> <li>Move to the next device.</li> </ul> </li> <li>Otherwise, move to the next device without performing any test.</li> </ul> <p>Return <em>an integer denoting the number of devices that will be tested after performing the test operations in order.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> batteryPercentages = [1,1,2,1,3] <strong>Output:</strong> 3 <strong>Explanation: </strong>Performing the test operations in order starting from device 0: At device 0, batteryPercentages[0] &gt; 0, so there is now 1 tested device, and batteryPercentages becomes [1,0,1,0,2]. At device 1, batteryPercentages[1] == 0, so we move to the next device without testing. At device 2, batteryPercentages[2] &gt; 0, so there are now 2 tested devices, and batteryPercentages becomes [1,0,1,0,1]. At device 3, batteryPercentages[3] == 0, so we move to the next device without testing. At device 4, batteryPercentages[4] &gt; 0, so there are now 3 tested devices, and batteryPercentages stays the same. So, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> batteryPercentages = [0,1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> Performing the test operations in order starting from device 0: At device 0, batteryPercentages[0] == 0, so we move to the next device without testing. At device 1, batteryPercentages[1] &gt; 0, so there is now 1 tested device, and batteryPercentages becomes [0,1,1]. At device 2, batteryPercentages[2] &gt; 0, so there are now 2 tested devices, and batteryPercentages stays the same. So, the answer is 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == batteryPercentages.length &lt;= 100 </code></li> <li><code>0 &lt;= batteryPercentages[i] &lt;= 100</code></li> </ul>
Array; Counting; Simulation
C++
class Solution { public: int countTestedDevices(vector<int>& batteryPercentages) { int ans = 0; for (int x : batteryPercentages) { ans += x > ans; } return ans; } };
2,960
Count Tested Devices After Test Operations
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>batteryPercentages</code> having length <code>n</code>, denoting the battery percentages of <code>n</code> <strong>0-indexed</strong> devices.</p> <p>Your task is to test each device <code>i</code> <strong>in order</strong> from <code>0</code> to <code>n - 1</code>, by performing the following test operations:</p> <ul> <li>If <code>batteryPercentages[i]</code> is <strong>greater</strong> than <code>0</code>: <ul> <li><strong>Increment</strong> the count of tested devices.</li> <li><strong>Decrease</strong> the battery percentage of all devices with indices <code>j</code> in the range <code>[i + 1, n - 1]</code> by <code>1</code>, ensuring their battery percentage <strong>never goes below</strong> <code>0</code>, i.e, <code>batteryPercentages[j] = max(0, batteryPercentages[j] - 1)</code>.</li> <li>Move to the next device.</li> </ul> </li> <li>Otherwise, move to the next device without performing any test.</li> </ul> <p>Return <em>an integer denoting the number of devices that will be tested after performing the test operations in order.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> batteryPercentages = [1,1,2,1,3] <strong>Output:</strong> 3 <strong>Explanation: </strong>Performing the test operations in order starting from device 0: At device 0, batteryPercentages[0] &gt; 0, so there is now 1 tested device, and batteryPercentages becomes [1,0,1,0,2]. At device 1, batteryPercentages[1] == 0, so we move to the next device without testing. At device 2, batteryPercentages[2] &gt; 0, so there are now 2 tested devices, and batteryPercentages becomes [1,0,1,0,1]. At device 3, batteryPercentages[3] == 0, so we move to the next device without testing. At device 4, batteryPercentages[4] &gt; 0, so there are now 3 tested devices, and batteryPercentages stays the same. So, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> batteryPercentages = [0,1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> Performing the test operations in order starting from device 0: At device 0, batteryPercentages[0] == 0, so we move to the next device without testing. At device 1, batteryPercentages[1] &gt; 0, so there is now 1 tested device, and batteryPercentages becomes [0,1,1]. At device 2, batteryPercentages[2] &gt; 0, so there are now 2 tested devices, and batteryPercentages stays the same. So, the answer is 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == batteryPercentages.length &lt;= 100 </code></li> <li><code>0 &lt;= batteryPercentages[i] &lt;= 100</code></li> </ul>
Array; Counting; Simulation
Go
func countTestedDevices(batteryPercentages []int) (ans int) { for _, x := range batteryPercentages { if x > ans { ans++ } } return }
2,960
Count Tested Devices After Test Operations
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>batteryPercentages</code> having length <code>n</code>, denoting the battery percentages of <code>n</code> <strong>0-indexed</strong> devices.</p> <p>Your task is to test each device <code>i</code> <strong>in order</strong> from <code>0</code> to <code>n - 1</code>, by performing the following test operations:</p> <ul> <li>If <code>batteryPercentages[i]</code> is <strong>greater</strong> than <code>0</code>: <ul> <li><strong>Increment</strong> the count of tested devices.</li> <li><strong>Decrease</strong> the battery percentage of all devices with indices <code>j</code> in the range <code>[i + 1, n - 1]</code> by <code>1</code>, ensuring their battery percentage <strong>never goes below</strong> <code>0</code>, i.e, <code>batteryPercentages[j] = max(0, batteryPercentages[j] - 1)</code>.</li> <li>Move to the next device.</li> </ul> </li> <li>Otherwise, move to the next device without performing any test.</li> </ul> <p>Return <em>an integer denoting the number of devices that will be tested after performing the test operations in order.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> batteryPercentages = [1,1,2,1,3] <strong>Output:</strong> 3 <strong>Explanation: </strong>Performing the test operations in order starting from device 0: At device 0, batteryPercentages[0] &gt; 0, so there is now 1 tested device, and batteryPercentages becomes [1,0,1,0,2]. At device 1, batteryPercentages[1] == 0, so we move to the next device without testing. At device 2, batteryPercentages[2] &gt; 0, so there are now 2 tested devices, and batteryPercentages becomes [1,0,1,0,1]. At device 3, batteryPercentages[3] == 0, so we move to the next device without testing. At device 4, batteryPercentages[4] &gt; 0, so there are now 3 tested devices, and batteryPercentages stays the same. So, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> batteryPercentages = [0,1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> Performing the test operations in order starting from device 0: At device 0, batteryPercentages[0] == 0, so we move to the next device without testing. At device 1, batteryPercentages[1] &gt; 0, so there is now 1 tested device, and batteryPercentages becomes [0,1,1]. At device 2, batteryPercentages[2] &gt; 0, so there are now 2 tested devices, and batteryPercentages stays the same. So, the answer is 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == batteryPercentages.length &lt;= 100 </code></li> <li><code>0 &lt;= batteryPercentages[i] &lt;= 100</code></li> </ul>
Array; Counting; Simulation
Java
class Solution { public int countTestedDevices(int[] batteryPercentages) { int ans = 0; for (int x : batteryPercentages) { ans += x > ans ? 1 : 0; } return ans; } }
2,960
Count Tested Devices After Test Operations
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>batteryPercentages</code> having length <code>n</code>, denoting the battery percentages of <code>n</code> <strong>0-indexed</strong> devices.</p> <p>Your task is to test each device <code>i</code> <strong>in order</strong> from <code>0</code> to <code>n - 1</code>, by performing the following test operations:</p> <ul> <li>If <code>batteryPercentages[i]</code> is <strong>greater</strong> than <code>0</code>: <ul> <li><strong>Increment</strong> the count of tested devices.</li> <li><strong>Decrease</strong> the battery percentage of all devices with indices <code>j</code> in the range <code>[i + 1, n - 1]</code> by <code>1</code>, ensuring their battery percentage <strong>never goes below</strong> <code>0</code>, i.e, <code>batteryPercentages[j] = max(0, batteryPercentages[j] - 1)</code>.</li> <li>Move to the next device.</li> </ul> </li> <li>Otherwise, move to the next device without performing any test.</li> </ul> <p>Return <em>an integer denoting the number of devices that will be tested after performing the test operations in order.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> batteryPercentages = [1,1,2,1,3] <strong>Output:</strong> 3 <strong>Explanation: </strong>Performing the test operations in order starting from device 0: At device 0, batteryPercentages[0] &gt; 0, so there is now 1 tested device, and batteryPercentages becomes [1,0,1,0,2]. At device 1, batteryPercentages[1] == 0, so we move to the next device without testing. At device 2, batteryPercentages[2] &gt; 0, so there are now 2 tested devices, and batteryPercentages becomes [1,0,1,0,1]. At device 3, batteryPercentages[3] == 0, so we move to the next device without testing. At device 4, batteryPercentages[4] &gt; 0, so there are now 3 tested devices, and batteryPercentages stays the same. So, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> batteryPercentages = [0,1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> Performing the test operations in order starting from device 0: At device 0, batteryPercentages[0] == 0, so we move to the next device without testing. At device 1, batteryPercentages[1] &gt; 0, so there is now 1 tested device, and batteryPercentages becomes [0,1,1]. At device 2, batteryPercentages[2] &gt; 0, so there are now 2 tested devices, and batteryPercentages stays the same. So, the answer is 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == batteryPercentages.length &lt;= 100 </code></li> <li><code>0 &lt;= batteryPercentages[i] &lt;= 100</code></li> </ul>
Array; Counting; Simulation
Python
class Solution: def countTestedDevices(self, batteryPercentages: List[int]) -> int: ans = 0 for x in batteryPercentages: ans += x > ans return ans
2,960
Count Tested Devices After Test Operations
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>batteryPercentages</code> having length <code>n</code>, denoting the battery percentages of <code>n</code> <strong>0-indexed</strong> devices.</p> <p>Your task is to test each device <code>i</code> <strong>in order</strong> from <code>0</code> to <code>n - 1</code>, by performing the following test operations:</p> <ul> <li>If <code>batteryPercentages[i]</code> is <strong>greater</strong> than <code>0</code>: <ul> <li><strong>Increment</strong> the count of tested devices.</li> <li><strong>Decrease</strong> the battery percentage of all devices with indices <code>j</code> in the range <code>[i + 1, n - 1]</code> by <code>1</code>, ensuring their battery percentage <strong>never goes below</strong> <code>0</code>, i.e, <code>batteryPercentages[j] = max(0, batteryPercentages[j] - 1)</code>.</li> <li>Move to the next device.</li> </ul> </li> <li>Otherwise, move to the next device without performing any test.</li> </ul> <p>Return <em>an integer denoting the number of devices that will be tested after performing the test operations in order.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> batteryPercentages = [1,1,2,1,3] <strong>Output:</strong> 3 <strong>Explanation: </strong>Performing the test operations in order starting from device 0: At device 0, batteryPercentages[0] &gt; 0, so there is now 1 tested device, and batteryPercentages becomes [1,0,1,0,2]. At device 1, batteryPercentages[1] == 0, so we move to the next device without testing. At device 2, batteryPercentages[2] &gt; 0, so there are now 2 tested devices, and batteryPercentages becomes [1,0,1,0,1]. At device 3, batteryPercentages[3] == 0, so we move to the next device without testing. At device 4, batteryPercentages[4] &gt; 0, so there are now 3 tested devices, and batteryPercentages stays the same. So, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> batteryPercentages = [0,1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> Performing the test operations in order starting from device 0: At device 0, batteryPercentages[0] == 0, so we move to the next device without testing. At device 1, batteryPercentages[1] &gt; 0, so there is now 1 tested device, and batteryPercentages becomes [0,1,1]. At device 2, batteryPercentages[2] &gt; 0, so there are now 2 tested devices, and batteryPercentages stays the same. So, the answer is 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == batteryPercentages.length &lt;= 100 </code></li> <li><code>0 &lt;= batteryPercentages[i] &lt;= 100</code></li> </ul>
Array; Counting; Simulation
Rust
impl Solution { pub fn count_tested_devices(battery_percentages: Vec<i32>) -> i32 { let mut ans = 0; for x in battery_percentages { ans += if x > ans { 1 } else { 0 }; } ans } }
2,960
Count Tested Devices After Test Operations
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>batteryPercentages</code> having length <code>n</code>, denoting the battery percentages of <code>n</code> <strong>0-indexed</strong> devices.</p> <p>Your task is to test each device <code>i</code> <strong>in order</strong> from <code>0</code> to <code>n - 1</code>, by performing the following test operations:</p> <ul> <li>If <code>batteryPercentages[i]</code> is <strong>greater</strong> than <code>0</code>: <ul> <li><strong>Increment</strong> the count of tested devices.</li> <li><strong>Decrease</strong> the battery percentage of all devices with indices <code>j</code> in the range <code>[i + 1, n - 1]</code> by <code>1</code>, ensuring their battery percentage <strong>never goes below</strong> <code>0</code>, i.e, <code>batteryPercentages[j] = max(0, batteryPercentages[j] - 1)</code>.</li> <li>Move to the next device.</li> </ul> </li> <li>Otherwise, move to the next device without performing any test.</li> </ul> <p>Return <em>an integer denoting the number of devices that will be tested after performing the test operations in order.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> batteryPercentages = [1,1,2,1,3] <strong>Output:</strong> 3 <strong>Explanation: </strong>Performing the test operations in order starting from device 0: At device 0, batteryPercentages[0] &gt; 0, so there is now 1 tested device, and batteryPercentages becomes [1,0,1,0,2]. At device 1, batteryPercentages[1] == 0, so we move to the next device without testing. At device 2, batteryPercentages[2] &gt; 0, so there are now 2 tested devices, and batteryPercentages becomes [1,0,1,0,1]. At device 3, batteryPercentages[3] == 0, so we move to the next device without testing. At device 4, batteryPercentages[4] &gt; 0, so there are now 3 tested devices, and batteryPercentages stays the same. So, the answer is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> batteryPercentages = [0,1,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> Performing the test operations in order starting from device 0: At device 0, batteryPercentages[0] == 0, so we move to the next device without testing. At device 1, batteryPercentages[1] &gt; 0, so there is now 1 tested device, and batteryPercentages becomes [0,1,1]. At device 2, batteryPercentages[2] &gt; 0, so there are now 2 tested devices, and batteryPercentages stays the same. So, the answer is 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == batteryPercentages.length &lt;= 100 </code></li> <li><code>0 &lt;= batteryPercentages[i] &lt;= 100</code></li> </ul>
Array; Counting; Simulation
TypeScript
function countTestedDevices(batteryPercentages: number[]): number { let ans = 0; for (const x of batteryPercentages) { ans += x > ans ? 1 : 0; } return ans; }
2,961
Double Modular Exponentiation
Medium
<p>You are given a <strong>0-indexed</strong> 2D array <code>variables</code> where <code>variables[i] = [a<sub>i</sub>, b<sub>i</sub>, c<sub>i,</sub> m<sub>i</sub>]</code>, and an integer <code>target</code>.</p> <p>An index <code>i</code> is <strong>good</strong> if the following formula holds:</p> <ul> <li><code>0 &lt;= i &lt; variables.length</code></li> <li><code>((a<sub>i</sub><sup>b<sub>i</sub></sup> % 10)<sup>c<sub>i</sub></sup>) % m<sub>i</sub> == target</code></li> </ul> <p>Return <em>an array consisting of <strong>good</strong> indices in <strong>any order</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> variables = [[2,3,3,10],[3,3,3,1],[6,1,1,4]], target = 2 <strong>Output:</strong> [0,2] <strong>Explanation:</strong> For each index i in the variables array: 1) For the index 0, variables[0] = [2,3,3,10], (2<sup>3</sup> % 10)<sup>3</sup> % 10 = 2. 2) For the index 1, variables[1] = [3,3,3,1], (3<sup>3</sup> % 10)<sup>3</sup> % 1 = 0. 3) For the index 2, variables[2] = [6,1,1,4], (6<sup>1</sup> % 10)<sup>1</sup> % 4 = 2. Therefore we return [0,2] as the answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> variables = [[39,3,1000,1000]], target = 17 <strong>Output:</strong> [] <strong>Explanation:</strong> For each index i in the variables array: 1) For the index 0, variables[0] = [39,3,1000,1000], (39<sup>3</sup> % 10)<sup>1000</sup> % 1000 = 1. Therefore we return [] as the answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= variables.length &lt;= 100</code></li> <li><code>variables[i] == [a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, m<sub>i</sub>]</code></li> <li><code>1 &lt;= a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, m<sub>i</sub> &lt;= 10<sup>3</sup></code></li> <li><code><font face="monospace">0 &lt;= target &lt;= 10<sup>3</sup></font></code></li> </ul>
Array; Math; Simulation
C++
class Solution { public: vector<int> getGoodIndices(vector<vector<int>>& variables, int target) { vector<int> ans; auto qpow = [&](long long a, int n, int mod) { long long ans = 1; for (; n; n >>= 1) { if (n & 1) { ans = ans * a % mod; } a = a * a % mod; } return (int) ans; }; for (int i = 0; i < variables.size(); ++i) { auto e = variables[i]; int a = e[0], b = e[1], c = e[2], m = e[3]; if (qpow(qpow(a, b, 10), c, m) == target) { ans.push_back(i); } } return ans; } };
2,961
Double Modular Exponentiation
Medium
<p>You are given a <strong>0-indexed</strong> 2D array <code>variables</code> where <code>variables[i] = [a<sub>i</sub>, b<sub>i</sub>, c<sub>i,</sub> m<sub>i</sub>]</code>, and an integer <code>target</code>.</p> <p>An index <code>i</code> is <strong>good</strong> if the following formula holds:</p> <ul> <li><code>0 &lt;= i &lt; variables.length</code></li> <li><code>((a<sub>i</sub><sup>b<sub>i</sub></sup> % 10)<sup>c<sub>i</sub></sup>) % m<sub>i</sub> == target</code></li> </ul> <p>Return <em>an array consisting of <strong>good</strong> indices in <strong>any order</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> variables = [[2,3,3,10],[3,3,3,1],[6,1,1,4]], target = 2 <strong>Output:</strong> [0,2] <strong>Explanation:</strong> For each index i in the variables array: 1) For the index 0, variables[0] = [2,3,3,10], (2<sup>3</sup> % 10)<sup>3</sup> % 10 = 2. 2) For the index 1, variables[1] = [3,3,3,1], (3<sup>3</sup> % 10)<sup>3</sup> % 1 = 0. 3) For the index 2, variables[2] = [6,1,1,4], (6<sup>1</sup> % 10)<sup>1</sup> % 4 = 2. Therefore we return [0,2] as the answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> variables = [[39,3,1000,1000]], target = 17 <strong>Output:</strong> [] <strong>Explanation:</strong> For each index i in the variables array: 1) For the index 0, variables[0] = [39,3,1000,1000], (39<sup>3</sup> % 10)<sup>1000</sup> % 1000 = 1. Therefore we return [] as the answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= variables.length &lt;= 100</code></li> <li><code>variables[i] == [a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, m<sub>i</sub>]</code></li> <li><code>1 &lt;= a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, m<sub>i</sub> &lt;= 10<sup>3</sup></code></li> <li><code><font face="monospace">0 &lt;= target &lt;= 10<sup>3</sup></font></code></li> </ul>
Array; Math; Simulation
Go
func getGoodIndices(variables [][]int, target int) (ans []int) { qpow := func(a, n, mod int) int { ans := 1 for ; n > 0; n >>= 1 { if n&1 == 1 { ans = ans * a % mod } a = a * a % mod } return ans } for i, e := range variables { a, b, c, m := e[0], e[1], e[2], e[3] if qpow(qpow(a, b, 10), c, m) == target { ans = append(ans, i) } } return }
2,961
Double Modular Exponentiation
Medium
<p>You are given a <strong>0-indexed</strong> 2D array <code>variables</code> where <code>variables[i] = [a<sub>i</sub>, b<sub>i</sub>, c<sub>i,</sub> m<sub>i</sub>]</code>, and an integer <code>target</code>.</p> <p>An index <code>i</code> is <strong>good</strong> if the following formula holds:</p> <ul> <li><code>0 &lt;= i &lt; variables.length</code></li> <li><code>((a<sub>i</sub><sup>b<sub>i</sub></sup> % 10)<sup>c<sub>i</sub></sup>) % m<sub>i</sub> == target</code></li> </ul> <p>Return <em>an array consisting of <strong>good</strong> indices in <strong>any order</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> variables = [[2,3,3,10],[3,3,3,1],[6,1,1,4]], target = 2 <strong>Output:</strong> [0,2] <strong>Explanation:</strong> For each index i in the variables array: 1) For the index 0, variables[0] = [2,3,3,10], (2<sup>3</sup> % 10)<sup>3</sup> % 10 = 2. 2) For the index 1, variables[1] = [3,3,3,1], (3<sup>3</sup> % 10)<sup>3</sup> % 1 = 0. 3) For the index 2, variables[2] = [6,1,1,4], (6<sup>1</sup> % 10)<sup>1</sup> % 4 = 2. Therefore we return [0,2] as the answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> variables = [[39,3,1000,1000]], target = 17 <strong>Output:</strong> [] <strong>Explanation:</strong> For each index i in the variables array: 1) For the index 0, variables[0] = [39,3,1000,1000], (39<sup>3</sup> % 10)<sup>1000</sup> % 1000 = 1. Therefore we return [] as the answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= variables.length &lt;= 100</code></li> <li><code>variables[i] == [a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, m<sub>i</sub>]</code></li> <li><code>1 &lt;= a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, m<sub>i</sub> &lt;= 10<sup>3</sup></code></li> <li><code><font face="monospace">0 &lt;= target &lt;= 10<sup>3</sup></font></code></li> </ul>
Array; Math; Simulation
Java
class Solution { public List<Integer> getGoodIndices(int[][] variables, int target) { List<Integer> ans = new ArrayList<>(); for (int i = 0; i < variables.length; ++i) { var e = variables[i]; int a = e[0], b = e[1], c = e[2], m = e[3]; if (qpow(qpow(a, b, 10), c, m) == target) { ans.add(i); } } return ans; } private int qpow(long a, int n, int mod) { long ans = 1; for (; n > 0; n >>= 1) { if ((n & 1) == 1) { ans = ans * a % mod; } a = a * a % mod; } return (int) ans; } }
2,961
Double Modular Exponentiation
Medium
<p>You are given a <strong>0-indexed</strong> 2D array <code>variables</code> where <code>variables[i] = [a<sub>i</sub>, b<sub>i</sub>, c<sub>i,</sub> m<sub>i</sub>]</code>, and an integer <code>target</code>.</p> <p>An index <code>i</code> is <strong>good</strong> if the following formula holds:</p> <ul> <li><code>0 &lt;= i &lt; variables.length</code></li> <li><code>((a<sub>i</sub><sup>b<sub>i</sub></sup> % 10)<sup>c<sub>i</sub></sup>) % m<sub>i</sub> == target</code></li> </ul> <p>Return <em>an array consisting of <strong>good</strong> indices in <strong>any order</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> variables = [[2,3,3,10],[3,3,3,1],[6,1,1,4]], target = 2 <strong>Output:</strong> [0,2] <strong>Explanation:</strong> For each index i in the variables array: 1) For the index 0, variables[0] = [2,3,3,10], (2<sup>3</sup> % 10)<sup>3</sup> % 10 = 2. 2) For the index 1, variables[1] = [3,3,3,1], (3<sup>3</sup> % 10)<sup>3</sup> % 1 = 0. 3) For the index 2, variables[2] = [6,1,1,4], (6<sup>1</sup> % 10)<sup>1</sup> % 4 = 2. Therefore we return [0,2] as the answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> variables = [[39,3,1000,1000]], target = 17 <strong>Output:</strong> [] <strong>Explanation:</strong> For each index i in the variables array: 1) For the index 0, variables[0] = [39,3,1000,1000], (39<sup>3</sup> % 10)<sup>1000</sup> % 1000 = 1. Therefore we return [] as the answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= variables.length &lt;= 100</code></li> <li><code>variables[i] == [a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, m<sub>i</sub>]</code></li> <li><code>1 &lt;= a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, m<sub>i</sub> &lt;= 10<sup>3</sup></code></li> <li><code><font face="monospace">0 &lt;= target &lt;= 10<sup>3</sup></font></code></li> </ul>
Array; Math; Simulation
Python
class Solution: def getGoodIndices(self, variables: List[List[int]], target: int) -> List[int]: return [ i for i, (a, b, c, m) in enumerate(variables) if pow(pow(a, b, 10), c, m) == target ]
2,961
Double Modular Exponentiation
Medium
<p>You are given a <strong>0-indexed</strong> 2D array <code>variables</code> where <code>variables[i] = [a<sub>i</sub>, b<sub>i</sub>, c<sub>i,</sub> m<sub>i</sub>]</code>, and an integer <code>target</code>.</p> <p>An index <code>i</code> is <strong>good</strong> if the following formula holds:</p> <ul> <li><code>0 &lt;= i &lt; variables.length</code></li> <li><code>((a<sub>i</sub><sup>b<sub>i</sub></sup> % 10)<sup>c<sub>i</sub></sup>) % m<sub>i</sub> == target</code></li> </ul> <p>Return <em>an array consisting of <strong>good</strong> indices in <strong>any order</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> variables = [[2,3,3,10],[3,3,3,1],[6,1,1,4]], target = 2 <strong>Output:</strong> [0,2] <strong>Explanation:</strong> For each index i in the variables array: 1) For the index 0, variables[0] = [2,3,3,10], (2<sup>3</sup> % 10)<sup>3</sup> % 10 = 2. 2) For the index 1, variables[1] = [3,3,3,1], (3<sup>3</sup> % 10)<sup>3</sup> % 1 = 0. 3) For the index 2, variables[2] = [6,1,1,4], (6<sup>1</sup> % 10)<sup>1</sup> % 4 = 2. Therefore we return [0,2] as the answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> variables = [[39,3,1000,1000]], target = 17 <strong>Output:</strong> [] <strong>Explanation:</strong> For each index i in the variables array: 1) For the index 0, variables[0] = [39,3,1000,1000], (39<sup>3</sup> % 10)<sup>1000</sup> % 1000 = 1. Therefore we return [] as the answer. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= variables.length &lt;= 100</code></li> <li><code>variables[i] == [a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, m<sub>i</sub>]</code></li> <li><code>1 &lt;= a<sub>i</sub>, b<sub>i</sub>, c<sub>i</sub>, m<sub>i</sub> &lt;= 10<sup>3</sup></code></li> <li><code><font face="monospace">0 &lt;= target &lt;= 10<sup>3</sup></font></code></li> </ul>
Array; Math; Simulation
TypeScript
function getGoodIndices(variables: number[][], target: number): number[] { const qpow = (a: number, n: number, mod: number) => { let ans = 1; for (; n; n >>= 1) { if (n & 1) { ans = Number((BigInt(ans) * BigInt(a)) % BigInt(mod)); } a = Number((BigInt(a) * BigInt(a)) % BigInt(mod)); } return ans; }; const ans: number[] = []; for (let i = 0; i < variables.length; ++i) { const [a, b, c, m] = variables[i]; if (qpow(qpow(a, b, 10), c, m) === target) { ans.push(i); } } return ans; }
2,962
Count Subarrays Where Max Element Appears at Least K Times
Medium
<p>You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>Return <em>the number of subarrays where the <strong>maximum</strong> element of </em><code>nums</code><em> appears <strong>at least</strong> </em><code>k</code><em> times in that subarray.</em></p> <p>A <strong>subarray</strong> is a contiguous sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,3,3], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,2,1], k = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> No subarray contains the element 4 at least 3 times. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Sliding Window
C++
class Solution { public: long long countSubarrays(vector<int>& nums, int k) { int mx = *max_element(nums.begin(), nums.end()); int n = nums.size(); long long ans = 0; int cnt = 0, j = 0; for (int x : nums) { while (j < n && cnt < k) { cnt += nums[j++] == mx; } if (cnt < k) { break; } ans += n - j + 1; cnt -= x == mx; } return ans; } };
2,962
Count Subarrays Where Max Element Appears at Least K Times
Medium
<p>You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>Return <em>the number of subarrays where the <strong>maximum</strong> element of </em><code>nums</code><em> appears <strong>at least</strong> </em><code>k</code><em> times in that subarray.</em></p> <p>A <strong>subarray</strong> is a contiguous sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,3,3], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,2,1], k = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> No subarray contains the element 4 at least 3 times. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Sliding Window
Go
func countSubarrays(nums []int, k int) (ans int64) { mx := slices.Max(nums) n := len(nums) cnt, j := 0, 0 for _, x := range nums { for ; j < n && cnt < k; j++ { if nums[j] == mx { cnt++ } } if cnt < k { break } ans += int64(n - j + 1) if x == mx { cnt-- } } return }
2,962
Count Subarrays Where Max Element Appears at Least K Times
Medium
<p>You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>Return <em>the number of subarrays where the <strong>maximum</strong> element of </em><code>nums</code><em> appears <strong>at least</strong> </em><code>k</code><em> times in that subarray.</em></p> <p>A <strong>subarray</strong> is a contiguous sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,3,3], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,2,1], k = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> No subarray contains the element 4 at least 3 times. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Sliding Window
Java
class Solution { public long countSubarrays(int[] nums, int k) { int mx = Arrays.stream(nums).max().getAsInt(); int n = nums.length; long ans = 0; int cnt = 0, j = 0; for (int x : nums) { while (j < n && cnt < k) { cnt += nums[j++] == mx ? 1 : 0; } if (cnt < k) { break; } ans += n - j + 1; cnt -= x == mx ? 1 : 0; } return ans; } }
2,962
Count Subarrays Where Max Element Appears at Least K Times
Medium
<p>You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</code>.</p> <p>Return <em>the number of subarrays where the <strong>maximum</strong> element of </em><code>nums</code><em> appears <strong>at least</strong> </em><code>k</code><em> times in that subarray.</em></p> <p>A <strong>subarray</strong> is a contiguous sequence of elements within an array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,2,3,3], k = 2 <strong>Output:</strong> 6 <strong>Explanation:</strong> The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,4,2,1], k = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> No subarray contains the element 4 at least 3 times. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Sliding Window
Python
class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: mx = max(nums) n = len(nums) ans = cnt = j = 0 for x in nums: while j < n and cnt < k: cnt += nums[j] == mx j += 1 if cnt < k: break ans += n - j + 1 cnt -= x == mx return ans