id
int64
1
3.65k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
3,091
Apply Operations to Make Sum of Array Greater Than or Equal to k
Medium
<p>You are given a <strong>positive</strong> integer <code>k</code>. Initially, you have an array <code>nums = [1]</code>.</p> <p>You can perform <strong>any</strong> of the following operations on the array <strong>any</strong> number of times (<strong>possibly zero</strong>):</p> <ul> <li>Choose any element in the array and <strong>increase</strong> its value by <code>1</code>.</li> <li>Duplicate any element in the array and add it to the end of the array.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations required to make the <strong>sum</strong> of elements of the final array greater than or equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">k = 11</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can do the following operations on the array <code>nums = [1]</code>:</p> <ul> <li>Increase the element by <code>1</code> three times. The resulting array is <code>nums = [4]</code>.</li> <li>Duplicate the element two times. The resulting array is <code>nums = [4,4,4]</code>.</li> </ul> <p>The sum of the final array is <code>4 + 4 + 4 = 12</code> which is greater than or equal to <code>k = 11</code>.<br /> The total number of operations performed is <code>3 + 2 = 5</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The sum of the original array is already greater than or equal to <code>1</code>, so no operations are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Math; Enumeration
Java
class Solution { public int minOperations(int k) { int ans = k; for (int a = 0; a < k; ++a) { int x = a + 1; int b = (k + x - 1) / x - 1; ans = Math.min(ans, a + b); } return ans; } }
3,091
Apply Operations to Make Sum of Array Greater Than or Equal to k
Medium
<p>You are given a <strong>positive</strong> integer <code>k</code>. Initially, you have an array <code>nums = [1]</code>.</p> <p>You can perform <strong>any</strong> of the following operations on the array <strong>any</strong> number of times (<strong>possibly zero</strong>):</p> <ul> <li>Choose any element in the array and <strong>increase</strong> its value by <code>1</code>.</li> <li>Duplicate any element in the array and add it to the end of the array.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations required to make the <strong>sum</strong> of elements of the final array greater than or equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">k = 11</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can do the following operations on the array <code>nums = [1]</code>:</p> <ul> <li>Increase the element by <code>1</code> three times. The resulting array is <code>nums = [4]</code>.</li> <li>Duplicate the element two times. The resulting array is <code>nums = [4,4,4]</code>.</li> </ul> <p>The sum of the final array is <code>4 + 4 + 4 = 12</code> which is greater than or equal to <code>k = 11</code>.<br /> The total number of operations performed is <code>3 + 2 = 5</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The sum of the original array is already greater than or equal to <code>1</code>, so no operations are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Math; Enumeration
Python
class Solution: def minOperations(self, k: int) -> int: ans = k for a in range(k): x = a + 1 b = (k + x - 1) // x - 1 ans = min(ans, a + b) return ans
3,091
Apply Operations to Make Sum of Array Greater Than or Equal to k
Medium
<p>You are given a <strong>positive</strong> integer <code>k</code>. Initially, you have an array <code>nums = [1]</code>.</p> <p>You can perform <strong>any</strong> of the following operations on the array <strong>any</strong> number of times (<strong>possibly zero</strong>):</p> <ul> <li>Choose any element in the array and <strong>increase</strong> its value by <code>1</code>.</li> <li>Duplicate any element in the array and add it to the end of the array.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations required to make the <strong>sum</strong> of elements of the final array greater than or equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">k = 11</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can do the following operations on the array <code>nums = [1]</code>:</p> <ul> <li>Increase the element by <code>1</code> three times. The resulting array is <code>nums = [4]</code>.</li> <li>Duplicate the element two times. The resulting array is <code>nums = [4,4,4]</code>.</li> </ul> <p>The sum of the final array is <code>4 + 4 + 4 = 12</code> which is greater than or equal to <code>k = 11</code>.<br /> The total number of operations performed is <code>3 + 2 = 5</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The sum of the original array is already greater than or equal to <code>1</code>, so no operations are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Math; Enumeration
Rust
impl Solution { pub fn min_operations(k: i32) -> i32 { let mut ans = k; for a in 0..k { let x = a + 1; let b = (k + x - 1) / x - 1; ans = ans.min(a + b); } ans } }
3,091
Apply Operations to Make Sum of Array Greater Than or Equal to k
Medium
<p>You are given a <strong>positive</strong> integer <code>k</code>. Initially, you have an array <code>nums = [1]</code>.</p> <p>You can perform <strong>any</strong> of the following operations on the array <strong>any</strong> number of times (<strong>possibly zero</strong>):</p> <ul> <li>Choose any element in the array and <strong>increase</strong> its value by <code>1</code>.</li> <li>Duplicate any element in the array and add it to the end of the array.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations required to make the <strong>sum</strong> of elements of the final array greater than or equal to </em><code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">k = 11</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>We can do the following operations on the array <code>nums = [1]</code>:</p> <ul> <li>Increase the element by <code>1</code> three times. The resulting array is <code>nums = [4]</code>.</li> <li>Duplicate the element two times. The resulting array is <code>nums = [4,4,4]</code>.</li> </ul> <p>The sum of the final array is <code>4 + 4 + 4 = 12</code> which is greater than or equal to <code>k = 11</code>.<br /> The total number of operations performed is <code>3 + 2 = 5</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The sum of the original array is already greater than or equal to <code>1</code>, so no operations are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Greedy; Math; Enumeration
TypeScript
function minOperations(k: number): number { let ans = k; for (let a = 0; a < k; ++a) { const x = a + 1; const b = Math.ceil(k / x) - 1; ans = Math.min(ans, a + b); } return ans; }
3,092
Most Frequent IDs
Medium
<p>The problem involves tracking the frequency of IDs in a collection that changes over time. You have two integer arrays, <code>nums</code> and <code>freq</code>, of equal length <code>n</code>. Each element in <code>nums</code> represents an ID, and the corresponding element in <code>freq</code> indicates how many times that ID should be added to or removed from the collection at each step.</p> <ul> <li><strong>Addition of IDs:</strong> If <code>freq[i]</code> is positive, it means <code>freq[i]</code> IDs with the value <code>nums[i]</code> are added to the collection at step <code>i</code>.</li> <li><strong>Removal of IDs:</strong> If <code>freq[i]</code> is negative, it means <code>-freq[i]</code> IDs with the value <code>nums[i]</code> are removed from the collection at step <code>i</code>.</li> </ul> <p>Return an array <code>ans</code> of length <code>n</code>, where <code>ans[i]</code> represents the <strong>count</strong> of the <em>most frequent ID</em> in the collection after the <code>i<sup>th</sup></code>&nbsp;step. If the collection is empty at any step, <code>ans[i]</code> should be 0 for that step.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,2,1], freq = [3,2,-3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,3,2,2]</span></p> <p><strong>Explanation:</strong></p> <p>After step 0, we have 3 IDs with the value of 2. So <code>ans[0] = 3</code>.<br /> After step 1, we have 3 IDs with the value of 2 and 2 IDs with the value of 3. So <code>ans[1] = 3</code>.<br /> After step 2, we have 2 IDs with the value of 3. So <code>ans[2] = 2</code>.<br /> After step 3, we have 2 IDs with the value of 3 and 1 ID with the value of 1. So <code>ans[3] = 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,5,3], freq = [2,-2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,0,1]</span></p> <p><strong>Explanation:</strong></p> <p>After step 0, we have 2 IDs with the value of 5. So <code>ans[0] = 2</code>.<br /> After step 1, there are no IDs. So <code>ans[1] = 0</code>.<br /> After step 2, we have 1 ID with the value of 3. So <code>ans[2] = 1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length == freq.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= freq[i] &lt;= 10<sup>5</sup></code></li> <li><code>freq[i] != 0</code></li> <li>The input is generated<!-- notionvc: a136b55a-f319-4fa6-9247-11be9f3b1db8 --> such that the occurrences of an ID will not be negative in any step.</li> </ul>
Array; Hash Table; Ordered Set; Heap (Priority Queue)
C++
class Solution { public: vector<long long> mostFrequentIDs(vector<int>& nums, vector<int>& freq) { unordered_map<int, long long> cnt; unordered_map<long long, int> lazy; int n = nums.size(); vector<long long> ans(n); priority_queue<long long> pq; for (int i = 0; i < n; ++i) { int x = nums[i], f = freq[i]; lazy[cnt[x]]++; cnt[x] += f; pq.push(cnt[x]); while (!pq.empty() && lazy[pq.top()] > 0) { lazy[pq.top()]--; pq.pop(); } ans[i] = pq.empty() ? 0 : pq.top(); } return ans; } };
3,092
Most Frequent IDs
Medium
<p>The problem involves tracking the frequency of IDs in a collection that changes over time. You have two integer arrays, <code>nums</code> and <code>freq</code>, of equal length <code>n</code>. Each element in <code>nums</code> represents an ID, and the corresponding element in <code>freq</code> indicates how many times that ID should be added to or removed from the collection at each step.</p> <ul> <li><strong>Addition of IDs:</strong> If <code>freq[i]</code> is positive, it means <code>freq[i]</code> IDs with the value <code>nums[i]</code> are added to the collection at step <code>i</code>.</li> <li><strong>Removal of IDs:</strong> If <code>freq[i]</code> is negative, it means <code>-freq[i]</code> IDs with the value <code>nums[i]</code> are removed from the collection at step <code>i</code>.</li> </ul> <p>Return an array <code>ans</code> of length <code>n</code>, where <code>ans[i]</code> represents the <strong>count</strong> of the <em>most frequent ID</em> in the collection after the <code>i<sup>th</sup></code>&nbsp;step. If the collection is empty at any step, <code>ans[i]</code> should be 0 for that step.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,2,1], freq = [3,2,-3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,3,2,2]</span></p> <p><strong>Explanation:</strong></p> <p>After step 0, we have 3 IDs with the value of 2. So <code>ans[0] = 3</code>.<br /> After step 1, we have 3 IDs with the value of 2 and 2 IDs with the value of 3. So <code>ans[1] = 3</code>.<br /> After step 2, we have 2 IDs with the value of 3. So <code>ans[2] = 2</code>.<br /> After step 3, we have 2 IDs with the value of 3 and 1 ID with the value of 1. So <code>ans[3] = 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,5,3], freq = [2,-2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,0,1]</span></p> <p><strong>Explanation:</strong></p> <p>After step 0, we have 2 IDs with the value of 5. So <code>ans[0] = 2</code>.<br /> After step 1, there are no IDs. So <code>ans[1] = 0</code>.<br /> After step 2, we have 1 ID with the value of 3. So <code>ans[2] = 1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length == freq.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= freq[i] &lt;= 10<sup>5</sup></code></li> <li><code>freq[i] != 0</code></li> <li>The input is generated<!-- notionvc: a136b55a-f319-4fa6-9247-11be9f3b1db8 --> such that the occurrences of an ID will not be negative in any step.</li> </ul>
Array; Hash Table; Ordered Set; Heap (Priority Queue)
Go
func mostFrequentIDs(nums []int, freq []int) []int64 { n := len(nums) cnt := map[int]int{} lazy := map[int]int{} ans := make([]int64, n) pq := hp{} heap.Init(&pq) for i, x := range nums { f := freq[i] lazy[cnt[x]]++ cnt[x] += f heap.Push(&pq, cnt[x]) for pq.Len() > 0 && lazy[pq.IntSlice[0]] > 0 { lazy[pq.IntSlice[0]]-- heap.Pop(&pq) } if pq.Len() > 0 { ans[i] = int64(pq.IntSlice[0]) } } return ans } type hp struct{ sort.IntSlice } func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } func (h *hp) Pop() any { a := h.IntSlice v := a[len(a)-1] h.IntSlice = a[:len(a)-1] return v }
3,092
Most Frequent IDs
Medium
<p>The problem involves tracking the frequency of IDs in a collection that changes over time. You have two integer arrays, <code>nums</code> and <code>freq</code>, of equal length <code>n</code>. Each element in <code>nums</code> represents an ID, and the corresponding element in <code>freq</code> indicates how many times that ID should be added to or removed from the collection at each step.</p> <ul> <li><strong>Addition of IDs:</strong> If <code>freq[i]</code> is positive, it means <code>freq[i]</code> IDs with the value <code>nums[i]</code> are added to the collection at step <code>i</code>.</li> <li><strong>Removal of IDs:</strong> If <code>freq[i]</code> is negative, it means <code>-freq[i]</code> IDs with the value <code>nums[i]</code> are removed from the collection at step <code>i</code>.</li> </ul> <p>Return an array <code>ans</code> of length <code>n</code>, where <code>ans[i]</code> represents the <strong>count</strong> of the <em>most frequent ID</em> in the collection after the <code>i<sup>th</sup></code>&nbsp;step. If the collection is empty at any step, <code>ans[i]</code> should be 0 for that step.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,2,1], freq = [3,2,-3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,3,2,2]</span></p> <p><strong>Explanation:</strong></p> <p>After step 0, we have 3 IDs with the value of 2. So <code>ans[0] = 3</code>.<br /> After step 1, we have 3 IDs with the value of 2 and 2 IDs with the value of 3. So <code>ans[1] = 3</code>.<br /> After step 2, we have 2 IDs with the value of 3. So <code>ans[2] = 2</code>.<br /> After step 3, we have 2 IDs with the value of 3 and 1 ID with the value of 1. So <code>ans[3] = 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,5,3], freq = [2,-2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,0,1]</span></p> <p><strong>Explanation:</strong></p> <p>After step 0, we have 2 IDs with the value of 5. So <code>ans[0] = 2</code>.<br /> After step 1, there are no IDs. So <code>ans[1] = 0</code>.<br /> After step 2, we have 1 ID with the value of 3. So <code>ans[2] = 1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length == freq.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= freq[i] &lt;= 10<sup>5</sup></code></li> <li><code>freq[i] != 0</code></li> <li>The input is generated<!-- notionvc: a136b55a-f319-4fa6-9247-11be9f3b1db8 --> such that the occurrences of an ID will not be negative in any step.</li> </ul>
Array; Hash Table; Ordered Set; Heap (Priority Queue)
Java
class Solution { public long[] mostFrequentIDs(int[] nums, int[] freq) { Map<Integer, Long> cnt = new HashMap<>(); Map<Long, Integer> lazy = new HashMap<>(); int n = nums.length; long[] ans = new long[n]; PriorityQueue<Long> pq = new PriorityQueue<>(Collections.reverseOrder()); for (int i = 0; i < n; ++i) { int x = nums[i], f = freq[i]; lazy.merge(cnt.getOrDefault(x, 0L), 1, Integer::sum); cnt.merge(x, (long) f, Long::sum); pq.add(cnt.get(x)); while (!pq.isEmpty() && lazy.getOrDefault(pq.peek(), 0) > 0) { lazy.merge(pq.poll(), -1, Integer::sum); } ans[i] = pq.isEmpty() ? 0 : pq.peek(); } return ans; } }
3,092
Most Frequent IDs
Medium
<p>The problem involves tracking the frequency of IDs in a collection that changes over time. You have two integer arrays, <code>nums</code> and <code>freq</code>, of equal length <code>n</code>. Each element in <code>nums</code> represents an ID, and the corresponding element in <code>freq</code> indicates how many times that ID should be added to or removed from the collection at each step.</p> <ul> <li><strong>Addition of IDs:</strong> If <code>freq[i]</code> is positive, it means <code>freq[i]</code> IDs with the value <code>nums[i]</code> are added to the collection at step <code>i</code>.</li> <li><strong>Removal of IDs:</strong> If <code>freq[i]</code> is negative, it means <code>-freq[i]</code> IDs with the value <code>nums[i]</code> are removed from the collection at step <code>i</code>.</li> </ul> <p>Return an array <code>ans</code> of length <code>n</code>, where <code>ans[i]</code> represents the <strong>count</strong> of the <em>most frequent ID</em> in the collection after the <code>i<sup>th</sup></code>&nbsp;step. If the collection is empty at any step, <code>ans[i]</code> should be 0 for that step.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,3,2,1], freq = [3,2,-3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[3,3,2,2]</span></p> <p><strong>Explanation:</strong></p> <p>After step 0, we have 3 IDs with the value of 2. So <code>ans[0] = 3</code>.<br /> After step 1, we have 3 IDs with the value of 2 and 2 IDs with the value of 3. So <code>ans[1] = 3</code>.<br /> After step 2, we have 2 IDs with the value of 3. So <code>ans[2] = 2</code>.<br /> After step 3, we have 2 IDs with the value of 3 and 1 ID with the value of 1. So <code>ans[3] = 2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,5,3], freq = [2,-2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,0,1]</span></p> <p><strong>Explanation:</strong></p> <p>After step 0, we have 2 IDs with the value of 5. So <code>ans[0] = 2</code>.<br /> After step 1, there are no IDs. So <code>ans[1] = 0</code>.<br /> After step 2, we have 1 ID with the value of 3. So <code>ans[2] = 1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length == freq.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= freq[i] &lt;= 10<sup>5</sup></code></li> <li><code>freq[i] != 0</code></li> <li>The input is generated<!-- notionvc: a136b55a-f319-4fa6-9247-11be9f3b1db8 --> such that the occurrences of an ID will not be negative in any step.</li> </ul>
Array; Hash Table; Ordered Set; Heap (Priority Queue)
Python
class Solution: def mostFrequentIDs(self, nums: List[int], freq: List[int]) -> List[int]: cnt = Counter() lazy = Counter() ans = [] pq = [] for x, f in zip(nums, freq): lazy[cnt[x]] += 1 cnt[x] += f heappush(pq, -cnt[x]) while pq and lazy[-pq[0]] > 0: lazy[-pq[0]] -= 1 heappop(pq) ans.append(0 if not pq else -pq[0]) return ans
3,093
Longest Common Suffix Queries
Hard
<p>You are given two arrays of strings <code>wordsContainer</code> and <code>wordsQuery</code>.</p> <p>For each <code>wordsQuery[i]</code>, you need to find a string from <code>wordsContainer</code> that has the <strong>longest common suffix</strong> with <code>wordsQuery[i]</code>. If there are two or more strings in <code>wordsContainer</code> that share the longest common suffix, find the string that is the <strong>smallest</strong> in length. If there are two or more such strings that have the <strong>same</strong> smallest length, find the one that occurred <strong>earlier</strong> in <code>wordsContainer</code>.</p> <p>Return <em>an array of integers </em><code>ans</code><em>, where </em><code>ans[i]</code><em> is the index of the string in </em><code>wordsContainer</code><em> that has the <strong>longest common suffix</strong> with </em><code>wordsQuery[i]</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">wordsContainer = [&quot;abcd&quot;,&quot;bcd&quot;,&quot;xbcd&quot;], wordsQuery = [&quot;cd&quot;,&quot;bcd&quot;,&quot;xyz&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at each <code>wordsQuery[i]</code> separately:</p> <ul> <li>For <code>wordsQuery[0] = &quot;cd&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;cd&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> <li>For <code>wordsQuery[1] = &quot;bcd&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;bcd&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> <li>For <code>wordsQuery[2] = &quot;xyz&quot;</code>, there is no string from <code>wordsContainer</code> that shares a common suffix. Hence the longest common suffix is <code>&quot;&quot;</code>, that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">wordsContainer = [&quot;abcdefgh&quot;,&quot;poiuygh&quot;,&quot;ghghgh&quot;], wordsQuery = [&quot;gh&quot;,&quot;acbfgh&quot;,&quot;acbfegh&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,0,2]</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at each <code>wordsQuery[i]</code> separately:</p> <ul> <li>For <code>wordsQuery[0] = &quot;gh&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;gh&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li> <li>For <code>wordsQuery[1] = &quot;acbfgh&quot;</code>, only the string at index 0 shares the longest common suffix <code>&quot;fgh&quot;</code>. Hence it is the answer, even though the string at index 2 is shorter.</li> <li>For <code>wordsQuery[2] = &quot;acbfegh&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;gh&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsContainer.length, wordsQuery.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= wordsContainer[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>1 &lt;= wordsQuery[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>wordsContainer[i]</code> consists only of lowercase English letters.</li> <li><code>wordsQuery[i]</code> consists only of lowercase English letters.</li> <li>Sum of <code>wordsContainer[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li> <li>Sum of <code>wordsQuery[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li> </ul>
Trie; Array; String
C++
class Trie { private: const int inf = 1 << 30; Trie* children[26]; int length = inf; int idx = inf; public: Trie() { for (int i = 0; i < 26; ++i) { children[i] = nullptr; } } void insert(string w, int i) { Trie* node = this; if (node->length > w.length()) { node->length = w.length(); node->idx = i; } for (int k = w.length() - 1; k >= 0; --k) { int idx = w[k] - 'a'; if (node->children[idx] == nullptr) { node->children[idx] = new Trie(); } node = node->children[idx]; if (node->length > w.length()) { node->length = w.length(); node->idx = i; } } } int query(string w) { Trie* node = this; for (int k = w.length() - 1; k >= 0; --k) { int idx = w[k] - 'a'; if (node->children[idx] == nullptr) { break; } node = node->children[idx]; } return node->idx; } }; class Solution { public: vector<int> stringIndices(vector<string>& wordsContainer, vector<string>& wordsQuery) { Trie* trie = new Trie(); for (int i = 0; i < wordsContainer.size(); ++i) { trie->insert(wordsContainer[i], i); } int n = wordsQuery.size(); vector<int> ans(n); for (int i = 0; i < n; ++i) { ans[i] = trie->query(wordsQuery[i]); } return ans; } };
3,093
Longest Common Suffix Queries
Hard
<p>You are given two arrays of strings <code>wordsContainer</code> and <code>wordsQuery</code>.</p> <p>For each <code>wordsQuery[i]</code>, you need to find a string from <code>wordsContainer</code> that has the <strong>longest common suffix</strong> with <code>wordsQuery[i]</code>. If there are two or more strings in <code>wordsContainer</code> that share the longest common suffix, find the string that is the <strong>smallest</strong> in length. If there are two or more such strings that have the <strong>same</strong> smallest length, find the one that occurred <strong>earlier</strong> in <code>wordsContainer</code>.</p> <p>Return <em>an array of integers </em><code>ans</code><em>, where </em><code>ans[i]</code><em> is the index of the string in </em><code>wordsContainer</code><em> that has the <strong>longest common suffix</strong> with </em><code>wordsQuery[i]</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">wordsContainer = [&quot;abcd&quot;,&quot;bcd&quot;,&quot;xbcd&quot;], wordsQuery = [&quot;cd&quot;,&quot;bcd&quot;,&quot;xyz&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at each <code>wordsQuery[i]</code> separately:</p> <ul> <li>For <code>wordsQuery[0] = &quot;cd&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;cd&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> <li>For <code>wordsQuery[1] = &quot;bcd&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;bcd&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> <li>For <code>wordsQuery[2] = &quot;xyz&quot;</code>, there is no string from <code>wordsContainer</code> that shares a common suffix. Hence the longest common suffix is <code>&quot;&quot;</code>, that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">wordsContainer = [&quot;abcdefgh&quot;,&quot;poiuygh&quot;,&quot;ghghgh&quot;], wordsQuery = [&quot;gh&quot;,&quot;acbfgh&quot;,&quot;acbfegh&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,0,2]</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at each <code>wordsQuery[i]</code> separately:</p> <ul> <li>For <code>wordsQuery[0] = &quot;gh&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;gh&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li> <li>For <code>wordsQuery[1] = &quot;acbfgh&quot;</code>, only the string at index 0 shares the longest common suffix <code>&quot;fgh&quot;</code>. Hence it is the answer, even though the string at index 2 is shorter.</li> <li>For <code>wordsQuery[2] = &quot;acbfegh&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;gh&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsContainer.length, wordsQuery.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= wordsContainer[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>1 &lt;= wordsQuery[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>wordsContainer[i]</code> consists only of lowercase English letters.</li> <li><code>wordsQuery[i]</code> consists only of lowercase English letters.</li> <li>Sum of <code>wordsContainer[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li> <li>Sum of <code>wordsQuery[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li> </ul>
Trie; Array; String
Go
const inf = 1 << 30 type Trie struct { children [26]*Trie length int idx int } func newTrie() *Trie { return &Trie{length: inf, idx: inf} } func (t *Trie) insert(w string, i int) { node := t if node.length > len(w) { node.length = len(w) node.idx = i } for k := len(w) - 1; k >= 0; k-- { idx := int(w[k] - 'a') if node.children[idx] == nil { node.children[idx] = newTrie() } node = node.children[idx] if node.length > len(w) { node.length = len(w) node.idx = i } } } func (t *Trie) query(w string) int { node := t for k := len(w) - 1; k >= 0; k-- { idx := int(w[k] - 'a') if node.children[idx] == nil { break } node = node.children[idx] } return node.idx } func stringIndices(wordsContainer []string, wordsQuery []string) (ans []int) { trie := newTrie() for i, w := range wordsContainer { trie.insert(w, i) } for _, w := range wordsQuery { ans = append(ans, trie.query(w)) } return }
3,093
Longest Common Suffix Queries
Hard
<p>You are given two arrays of strings <code>wordsContainer</code> and <code>wordsQuery</code>.</p> <p>For each <code>wordsQuery[i]</code>, you need to find a string from <code>wordsContainer</code> that has the <strong>longest common suffix</strong> with <code>wordsQuery[i]</code>. If there are two or more strings in <code>wordsContainer</code> that share the longest common suffix, find the string that is the <strong>smallest</strong> in length. If there are two or more such strings that have the <strong>same</strong> smallest length, find the one that occurred <strong>earlier</strong> in <code>wordsContainer</code>.</p> <p>Return <em>an array of integers </em><code>ans</code><em>, where </em><code>ans[i]</code><em> is the index of the string in </em><code>wordsContainer</code><em> that has the <strong>longest common suffix</strong> with </em><code>wordsQuery[i]</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">wordsContainer = [&quot;abcd&quot;,&quot;bcd&quot;,&quot;xbcd&quot;], wordsQuery = [&quot;cd&quot;,&quot;bcd&quot;,&quot;xyz&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at each <code>wordsQuery[i]</code> separately:</p> <ul> <li>For <code>wordsQuery[0] = &quot;cd&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;cd&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> <li>For <code>wordsQuery[1] = &quot;bcd&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;bcd&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> <li>For <code>wordsQuery[2] = &quot;xyz&quot;</code>, there is no string from <code>wordsContainer</code> that shares a common suffix. Hence the longest common suffix is <code>&quot;&quot;</code>, that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">wordsContainer = [&quot;abcdefgh&quot;,&quot;poiuygh&quot;,&quot;ghghgh&quot;], wordsQuery = [&quot;gh&quot;,&quot;acbfgh&quot;,&quot;acbfegh&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,0,2]</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at each <code>wordsQuery[i]</code> separately:</p> <ul> <li>For <code>wordsQuery[0] = &quot;gh&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;gh&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li> <li>For <code>wordsQuery[1] = &quot;acbfgh&quot;</code>, only the string at index 0 shares the longest common suffix <code>&quot;fgh&quot;</code>. Hence it is the answer, even though the string at index 2 is shorter.</li> <li>For <code>wordsQuery[2] = &quot;acbfegh&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;gh&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsContainer.length, wordsQuery.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= wordsContainer[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>1 &lt;= wordsQuery[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>wordsContainer[i]</code> consists only of lowercase English letters.</li> <li><code>wordsQuery[i]</code> consists only of lowercase English letters.</li> <li>Sum of <code>wordsContainer[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li> <li>Sum of <code>wordsQuery[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li> </ul>
Trie; Array; String
Java
class Trie { private final int inf = 1 << 30; private Trie[] children = new Trie[26]; private int length = inf; private int idx = inf; public void insert(String w, int i) { Trie node = this; if (node.length > w.length()) { node.length = w.length(); node.idx = i; } for (int k = w.length() - 1; k >= 0; --k) { int idx = w.charAt(k) - 'a'; if (node.children[idx] == null) { node.children[idx] = new Trie(); } node = node.children[idx]; if (node.length > w.length()) { node.length = w.length(); node.idx = i; } } } public int query(String w) { Trie node = this; for (int k = w.length() - 1; k >= 0; --k) { int idx = w.charAt(k) - 'a'; if (node.children[idx] == null) { break; } node = node.children[idx]; } return node.idx; } } class Solution { public int[] stringIndices(String[] wordsContainer, String[] wordsQuery) { Trie trie = new Trie(); for (int i = 0; i < wordsContainer.length; ++i) { trie.insert(wordsContainer[i], i); } int n = wordsQuery.length; int[] ans = new int[n]; for (int i = 0; i < n; ++i) { ans[i] = trie.query(wordsQuery[i]); } return ans; } }
3,093
Longest Common Suffix Queries
Hard
<p>You are given two arrays of strings <code>wordsContainer</code> and <code>wordsQuery</code>.</p> <p>For each <code>wordsQuery[i]</code>, you need to find a string from <code>wordsContainer</code> that has the <strong>longest common suffix</strong> with <code>wordsQuery[i]</code>. If there are two or more strings in <code>wordsContainer</code> that share the longest common suffix, find the string that is the <strong>smallest</strong> in length. If there are two or more such strings that have the <strong>same</strong> smallest length, find the one that occurred <strong>earlier</strong> in <code>wordsContainer</code>.</p> <p>Return <em>an array of integers </em><code>ans</code><em>, where </em><code>ans[i]</code><em> is the index of the string in </em><code>wordsContainer</code><em> that has the <strong>longest common suffix</strong> with </em><code>wordsQuery[i]</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">wordsContainer = [&quot;abcd&quot;,&quot;bcd&quot;,&quot;xbcd&quot;], wordsQuery = [&quot;cd&quot;,&quot;bcd&quot;,&quot;xyz&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at each <code>wordsQuery[i]</code> separately:</p> <ul> <li>For <code>wordsQuery[0] = &quot;cd&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;cd&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> <li>For <code>wordsQuery[1] = &quot;bcd&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;bcd&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> <li>For <code>wordsQuery[2] = &quot;xyz&quot;</code>, there is no string from <code>wordsContainer</code> that shares a common suffix. Hence the longest common suffix is <code>&quot;&quot;</code>, that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">wordsContainer = [&quot;abcdefgh&quot;,&quot;poiuygh&quot;,&quot;ghghgh&quot;], wordsQuery = [&quot;gh&quot;,&quot;acbfgh&quot;,&quot;acbfegh&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,0,2]</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at each <code>wordsQuery[i]</code> separately:</p> <ul> <li>For <code>wordsQuery[0] = &quot;gh&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;gh&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li> <li>For <code>wordsQuery[1] = &quot;acbfgh&quot;</code>, only the string at index 0 shares the longest common suffix <code>&quot;fgh&quot;</code>. Hence it is the answer, even though the string at index 2 is shorter.</li> <li>For <code>wordsQuery[2] = &quot;acbfegh&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;gh&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsContainer.length, wordsQuery.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= wordsContainer[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>1 &lt;= wordsQuery[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>wordsContainer[i]</code> consists only of lowercase English letters.</li> <li><code>wordsQuery[i]</code> consists only of lowercase English letters.</li> <li>Sum of <code>wordsContainer[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li> <li>Sum of <code>wordsQuery[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li> </ul>
Trie; Array; String
Python
class Trie: __slots__ = ("children", "length", "idx") def __init__(self): self.children = [None] * 26 self.length = inf self.idx = inf def insert(self, w: str, i: int): node = self if node.length > len(w): node.length = len(w) node.idx = i for c in w[::-1]: idx = ord(c) - ord("a") if node.children[idx] is None: node.children[idx] = Trie() node = node.children[idx] if node.length > len(w): node.length = len(w) node.idx = i def query(self, w: str) -> int: node = self for c in w[::-1]: idx = ord(c) - ord("a") if node.children[idx] is None: break node = node.children[idx] return node.idx class Solution: def stringIndices( self, wordsContainer: List[str], wordsQuery: List[str] ) -> List[int]: trie = Trie() for i, w in enumerate(wordsContainer): trie.insert(w, i) return [trie.query(w) for w in wordsQuery]
3,093
Longest Common Suffix Queries
Hard
<p>You are given two arrays of strings <code>wordsContainer</code> and <code>wordsQuery</code>.</p> <p>For each <code>wordsQuery[i]</code>, you need to find a string from <code>wordsContainer</code> that has the <strong>longest common suffix</strong> with <code>wordsQuery[i]</code>. If there are two or more strings in <code>wordsContainer</code> that share the longest common suffix, find the string that is the <strong>smallest</strong> in length. If there are two or more such strings that have the <strong>same</strong> smallest length, find the one that occurred <strong>earlier</strong> in <code>wordsContainer</code>.</p> <p>Return <em>an array of integers </em><code>ans</code><em>, where </em><code>ans[i]</code><em> is the index of the string in </em><code>wordsContainer</code><em> that has the <strong>longest common suffix</strong> with </em><code>wordsQuery[i]</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">wordsContainer = [&quot;abcd&quot;,&quot;bcd&quot;,&quot;xbcd&quot;], wordsQuery = [&quot;cd&quot;,&quot;bcd&quot;,&quot;xyz&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at each <code>wordsQuery[i]</code> separately:</p> <ul> <li>For <code>wordsQuery[0] = &quot;cd&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;cd&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> <li>For <code>wordsQuery[1] = &quot;bcd&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;bcd&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> <li>For <code>wordsQuery[2] = &quot;xyz&quot;</code>, there is no string from <code>wordsContainer</code> that shares a common suffix. Hence the longest common suffix is <code>&quot;&quot;</code>, that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">wordsContainer = [&quot;abcdefgh&quot;,&quot;poiuygh&quot;,&quot;ghghgh&quot;], wordsQuery = [&quot;gh&quot;,&quot;acbfgh&quot;,&quot;acbfegh&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,0,2]</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at each <code>wordsQuery[i]</code> separately:</p> <ul> <li>For <code>wordsQuery[0] = &quot;gh&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;gh&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li> <li>For <code>wordsQuery[1] = &quot;acbfgh&quot;</code>, only the string at index 0 shares the longest common suffix <code>&quot;fgh&quot;</code>. Hence it is the answer, even though the string at index 2 is shorter.</li> <li>For <code>wordsQuery[2] = &quot;acbfegh&quot;</code>, strings from <code>wordsContainer</code> that share the longest common suffix <code>&quot;gh&quot;</code> are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= wordsContainer.length, wordsQuery.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= wordsContainer[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>1 &lt;= wordsQuery[i].length &lt;= 5 * 10<sup>3</sup></code></li> <li><code>wordsContainer[i]</code> consists only of lowercase English letters.</li> <li><code>wordsQuery[i]</code> consists only of lowercase English letters.</li> <li>Sum of <code>wordsContainer[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li> <li>Sum of <code>wordsQuery[i].length</code> is at most <code>5 * 10<sup>5</sup></code>.</li> </ul>
Trie; Array; String
TypeScript
class Trie { private children: Trie[] = new Array<Trie>(26); private length: number = Infinity; private idx: number = Infinity; public insert(w: string, i: number): void { let node: Trie = this; if (node.length > w.length) { node.length = w.length; node.idx = i; } for (let k: number = w.length - 1; k >= 0; --k) { let idx: number = w.charCodeAt(k) - 'a'.charCodeAt(0); if (node.children[idx] == null) { node.children[idx] = new Trie(); } node = node.children[idx]; if (node.length > w.length) { node.length = w.length; node.idx = i; } } } public query(w: string): number { let node: Trie = this; for (let k: number = w.length - 1; k >= 0; --k) { let idx: number = w.charCodeAt(k) - 'a'.charCodeAt(0); if (node.children[idx] == null) { break; } node = node.children[idx]; } return node.idx; } } function stringIndices(wordsContainer: string[], wordsQuery: string[]): number[] { const trie: Trie = new Trie(); for (let i: number = 0; i < wordsContainer.length; ++i) { trie.insert(wordsContainer[i], i); } const n: number = wordsQuery.length; const ans: number[] = new Array<number>(n); for (let i: number = 0; i < n; ++i) { ans[i] = trie.query(wordsQuery[i]); } return ans; }
3,094
Guess the Number Using Bitwise Questions II
Medium
<p>There is a number <code>n</code> between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive) that you have to find.</p> <p>There is a pre-defined API <code>int commonBits(int num)</code> that helps you with your mission. But here is the challenge, every time you call this function, <code>n</code> changes in some way. But keep in mind, that you have to find the <strong>initial value of </strong><code>n</code>.</p> <p><code>commonBits(int num)</code> acts as follows:</p> <ul> <li>Calculate <code>count</code> which is the number of bits where both <code>n</code> and <code>num</code> have the same value in that position of their binary representation.</li> <li><code>n = n XOR num</code></li> <li>Return <code>count</code>.</li> </ul> <p>Return <em>the number</em> <code>n</code>.</p> <p><strong>Note:</strong> In this world, all numbers are between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive), thus for counting common bits, we see only the first 30 bits of those numbers.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 2<sup>30</sup> - 1</code></li> <li><code>0 &lt;= num &lt;= 2<sup>30</sup> - 1</code></li> <li>If you ask for some <code>num</code> out of the given range, the output wouldn&#39;t be reliable.</li> </ul>
Bit Manipulation; Interactive
C++
/** * Definition of commonBits API. * int commonBits(int num); */ class Solution { public: int findNumber() { int n = 0; for (int i = 0; i < 32; ++i) { int count1 = commonBits(1 << i); int count2 = commonBits(1 << i); if (count1 > count2) { n |= 1 << i; } } return n; } };
3,094
Guess the Number Using Bitwise Questions II
Medium
<p>There is a number <code>n</code> between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive) that you have to find.</p> <p>There is a pre-defined API <code>int commonBits(int num)</code> that helps you with your mission. But here is the challenge, every time you call this function, <code>n</code> changes in some way. But keep in mind, that you have to find the <strong>initial value of </strong><code>n</code>.</p> <p><code>commonBits(int num)</code> acts as follows:</p> <ul> <li>Calculate <code>count</code> which is the number of bits where both <code>n</code> and <code>num</code> have the same value in that position of their binary representation.</li> <li><code>n = n XOR num</code></li> <li>Return <code>count</code>.</li> </ul> <p>Return <em>the number</em> <code>n</code>.</p> <p><strong>Note:</strong> In this world, all numbers are between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive), thus for counting common bits, we see only the first 30 bits of those numbers.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 2<sup>30</sup> - 1</code></li> <li><code>0 &lt;= num &lt;= 2<sup>30</sup> - 1</code></li> <li>If you ask for some <code>num</code> out of the given range, the output wouldn&#39;t be reliable.</li> </ul>
Bit Manipulation; Interactive
Go
/** * Definition of commonBits API. * func commonBits(num int) int; */ func findNumber() (n int) { for i := 0; i < 32; i++ { count1 := commonBits(1 << i) count2 := commonBits(1 << i) if count1 > count2 { n |= 1 << i } } return }
3,094
Guess the Number Using Bitwise Questions II
Medium
<p>There is a number <code>n</code> between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive) that you have to find.</p> <p>There is a pre-defined API <code>int commonBits(int num)</code> that helps you with your mission. But here is the challenge, every time you call this function, <code>n</code> changes in some way. But keep in mind, that you have to find the <strong>initial value of </strong><code>n</code>.</p> <p><code>commonBits(int num)</code> acts as follows:</p> <ul> <li>Calculate <code>count</code> which is the number of bits where both <code>n</code> and <code>num</code> have the same value in that position of their binary representation.</li> <li><code>n = n XOR num</code></li> <li>Return <code>count</code>.</li> </ul> <p>Return <em>the number</em> <code>n</code>.</p> <p><strong>Note:</strong> In this world, all numbers are between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive), thus for counting common bits, we see only the first 30 bits of those numbers.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 2<sup>30</sup> - 1</code></li> <li><code>0 &lt;= num &lt;= 2<sup>30</sup> - 1</code></li> <li>If you ask for some <code>num</code> out of the given range, the output wouldn&#39;t be reliable.</li> </ul>
Bit Manipulation; Interactive
Java
/** * Definition of commonBits API (defined in the parent class Problem). * int commonBits(int num); */ public class Solution extends Problem { public int findNumber() { int n = 0; for (int i = 0; i < 32; ++i) { int count1 = commonBits(1 << i); int count2 = commonBits(1 << i); if (count1 > count2) { n |= 1 << i; } } return n; } }
3,094
Guess the Number Using Bitwise Questions II
Medium
<p>There is a number <code>n</code> between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive) that you have to find.</p> <p>There is a pre-defined API <code>int commonBits(int num)</code> that helps you with your mission. But here is the challenge, every time you call this function, <code>n</code> changes in some way. But keep in mind, that you have to find the <strong>initial value of </strong><code>n</code>.</p> <p><code>commonBits(int num)</code> acts as follows:</p> <ul> <li>Calculate <code>count</code> which is the number of bits where both <code>n</code> and <code>num</code> have the same value in that position of their binary representation.</li> <li><code>n = n XOR num</code></li> <li>Return <code>count</code>.</li> </ul> <p>Return <em>the number</em> <code>n</code>.</p> <p><strong>Note:</strong> In this world, all numbers are between <code>0</code> and <code>2<sup>30</sup> - 1</code> (both inclusive), thus for counting common bits, we see only the first 30 bits of those numbers.</p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 2<sup>30</sup> - 1</code></li> <li><code>0 &lt;= num &lt;= 2<sup>30</sup> - 1</code></li> <li>If you ask for some <code>num</code> out of the given range, the output wouldn&#39;t be reliable.</li> </ul>
Bit Manipulation; Interactive
Python
# Definition of commonBits API. # def commonBits(num: int) -> int: class Solution: def findNumber(self) -> int: n = 0 for i in range(32): count1 = commonBits(1 << i) count2 = commonBits(1 << i) if count1 > count2: n |= 1 << i return n
3,095
Shortest Subarray With OR at Least K I
Easy
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p> <p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p> <p>Note that <code>[2]</code> is also a special subarray.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= k &lt; 64</code></li> </ul>
Bit Manipulation; Array; Sliding Window
C++
class Solution { public: int minimumSubarrayLength(vector<int>& nums, int k) { int n = nums.size(); int cnt[32]{}; int ans = n + 1; for (int i = 0, j = 0, s = 0; j < n; ++j) { s |= nums[j]; for (int h = 0; h < 32; ++h) { if ((nums[j] >> h & 1) == 1) { ++cnt[h]; } } for (; s >= k && i <= j; ++i) { ans = min(ans, j - i + 1); for (int h = 0; h < 32; ++h) { if ((nums[i] >> h & 1) == 1) { if (--cnt[h] == 0) { s ^= 1 << h; } } } } } return ans > n ? -1 : ans; } };
3,095
Shortest Subarray With OR at Least K I
Easy
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p> <p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p> <p>Note that <code>[2]</code> is also a special subarray.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= k &lt; 64</code></li> </ul>
Bit Manipulation; Array; Sliding Window
Go
func minimumSubarrayLength(nums []int, k int) int { n := len(nums) cnt := [32]int{} ans := n + 1 s, i := 0, 0 for j, x := range nums { s |= x for h := 0; h < 32; h++ { if x>>h&1 == 1 { cnt[h]++ } } for ; s >= k && i <= j; i++ { ans = min(ans, j-i+1) for h := 0; h < 32; h++ { if nums[i]>>h&1 == 1 { cnt[h]-- if cnt[h] == 0 { s ^= 1 << h } } } } } if ans == n+1 { return -1 } return ans }
3,095
Shortest Subarray With OR at Least K I
Easy
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p> <p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p> <p>Note that <code>[2]</code> is also a special subarray.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= k &lt; 64</code></li> </ul>
Bit Manipulation; Array; Sliding Window
Java
class Solution { public int minimumSubarrayLength(int[] nums, int k) { int n = nums.length; int[] cnt = new int[32]; int ans = n + 1; for (int i = 0, j = 0, s = 0; j < n; ++j) { s |= nums[j]; for (int h = 0; h < 32; ++h) { if ((nums[j] >> h & 1) == 1) { ++cnt[h]; } } for (; s >= k && i <= j; ++i) { ans = Math.min(ans, j - i + 1); for (int h = 0; h < 32; ++h) { if ((nums[i] >> h & 1) == 1) { if (--cnt[h] == 0) { s ^= 1 << h; } } } } } return ans > n ? -1 : ans; } }
3,095
Shortest Subarray With OR at Least K I
Easy
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p> <p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p> <p>Note that <code>[2]</code> is also a special subarray.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= k &lt; 64</code></li> </ul>
Bit Manipulation; Array; Sliding Window
Python
class Solution: def minimumSubarrayLength(self, nums: List[int], k: int) -> int: n = len(nums) cnt = [0] * 32 ans = n + 1 s = i = 0 for j, x in enumerate(nums): s |= x for h in range(32): if x >> h & 1: cnt[h] += 1 while s >= k and i <= j: ans = min(ans, j - i + 1) y = nums[i] for h in range(32): if y >> h & 1: cnt[h] -= 1 if cnt[h] == 0: s ^= 1 << h i += 1 return -1 if ans > n else ans
3,095
Shortest Subarray With OR at Least K I
Easy
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p> <p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p> <p>Note that <code>[2]</code> is also a special subarray.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= k &lt; 64</code></li> </ul>
Bit Manipulation; Array; Sliding Window
Rust
impl Solution { pub fn minimum_subarray_length(nums: Vec<i32>, k: i32) -> i32 { let n = nums.len(); let mut cnt = vec![0; 32]; let mut ans = n as i32 + 1; let mut s = 0; let mut i = 0; for (j, &x) in nums.iter().enumerate() { s |= x; for h in 0..32 { if (x >> h) & 1 == 1 { cnt[h] += 1; } } while s >= k && i <= j { ans = ans.min((j - i + 1) as i32); let y = nums[i]; for h in 0..32 { if (y >> h) & 1 == 1 { cnt[h] -= 1; if cnt[h] == 0 { s ^= 1 << h; } } } i += 1; } } if ans > n as i32 { -1 } else { ans } } }
3,095
Shortest Subarray With OR at Least K I
Easy
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p> <p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p> <p>Note that <code>[2]</code> is also a special subarray.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>0 &lt;= nums[i] &lt;= 50</code></li> <li><code>0 &lt;= k &lt; 64</code></li> </ul>
Bit Manipulation; Array; Sliding Window
TypeScript
function minimumSubarrayLength(nums: number[], k: number): number { const n = nums.length; let ans = n + 1; const cnt: number[] = new Array<number>(32).fill(0); for (let i = 0, j = 0, s = 0; j < n; ++j) { s |= nums[j]; for (let h = 0; h < 32; ++h) { if (((nums[j] >> h) & 1) === 1) { ++cnt[h]; } } for (; s >= k && i <= j; ++i) { ans = Math.min(ans, j - i + 1); for (let h = 0; h < 32; ++h) { if (((nums[i] >> h) & 1) === 1 && --cnt[h] === 0) { s ^= 1 << h; } } } } return ans === n + 1 ? -1 : ans; }
3,096
Minimum Levels to Gain More Points
Medium
<p>You are given a binary array <code>possible</code> of length <code>n</code>.</p> <p>Alice and Bob are playing a game that consists of <code>n</code> levels. Some of the levels in the game are <strong>impossible</strong> to clear while others can <strong>always</strong> be cleared. In particular, if <code>possible[i] == 0</code>, then the <code>i<sup>th</sup></code> level is <strong>impossible</strong> to clear for <strong>both</strong> the players. A player gains <code>1</code> point on clearing a level and loses <code>1</code> point if the player fails to clear it.</p> <p>At the start of the game, Alice will play some levels in the <strong>given order</strong> starting from the <code>0<sup>th</sup></code> level, after which Bob will play for the rest of the levels.</p> <p>Alice wants to know the <strong>minimum</strong> number of levels she should play to gain more points than Bob, if both players play optimally to <strong>maximize</strong> their points.</p> <p>Return <em>the <strong>minimum</strong> number of levels Alice should play to gain more points</em>. <em>If this is <strong>not</strong> possible, return</em> <code>-1</code>.</p> <p><strong>Note</strong> that each player must play at least <code>1</code> level.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at all the levels that Alice can play up to:</p> <ul> <li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point.</li> <li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 1 - 1 = 0 points, while Bob has 1 - 1 = 0 points.</li> <li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 - 1 + 1 = 1 point, while Bob has -1 point.</li> </ul> <p>Alice must play a minimum of 1 level to gain more points.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at all the levels that Alice can play up to:</p> <ul> <li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points.</li> <li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points.</li> <li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points.</li> <li>If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point.</li> </ul> <p>Alice must play a minimum of 3 levels to gain more points.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can&#39;t gain more points than Bob.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == possible.length &lt;= 10<sup>5</sup></code></li> <li><code>possible[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Prefix Sum
C++
class Solution { public: int minimumLevels(vector<int>& possible) { int s = 0; for (int x : possible) { s += x == 0 ? -1 : 1; } int t = 0; for (int i = 1; i < possible.size(); ++i) { t += possible[i - 1] == 0 ? -1 : 1; if (t > s - t) { return i; } } return -1; } };
3,096
Minimum Levels to Gain More Points
Medium
<p>You are given a binary array <code>possible</code> of length <code>n</code>.</p> <p>Alice and Bob are playing a game that consists of <code>n</code> levels. Some of the levels in the game are <strong>impossible</strong> to clear while others can <strong>always</strong> be cleared. In particular, if <code>possible[i] == 0</code>, then the <code>i<sup>th</sup></code> level is <strong>impossible</strong> to clear for <strong>both</strong> the players. A player gains <code>1</code> point on clearing a level and loses <code>1</code> point if the player fails to clear it.</p> <p>At the start of the game, Alice will play some levels in the <strong>given order</strong> starting from the <code>0<sup>th</sup></code> level, after which Bob will play for the rest of the levels.</p> <p>Alice wants to know the <strong>minimum</strong> number of levels she should play to gain more points than Bob, if both players play optimally to <strong>maximize</strong> their points.</p> <p>Return <em>the <strong>minimum</strong> number of levels Alice should play to gain more points</em>. <em>If this is <strong>not</strong> possible, return</em> <code>-1</code>.</p> <p><strong>Note</strong> that each player must play at least <code>1</code> level.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at all the levels that Alice can play up to:</p> <ul> <li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point.</li> <li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 1 - 1 = 0 points, while Bob has 1 - 1 = 0 points.</li> <li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 - 1 + 1 = 1 point, while Bob has -1 point.</li> </ul> <p>Alice must play a minimum of 1 level to gain more points.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at all the levels that Alice can play up to:</p> <ul> <li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points.</li> <li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points.</li> <li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points.</li> <li>If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point.</li> </ul> <p>Alice must play a minimum of 3 levels to gain more points.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can&#39;t gain more points than Bob.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == possible.length &lt;= 10<sup>5</sup></code></li> <li><code>possible[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Prefix Sum
Go
func minimumLevels(possible []int) int { s := 0 for _, x := range possible { if x == 0 { x = -1 } s += x } t := 0 for i, x := range possible[:len(possible)-1] { if x == 0 { x = -1 } t += x if t > s-t { return i + 1 } } return -1 }
3,096
Minimum Levels to Gain More Points
Medium
<p>You are given a binary array <code>possible</code> of length <code>n</code>.</p> <p>Alice and Bob are playing a game that consists of <code>n</code> levels. Some of the levels in the game are <strong>impossible</strong> to clear while others can <strong>always</strong> be cleared. In particular, if <code>possible[i] == 0</code>, then the <code>i<sup>th</sup></code> level is <strong>impossible</strong> to clear for <strong>both</strong> the players. A player gains <code>1</code> point on clearing a level and loses <code>1</code> point if the player fails to clear it.</p> <p>At the start of the game, Alice will play some levels in the <strong>given order</strong> starting from the <code>0<sup>th</sup></code> level, after which Bob will play for the rest of the levels.</p> <p>Alice wants to know the <strong>minimum</strong> number of levels she should play to gain more points than Bob, if both players play optimally to <strong>maximize</strong> their points.</p> <p>Return <em>the <strong>minimum</strong> number of levels Alice should play to gain more points</em>. <em>If this is <strong>not</strong> possible, return</em> <code>-1</code>.</p> <p><strong>Note</strong> that each player must play at least <code>1</code> level.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at all the levels that Alice can play up to:</p> <ul> <li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point.</li> <li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 1 - 1 = 0 points, while Bob has 1 - 1 = 0 points.</li> <li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 - 1 + 1 = 1 point, while Bob has -1 point.</li> </ul> <p>Alice must play a minimum of 1 level to gain more points.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at all the levels that Alice can play up to:</p> <ul> <li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points.</li> <li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points.</li> <li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points.</li> <li>If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point.</li> </ul> <p>Alice must play a minimum of 3 levels to gain more points.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can&#39;t gain more points than Bob.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == possible.length &lt;= 10<sup>5</sup></code></li> <li><code>possible[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Prefix Sum
Java
class Solution { public int minimumLevels(int[] possible) { int s = 0; for (int x : possible) { s += x == 0 ? -1 : 1; } int t = 0; for (int i = 1; i < possible.length; ++i) { t += possible[i - 1] == 0 ? -1 : 1; if (t > s - t) { return i; } } return -1; } }
3,096
Minimum Levels to Gain More Points
Medium
<p>You are given a binary array <code>possible</code> of length <code>n</code>.</p> <p>Alice and Bob are playing a game that consists of <code>n</code> levels. Some of the levels in the game are <strong>impossible</strong> to clear while others can <strong>always</strong> be cleared. In particular, if <code>possible[i] == 0</code>, then the <code>i<sup>th</sup></code> level is <strong>impossible</strong> to clear for <strong>both</strong> the players. A player gains <code>1</code> point on clearing a level and loses <code>1</code> point if the player fails to clear it.</p> <p>At the start of the game, Alice will play some levels in the <strong>given order</strong> starting from the <code>0<sup>th</sup></code> level, after which Bob will play for the rest of the levels.</p> <p>Alice wants to know the <strong>minimum</strong> number of levels she should play to gain more points than Bob, if both players play optimally to <strong>maximize</strong> their points.</p> <p>Return <em>the <strong>minimum</strong> number of levels Alice should play to gain more points</em>. <em>If this is <strong>not</strong> possible, return</em> <code>-1</code>.</p> <p><strong>Note</strong> that each player must play at least <code>1</code> level.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at all the levels that Alice can play up to:</p> <ul> <li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point.</li> <li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 1 - 1 = 0 points, while Bob has 1 - 1 = 0 points.</li> <li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 - 1 + 1 = 1 point, while Bob has -1 point.</li> </ul> <p>Alice must play a minimum of 1 level to gain more points.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at all the levels that Alice can play up to:</p> <ul> <li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points.</li> <li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points.</li> <li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points.</li> <li>If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point.</li> </ul> <p>Alice must play a minimum of 3 levels to gain more points.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can&#39;t gain more points than Bob.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == possible.length &lt;= 10<sup>5</sup></code></li> <li><code>possible[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Prefix Sum
Python
class Solution: def minimumLevels(self, possible: List[int]) -> int: s = sum(-1 if x == 0 else 1 for x in possible) t = 0 for i, x in enumerate(possible[:-1], 1): t += -1 if x == 0 else 1 if t > s - t: return i return -1
3,096
Minimum Levels to Gain More Points
Medium
<p>You are given a binary array <code>possible</code> of length <code>n</code>.</p> <p>Alice and Bob are playing a game that consists of <code>n</code> levels. Some of the levels in the game are <strong>impossible</strong> to clear while others can <strong>always</strong> be cleared. In particular, if <code>possible[i] == 0</code>, then the <code>i<sup>th</sup></code> level is <strong>impossible</strong> to clear for <strong>both</strong> the players. A player gains <code>1</code> point on clearing a level and loses <code>1</code> point if the player fails to clear it.</p> <p>At the start of the game, Alice will play some levels in the <strong>given order</strong> starting from the <code>0<sup>th</sup></code> level, after which Bob will play for the rest of the levels.</p> <p>Alice wants to know the <strong>minimum</strong> number of levels she should play to gain more points than Bob, if both players play optimally to <strong>maximize</strong> their points.</p> <p>Return <em>the <strong>minimum</strong> number of levels Alice should play to gain more points</em>. <em>If this is <strong>not</strong> possible, return</em> <code>-1</code>.</p> <p><strong>Note</strong> that each player must play at least <code>1</code> level.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at all the levels that Alice can play up to:</p> <ul> <li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has -1 + 1 - 1 = -1 point.</li> <li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 1 - 1 = 0 points, while Bob has 1 - 1 = 0 points.</li> <li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 1 - 1 + 1 = 1 point, while Bob has -1 point.</li> </ul> <p>Alice must play a minimum of 1 level to gain more points.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [1,1,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>Let&#39;s look at all the levels that Alice can play up to:</p> <ul> <li>If Alice plays only level 0 and Bob plays the rest of the levels, Alice has 1 point, while Bob has 4 points.</li> <li>If Alice plays till level 1 and Bob plays the rest of the levels, Alice has 2 points, while Bob has 3 points.</li> <li>If Alice plays till level 2 and Bob plays the rest of the levels, Alice has 3 points, while Bob has 2 points.</li> <li>If Alice plays till level 3 and Bob plays the rest of the levels, Alice has 4 points, while Bob has 1 point.</li> </ul> <p>Alice must play a minimum of 3 levels to gain more points.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">possible = [0,0]</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can&#39;t gain more points than Bob.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == possible.length &lt;= 10<sup>5</sup></code></li> <li><code>possible[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Prefix Sum
TypeScript
function minimumLevels(possible: number[]): number { const s = possible.reduce((acc, x) => acc + (x === 0 ? -1 : 1), 0); let t = 0; for (let i = 1; i < possible.length; ++i) { t += possible[i - 1] === 0 ? -1 : 1; if (t > s - t) { return i; } } return -1; }
3,097
Shortest Subarray With OR at Least K II
Medium
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p> <p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array; Sliding Window
C++
class Solution { public: int minimumSubarrayLength(vector<int>& nums, int k) { int n = nums.size(); int cnt[32]{}; int ans = n + 1; for (int i = 0, j = 0, s = 0; j < n; ++j) { s |= nums[j]; for (int h = 0; h < 32; ++h) { if ((nums[j] >> h & 1) == 1) { ++cnt[h]; } } for (; s >= k && i <= j; ++i) { ans = min(ans, j - i + 1); for (int h = 0; h < 32; ++h) { if ((nums[i] >> h & 1) == 1) { if (--cnt[h] == 0) { s ^= 1 << h; } } } } } return ans > n ? -1 : ans; } };
3,097
Shortest Subarray With OR at Least K II
Medium
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p> <p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array; Sliding Window
Go
func minimumSubarrayLength(nums []int, k int) int { n := len(nums) cnt := [32]int{} ans := n + 1 s, i := 0, 0 for j, x := range nums { s |= x for h := 0; h < 32; h++ { if x>>h&1 == 1 { cnt[h]++ } } for ; s >= k && i <= j; i++ { ans = min(ans, j-i+1) for h := 0; h < 32; h++ { if nums[i]>>h&1 == 1 { cnt[h]-- if cnt[h] == 0 { s ^= 1 << h } } } } } if ans == n+1 { return -1 } return ans }
3,097
Shortest Subarray With OR at Least K II
Medium
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p> <p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array; Sliding Window
Java
class Solution { public int minimumSubarrayLength(int[] nums, int k) { int n = nums.length; int[] cnt = new int[32]; int ans = n + 1; for (int i = 0, j = 0, s = 0; j < n; ++j) { s |= nums[j]; for (int h = 0; h < 32; ++h) { if ((nums[j] >> h & 1) == 1) { ++cnt[h]; } } for (; s >= k && i <= j; ++i) { ans = Math.min(ans, j - i + 1); for (int h = 0; h < 32; ++h) { if ((nums[i] >> h & 1) == 1) { if (--cnt[h] == 0) { s ^= 1 << h; } } } } } return ans > n ? -1 : ans; } }
3,097
Shortest Subarray With OR at Least K II
Medium
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p> <p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array; Sliding Window
Python
class Solution: def minimumSubarrayLength(self, nums: List[int], k: int) -> int: n = len(nums) cnt = [0] * 32 ans = n + 1 s = i = 0 for j, x in enumerate(nums): s |= x for h in range(32): if x >> h & 1: cnt[h] += 1 while s >= k and i <= j: ans = min(ans, j - i + 1) y = nums[i] for h in range(32): if y >> h & 1: cnt[h] -= 1 if cnt[h] == 0: s ^= 1 << h i += 1 return -1 if ans > n else ans
3,097
Shortest Subarray With OR at Least K II
Medium
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p> <p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array; Sliding Window
Rust
impl Solution { pub fn minimum_subarray_length(nums: Vec<i32>, k: i32) -> i32 { let n = nums.len(); let mut cnt = vec![0; 32]; let mut ans = n as i32 + 1; let mut s = 0; let mut i = 0; for (j, &x) in nums.iter().enumerate() { s |= x; for h in 0..32 { if (x >> h) & 1 == 1 { cnt[h] += 1; } } while s >= k && i <= j { ans = ans.min((j - i + 1) as i32); let y = nums[i]; for h in 0..32 { if (y >> h) & 1 == 1 { cnt[h] -= 1; if cnt[h] == 0 { s ^= 1 << h; } } } i += 1; } } if ans > n as i32 { -1 } else { ans } } }
3,097
Shortest Subarray With OR at Least K II
Medium
<p>You are given an array <code>nums</code> of <strong>non-negative</strong> integers and an integer <code>k</code>.</p> <p>An array is called <strong>special</strong> if the bitwise <code>OR</code> of all of its elements is <strong>at least</strong> <code>k</code>.</p> <p>Return <em>the length of the <strong>shortest</strong> <strong>special</strong> <strong>non-empty</strong> <span data-keyword="subarray-nonempty">subarray</span> of</em> <code>nums</code>, <em>or return</em> <code>-1</code> <em>if no special subarray exists</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[3]</code> has <code>OR</code> value of <code>3</code>. Hence, we return <code>1</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,1,8], k = 10</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[2,1,8]</code> has <code>OR</code> value of <code>11</code>. Hence, we return <code>3</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2], k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The subarray <code>[1]</code> has <code>OR</code> value of <code>1</code>. Hence, we return <code>1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>9</sup></code></li> </ul>
Bit Manipulation; Array; Sliding Window
TypeScript
function minimumSubarrayLength(nums: number[], k: number): number { const n = nums.length; let ans = n + 1; const cnt: number[] = new Array<number>(32).fill(0); for (let i = 0, j = 0, s = 0; j < n; ++j) { s |= nums[j]; for (let h = 0; h < 32; ++h) { if (((nums[j] >> h) & 1) === 1) { ++cnt[h]; } } for (; s >= k && i <= j; ++i) { ans = Math.min(ans, j - i + 1); for (let h = 0; h < 32; ++h) { if (((nums[i] >> h) & 1) === 1 && --cnt[h] === 0) { s ^= 1 << h; } } } } return ans === n + 1 ? -1 : ans; }
3,098
Find the Sum of Subsequence Powers
Hard
<p>You are given an integer array <code>nums</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>power</strong> of a <span data-keyword="subsequence-array">subsequence</span> is defined as the <strong>minimum</strong> absolute difference between <strong>any</strong> two elements in the subsequence.</p> <p>Return <em>the <strong>sum</strong> of <strong>powers</strong> of <strong>all</strong> subsequences of </em><code>nums</code><em> which have length</em> <strong><em>equal to</em></strong> <code>k</code>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There are 4 subsequences in <code>nums</code> which have length 3: <code>[1,2,3]</code>, <code>[1,3,4]</code>, <code>[1,2,4]</code>, and <code>[2,3,4]</code>. The sum of powers is <code>|2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The only subsequence in <code>nums</code> which has length 2 is&nbsp;<code>[2,2]</code>. The sum of powers is <code>|2 - 2| = 0</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,-1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>There are 3 subsequences in <code>nums</code> which have length 2: <code>[4,3]</code>, <code>[4,-1]</code>, and <code>[3,-1]</code>. The sum of powers is <code>|4 - 3| + |4 - (-1)| + |3 - (-1)| = 10</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 50</code></li> <li><code>-10<sup>8</sup> &lt;= nums[i] &lt;= 10<sup>8</sup> </code></li> <li><code>2 &lt;= k &lt;= n</code></li> </ul>
Array; Dynamic Programming; Sorting
C++
class Solution { public: int sumOfPowers(vector<int>& nums, int k) { unordered_map<long long, int> f; const int mod = 1e9 + 7; int n = nums.size(); sort(nums.begin(), nums.end()); auto dfs = [&](this auto&& dfs, int i, int j, int k, int mi) -> int { if (i >= n) { return k == 0 ? mi : 0; } if (n - i < k) { return 0; } long long key = (1LL * mi) << 18 | (i << 12) | (j << 6) | k; if (f.contains(key)) { return f[key]; } long long ans = dfs(i + 1, j, k, mi); if (j == n) { ans += dfs(i + 1, i, k - 1, mi); } else { ans += dfs(i + 1, i, k - 1, min(mi, nums[i] - nums[j])); } ans %= mod; f[key] = ans; return f[key]; }; return dfs(0, n, k, INT_MAX); } };
3,098
Find the Sum of Subsequence Powers
Hard
<p>You are given an integer array <code>nums</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>power</strong> of a <span data-keyword="subsequence-array">subsequence</span> is defined as the <strong>minimum</strong> absolute difference between <strong>any</strong> two elements in the subsequence.</p> <p>Return <em>the <strong>sum</strong> of <strong>powers</strong> of <strong>all</strong> subsequences of </em><code>nums</code><em> which have length</em> <strong><em>equal to</em></strong> <code>k</code>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There are 4 subsequences in <code>nums</code> which have length 3: <code>[1,2,3]</code>, <code>[1,3,4]</code>, <code>[1,2,4]</code>, and <code>[2,3,4]</code>. The sum of powers is <code>|2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The only subsequence in <code>nums</code> which has length 2 is&nbsp;<code>[2,2]</code>. The sum of powers is <code>|2 - 2| = 0</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,-1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>There are 3 subsequences in <code>nums</code> which have length 2: <code>[4,3]</code>, <code>[4,-1]</code>, and <code>[3,-1]</code>. The sum of powers is <code>|4 - 3| + |4 - (-1)| + |3 - (-1)| = 10</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 50</code></li> <li><code>-10<sup>8</sup> &lt;= nums[i] &lt;= 10<sup>8</sup> </code></li> <li><code>2 &lt;= k &lt;= n</code></li> </ul>
Array; Dynamic Programming; Sorting
Go
func sumOfPowers(nums []int, k int) int { const mod int = 1e9 + 7 sort.Ints(nums) n := len(nums) f := map[int]int{} var dfs func(i, j, k, mi int) int dfs = func(i, j, k, mi int) int { if i >= n { if k == 0 { return mi } return 0 } if n-i < k { return 0 } key := mi<<18 | (i << 12) | (j << 6) | k if v, ok := f[key]; ok { return v } ans := dfs(i+1, j, k, mi) if j == n { ans += dfs(i+1, i, k-1, mi) } else { ans += dfs(i+1, i, k-1, min(mi, nums[i]-nums[j])) } ans %= mod f[key] = ans return ans } return dfs(0, n, k, math.MaxInt) }
3,098
Find the Sum of Subsequence Powers
Hard
<p>You are given an integer array <code>nums</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>power</strong> of a <span data-keyword="subsequence-array">subsequence</span> is defined as the <strong>minimum</strong> absolute difference between <strong>any</strong> two elements in the subsequence.</p> <p>Return <em>the <strong>sum</strong> of <strong>powers</strong> of <strong>all</strong> subsequences of </em><code>nums</code><em> which have length</em> <strong><em>equal to</em></strong> <code>k</code>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There are 4 subsequences in <code>nums</code> which have length 3: <code>[1,2,3]</code>, <code>[1,3,4]</code>, <code>[1,2,4]</code>, and <code>[2,3,4]</code>. The sum of powers is <code>|2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The only subsequence in <code>nums</code> which has length 2 is&nbsp;<code>[2,2]</code>. The sum of powers is <code>|2 - 2| = 0</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,-1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>There are 3 subsequences in <code>nums</code> which have length 2: <code>[4,3]</code>, <code>[4,-1]</code>, and <code>[3,-1]</code>. The sum of powers is <code>|4 - 3| + |4 - (-1)| + |3 - (-1)| = 10</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 50</code></li> <li><code>-10<sup>8</sup> &lt;= nums[i] &lt;= 10<sup>8</sup> </code></li> <li><code>2 &lt;= k &lt;= n</code></li> </ul>
Array; Dynamic Programming; Sorting
Java
class Solution { private Map<Long, Integer> f = new HashMap<>(); private final int mod = (int) 1e9 + 7; private int[] nums; public int sumOfPowers(int[] nums, int k) { Arrays.sort(nums); this.nums = nums; return dfs(0, nums.length, k, Integer.MAX_VALUE); } private int dfs(int i, int j, int k, int mi) { if (i >= nums.length) { return k == 0 ? mi : 0; } if (nums.length - i < k) { return 0; } long key = (1L * mi) << 18 | (i << 12) | (j << 6) | k; if (f.containsKey(key)) { return f.get(key); } int ans = dfs(i + 1, j, k, mi); if (j == nums.length) { ans += dfs(i + 1, i, k - 1, mi); } else { ans += dfs(i + 1, i, k - 1, Math.min(mi, nums[i] - nums[j])); } ans %= mod; f.put(key, ans); return ans; } }
3,098
Find the Sum of Subsequence Powers
Hard
<p>You are given an integer array <code>nums</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>power</strong> of a <span data-keyword="subsequence-array">subsequence</span> is defined as the <strong>minimum</strong> absolute difference between <strong>any</strong> two elements in the subsequence.</p> <p>Return <em>the <strong>sum</strong> of <strong>powers</strong> of <strong>all</strong> subsequences of </em><code>nums</code><em> which have length</em> <strong><em>equal to</em></strong> <code>k</code>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There are 4 subsequences in <code>nums</code> which have length 3: <code>[1,2,3]</code>, <code>[1,3,4]</code>, <code>[1,2,4]</code>, and <code>[2,3,4]</code>. The sum of powers is <code>|2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The only subsequence in <code>nums</code> which has length 2 is&nbsp;<code>[2,2]</code>. The sum of powers is <code>|2 - 2| = 0</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,-1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>There are 3 subsequences in <code>nums</code> which have length 2: <code>[4,3]</code>, <code>[4,-1]</code>, and <code>[3,-1]</code>. The sum of powers is <code>|4 - 3| + |4 - (-1)| + |3 - (-1)| = 10</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 50</code></li> <li><code>-10<sup>8</sup> &lt;= nums[i] &lt;= 10<sup>8</sup> </code></li> <li><code>2 &lt;= k &lt;= n</code></li> </ul>
Array; Dynamic Programming; Sorting
Python
class Solution: def sumOfPowers(self, nums: List[int], k: int) -> int: @cache def dfs(i: int, j: int, k: int, mi: int) -> int: if i >= n: return mi if k == 0 else 0 if n - i < k: return 0 ans = dfs(i + 1, j, k, mi) if j == n: ans += dfs(i + 1, i, k - 1, mi) else: ans += dfs(i + 1, i, k - 1, min(mi, nums[i] - nums[j])) ans %= mod return ans mod = 10**9 + 7 n = len(nums) nums.sort() return dfs(0, n, k, inf)
3,098
Find the Sum of Subsequence Powers
Hard
<p>You are given an integer array <code>nums</code> of length <code>n</code>, and a <strong>positive</strong> integer <code>k</code>.</p> <p>The <strong>power</strong> of a <span data-keyword="subsequence-array">subsequence</span> is defined as the <strong>minimum</strong> absolute difference between <strong>any</strong> two elements in the subsequence.</p> <p>Return <em>the <strong>sum</strong> of <strong>powers</strong> of <strong>all</strong> subsequences of </em><code>nums</code><em> which have length</em> <strong><em>equal to</em></strong> <code>k</code>.</p> <p>Since the answer may be large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There are 4 subsequences in <code>nums</code> which have length 3: <code>[1,2,3]</code>, <code>[1,3,4]</code>, <code>[1,2,4]</code>, and <code>[2,3,4]</code>. The sum of powers is <code>|2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The only subsequence in <code>nums</code> which has length 2 is&nbsp;<code>[2,2]</code>. The sum of powers is <code>|2 - 2| = 0</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,3,-1], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>There are 3 subsequences in <code>nums</code> which have length 2: <code>[4,3]</code>, <code>[4,-1]</code>, and <code>[3,-1]</code>. The sum of powers is <code>|4 - 3| + |4 - (-1)| + |3 - (-1)| = 10</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n == nums.length &lt;= 50</code></li> <li><code>-10<sup>8</sup> &lt;= nums[i] &lt;= 10<sup>8</sup> </code></li> <li><code>2 &lt;= k &lt;= n</code></li> </ul>
Array; Dynamic Programming; Sorting
TypeScript
function sumOfPowers(nums: number[], k: number): number { const mod = BigInt(1e9 + 7); nums.sort((a, b) => a - b); const n = nums.length; const f: Map<bigint, bigint> = new Map(); function dfs(i: number, j: number, k: number, mi: number): bigint { if (i >= n) { if (k === 0) { return BigInt(mi); } return BigInt(0); } if (n - i < k) { return BigInt(0); } const key = (BigInt(mi) << BigInt(18)) | (BigInt(i) << BigInt(12)) | (BigInt(j) << BigInt(6)) | BigInt(k); if (f.has(key)) { return f.get(key)!; } let ans = dfs(i + 1, j, k, mi); if (j === n) { ans += dfs(i + 1, i, k - 1, mi); } else { ans += dfs(i + 1, i, k - 1, Math.min(mi, nums[i] - nums[j])); } ans %= mod; f.set(key, ans); return ans; } return Number(dfs(0, n, k, Number.MAX_SAFE_INTEGER)); }
3,099
Harshad Number
Easy
<p>An integer divisible by the <strong>sum</strong> of its digits is said to be a <strong>Harshad</strong> number. You are given an integer <code>x</code>. Return<em> the sum of the digits </em>of<em> </em><code>x</code><em> </em>if<em> </em><code>x</code><em> </em>is a <strong>Harshad</strong> number, otherwise, return<em> </em><code>-1</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 18</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <p>The sum of digits of <code>x</code> is <code>9</code>. <code>18</code> is divisible by <code>9</code>. So <code>18</code> is a Harshad number and the answer is <code>9</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 23</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The sum of digits of <code>x</code> is <code>5</code>. <code>23</code> is not divisible by <code>5</code>. So <code>23</code> is not a Harshad number and the answer is <code>-1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 100</code></li> </ul>
Math
C++
class Solution { public: int sumOfTheDigitsOfHarshadNumber(int x) { int s = 0; for (int y = x; y > 0; y /= 10) { s += y % 10; } return x % s == 0 ? s : -1; } };
3,099
Harshad Number
Easy
<p>An integer divisible by the <strong>sum</strong> of its digits is said to be a <strong>Harshad</strong> number. You are given an integer <code>x</code>. Return<em> the sum of the digits </em>of<em> </em><code>x</code><em> </em>if<em> </em><code>x</code><em> </em>is a <strong>Harshad</strong> number, otherwise, return<em> </em><code>-1</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 18</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <p>The sum of digits of <code>x</code> is <code>9</code>. <code>18</code> is divisible by <code>9</code>. So <code>18</code> is a Harshad number and the answer is <code>9</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 23</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The sum of digits of <code>x</code> is <code>5</code>. <code>23</code> is not divisible by <code>5</code>. So <code>23</code> is not a Harshad number and the answer is <code>-1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 100</code></li> </ul>
Math
Go
func sumOfTheDigitsOfHarshadNumber(x int) int { s := 0 for y := x; y > 0; y /= 10 { s += y % 10 } if x%s == 0 { return s } return -1 }
3,099
Harshad Number
Easy
<p>An integer divisible by the <strong>sum</strong> of its digits is said to be a <strong>Harshad</strong> number. You are given an integer <code>x</code>. Return<em> the sum of the digits </em>of<em> </em><code>x</code><em> </em>if<em> </em><code>x</code><em> </em>is a <strong>Harshad</strong> number, otherwise, return<em> </em><code>-1</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 18</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <p>The sum of digits of <code>x</code> is <code>9</code>. <code>18</code> is divisible by <code>9</code>. So <code>18</code> is a Harshad number and the answer is <code>9</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 23</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The sum of digits of <code>x</code> is <code>5</code>. <code>23</code> is not divisible by <code>5</code>. So <code>23</code> is not a Harshad number and the answer is <code>-1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 100</code></li> </ul>
Math
Java
class Solution { public int sumOfTheDigitsOfHarshadNumber(int x) { int s = 0; for (int y = x; y > 0; y /= 10) { s += y % 10; } return x % s == 0 ? s : -1; } }
3,099
Harshad Number
Easy
<p>An integer divisible by the <strong>sum</strong> of its digits is said to be a <strong>Harshad</strong> number. You are given an integer <code>x</code>. Return<em> the sum of the digits </em>of<em> </em><code>x</code><em> </em>if<em> </em><code>x</code><em> </em>is a <strong>Harshad</strong> number, otherwise, return<em> </em><code>-1</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 18</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <p>The sum of digits of <code>x</code> is <code>9</code>. <code>18</code> is divisible by <code>9</code>. So <code>18</code> is a Harshad number and the answer is <code>9</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 23</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The sum of digits of <code>x</code> is <code>5</code>. <code>23</code> is not divisible by <code>5</code>. So <code>23</code> is not a Harshad number and the answer is <code>-1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 100</code></li> </ul>
Math
Python
class Solution: def sumOfTheDigitsOfHarshadNumber(self, x: int) -> int: s, y = 0, x while y: s += y % 10 y //= 10 return s if x % s == 0 else -1
3,099
Harshad Number
Easy
<p>An integer divisible by the <strong>sum</strong> of its digits is said to be a <strong>Harshad</strong> number. You are given an integer <code>x</code>. Return<em> the sum of the digits </em>of<em> </em><code>x</code><em> </em>if<em> </em><code>x</code><em> </em>is a <strong>Harshad</strong> number, otherwise, return<em> </em><code>-1</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 18</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <p>The sum of digits of <code>x</code> is <code>9</code>. <code>18</code> is divisible by <code>9</code>. So <code>18</code> is a Harshad number and the answer is <code>9</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 23</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>The sum of digits of <code>x</code> is <code>5</code>. <code>23</code> is not divisible by <code>5</code>. So <code>23</code> is not a Harshad number and the answer is <code>-1</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 100</code></li> </ul>
Math
TypeScript
function sumOfTheDigitsOfHarshadNumber(x: number): number { let s = 0; for (let y = x; y; y = Math.floor(y / 10)) { s += y % 10; } return x % s === 0 ? s : -1; }
3,100
Water Bottles II
Medium
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p> <p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p> <ul> <li>Drink any number of full water bottles turning them into empty bottles.</li> <li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li> </ul> <p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p> <p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> numBottles = 13, numExchange = 6 <strong>Output:</strong> 15 <strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> numBottles = 10, numExchange = 3 <strong>Output:</strong> 13 <strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numBottles &lt;= 100 </code></li> <li><code>1 &lt;= numExchange &lt;= 100</code></li> </ul>
Math; Simulation
C++
class Solution { public: int maxBottlesDrunk(int numBottles, int numExchange) { int ans = numBottles; while (numBottles >= numExchange) { numBottles -= numExchange; ++numExchange; ++ans; ++numBottles; } return ans; } };
3,100
Water Bottles II
Medium
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p> <p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p> <ul> <li>Drink any number of full water bottles turning them into empty bottles.</li> <li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li> </ul> <p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p> <p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> numBottles = 13, numExchange = 6 <strong>Output:</strong> 15 <strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> numBottles = 10, numExchange = 3 <strong>Output:</strong> 13 <strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numBottles &lt;= 100 </code></li> <li><code>1 &lt;= numExchange &lt;= 100</code></li> </ul>
Math; Simulation
Go
func maxBottlesDrunk(numBottles int, numExchange int) int { ans := numBottles for numBottles >= numExchange { numBottles -= numExchange numExchange++ ans++ numBottles++ } return ans }
3,100
Water Bottles II
Medium
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p> <p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p> <ul> <li>Drink any number of full water bottles turning them into empty bottles.</li> <li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li> </ul> <p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p> <p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> numBottles = 13, numExchange = 6 <strong>Output:</strong> 15 <strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> numBottles = 10, numExchange = 3 <strong>Output:</strong> 13 <strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numBottles &lt;= 100 </code></li> <li><code>1 &lt;= numExchange &lt;= 100</code></li> </ul>
Math; Simulation
Java
class Solution { public int maxBottlesDrunk(int numBottles, int numExchange) { int ans = numBottles; while (numBottles >= numExchange) { numBottles -= numExchange; ++numExchange; ++ans; ++numBottles; } return ans; } }
3,100
Water Bottles II
Medium
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p> <p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p> <ul> <li>Drink any number of full water bottles turning them into empty bottles.</li> <li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li> </ul> <p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p> <p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> numBottles = 13, numExchange = 6 <strong>Output:</strong> 15 <strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> numBottles = 10, numExchange = 3 <strong>Output:</strong> 13 <strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numBottles &lt;= 100 </code></li> <li><code>1 &lt;= numExchange &lt;= 100</code></li> </ul>
Math; Simulation
Python
class Solution: def maxBottlesDrunk(self, numBottles: int, numExchange: int) -> int: ans = numBottles while numBottles >= numExchange: numBottles -= numExchange numExchange += 1 ans += 1 numBottles += 1 return ans
3,100
Water Bottles II
Medium
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p> <p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p> <ul> <li>Drink any number of full water bottles turning them into empty bottles.</li> <li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li> </ul> <p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p> <p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> numBottles = 13, numExchange = 6 <strong>Output:</strong> 15 <strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> numBottles = 10, numExchange = 3 <strong>Output:</strong> 13 <strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numBottles &lt;= 100 </code></li> <li><code>1 &lt;= numExchange &lt;= 100</code></li> </ul>
Math; Simulation
Rust
impl Solution { pub fn max_bottles_drunk(mut num_bottles: i32, mut num_exchange: i32) -> i32 { let mut ans = num_bottles; while num_bottles >= num_exchange { num_bottles -= num_exchange; num_exchange += 1; ans += 1; num_bottles += 1; } ans } }
3,100
Water Bottles II
Medium
<p>You are given two integers <code>numBottles</code> and <code>numExchange</code>.</p> <p><code>numBottles</code> represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:</p> <ul> <li>Drink any number of full water bottles turning them into empty bottles.</li> <li>Exchange <code>numExchange</code> empty bottles with one full water bottle. Then, increase <code>numExchange</code> by one.</li> </ul> <p>Note that you cannot exchange multiple batches of empty bottles for the same value of <code>numExchange</code>. For example, if <code>numBottles == 3</code> and <code>numExchange == 1</code>, you cannot exchange <code>3</code> empty water bottles for <code>3</code> full bottles.</p> <p>Return <em>the <strong>maximum</strong> number of water bottles you can drink</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/exampleone1.png" style="width: 948px; height: 482px; padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> numBottles = 13, numExchange = 6 <strong>Output:</strong> 15 <strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3100.Water%20Bottles%20II/images/example231.png" style="width: 990px; height: 642px; padding: 10px; background: #fff; border-radius: .5rem;" /> <pre> <strong>Input:</strong> numBottles = 10, numExchange = 3 <strong>Output:</strong> 13 <strong>Explanation:</strong> The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= numBottles &lt;= 100 </code></li> <li><code>1 &lt;= numExchange &lt;= 100</code></li> </ul>
Math; Simulation
TypeScript
function maxBottlesDrunk(numBottles: number, numExchange: number): number { let ans = numBottles; while (numBottles >= numExchange) { numBottles -= numExchange; ++numExchange; ++ans; ++numBottles; } return ans; }
3,101
Count Alternating Subarrays
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>We call a <span data-keyword="subarray-nonempty">subarray</span> <strong>alternating</strong> if <strong>no</strong> two <strong>adjacent</strong> elements in the subarray have the <strong>same</strong> value.</p> <p>Return <em>the number of alternating subarrays in </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The following subarrays are alternating: <code>[0]</code>, <code>[1]</code>, <code>[1]</code>, <code>[1]</code>, and <code>[0,1]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Math
C++
class Solution { public: long long countAlternatingSubarrays(vector<int>& nums) { long long ans = 1, s = 1; for (int i = 1; i < nums.size(); ++i) { s = nums[i] != nums[i - 1] ? s + 1 : 1; ans += s; } return ans; } };
3,101
Count Alternating Subarrays
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>We call a <span data-keyword="subarray-nonempty">subarray</span> <strong>alternating</strong> if <strong>no</strong> two <strong>adjacent</strong> elements in the subarray have the <strong>same</strong> value.</p> <p>Return <em>the number of alternating subarrays in </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The following subarrays are alternating: <code>[0]</code>, <code>[1]</code>, <code>[1]</code>, <code>[1]</code>, and <code>[0,1]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Math
Go
func countAlternatingSubarrays(nums []int) int64 { ans, s := int64(1), int64(1) for i, x := range nums[1:] { if x != nums[i] { s++ } else { s = 1 } ans += s } return ans }
3,101
Count Alternating Subarrays
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>We call a <span data-keyword="subarray-nonempty">subarray</span> <strong>alternating</strong> if <strong>no</strong> two <strong>adjacent</strong> elements in the subarray have the <strong>same</strong> value.</p> <p>Return <em>the number of alternating subarrays in </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The following subarrays are alternating: <code>[0]</code>, <code>[1]</code>, <code>[1]</code>, <code>[1]</code>, and <code>[0,1]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Math
Java
class Solution { public long countAlternatingSubarrays(int[] nums) { long ans = 1, s = 1; for (int i = 1; i < nums.length; ++i) { s = nums[i] != nums[i - 1] ? s + 1 : 1; ans += s; } return ans; } }
3,101
Count Alternating Subarrays
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>We call a <span data-keyword="subarray-nonempty">subarray</span> <strong>alternating</strong> if <strong>no</strong> two <strong>adjacent</strong> elements in the subarray have the <strong>same</strong> value.</p> <p>Return <em>the number of alternating subarrays in </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The following subarrays are alternating: <code>[0]</code>, <code>[1]</code>, <code>[1]</code>, <code>[1]</code>, and <code>[0,1]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Math
Python
class Solution: def countAlternatingSubarrays(self, nums: List[int]) -> int: ans = s = 1 for a, b in pairwise(nums): s = s + 1 if a != b else 1 ans += s return ans
3,101
Count Alternating Subarrays
Medium
<p>You are given a <span data-keyword="binary-array">binary array</span> <code>nums</code>.</p> <p>We call a <span data-keyword="subarray-nonempty">subarray</span> <strong>alternating</strong> if <strong>no</strong> two <strong>adjacent</strong> elements in the subarray have the <strong>same</strong> value.</p> <p>Return <em>the number of alternating subarrays in </em><code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>The following subarrays are alternating: <code>[0]</code>, <code>[1]</code>, <code>[1]</code>, <code>[1]</code>, and <code>[0,1]</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,0,1,0]</span></p> <p><strong>Output:</strong> <span class="example-io">10</span></p> <p><strong>Explanation:</strong></p> <p>Every subarray of the array is alternating. There are 10 possible subarrays that we can choose.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li> </ul>
Array; Math
TypeScript
function countAlternatingSubarrays(nums: number[]): number { let [ans, s] = [1, 1]; for (let i = 1; i < nums.length; ++i) { s = nums[i] !== nums[i - 1] ? s + 1 : 1; ans += s; } return ans; }
3,102
Minimize Manhattan Distances
Hard
<p>You are given an array <code>points</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>The distance between two points is defined as their <span data-keyword="manhattan-distance">Manhattan distance</span>.</p> <p>Return <em>the <strong>minimum</strong> possible value for <strong>maximum</strong> distance between any two points by removing exactly one point</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[3,10],[5,15],[10,2],[4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The maximum distance after removing each point is the following:</p> <ul> <li>After removing the 0<sup>th</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li> <li>After removing the 1<sup>st</sup> point the maximum distance is between points (3, 10) and (10, 2), which is <code>|3 - 10| + |10 - 2| = 15</code>.</li> <li>After removing the 2<sup>nd</sup> point the maximum distance is between points (5, 15) and (4, 4), which is <code>|5 - 4| + |15 - 4| = 12</code>.</li> <li>After removing the 3<sup>rd</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li> </ul> <p>12 is the minimum possible maximum distance between any two points after removing exactly one point.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Removing any of the points results in the maximum distance between any two points of 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= points.length &lt;= 10<sup>5</sup></code></li> <li><code>points[i].length == 2</code></li> <li><code>1 &lt;= points[i][0], points[i][1] &lt;= 10<sup>8</sup></code></li> </ul>
Geometry; Array; Math; Ordered Set; Sorting
C++
class Solution { public: int minimumDistance(vector<vector<int>>& points) { multiset<int> st1; multiset<int> st2; for (auto& p : points) { int x = p[0], y = p[1]; st1.insert(x + y); st2.insert(x - y); } int ans = INT_MAX; for (auto& p : points) { int x = p[0], y = p[1]; st1.erase(st1.find(x + y)); st2.erase(st2.find(x - y)); ans = min(ans, max(*st1.rbegin() - *st1.begin(), *st2.rbegin() - *st2.begin())); st1.insert(x + y); st2.insert(x - y); } return ans; } };
3,102
Minimize Manhattan Distances
Hard
<p>You are given an array <code>points</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>The distance between two points is defined as their <span data-keyword="manhattan-distance">Manhattan distance</span>.</p> <p>Return <em>the <strong>minimum</strong> possible value for <strong>maximum</strong> distance between any two points by removing exactly one point</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[3,10],[5,15],[10,2],[4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The maximum distance after removing each point is the following:</p> <ul> <li>After removing the 0<sup>th</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li> <li>After removing the 1<sup>st</sup> point the maximum distance is between points (3, 10) and (10, 2), which is <code>|3 - 10| + |10 - 2| = 15</code>.</li> <li>After removing the 2<sup>nd</sup> point the maximum distance is between points (5, 15) and (4, 4), which is <code>|5 - 4| + |15 - 4| = 12</code>.</li> <li>After removing the 3<sup>rd</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li> </ul> <p>12 is the minimum possible maximum distance between any two points after removing exactly one point.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Removing any of the points results in the maximum distance between any two points of 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= points.length &lt;= 10<sup>5</sup></code></li> <li><code>points[i].length == 2</code></li> <li><code>1 &lt;= points[i][0], points[i][1] &lt;= 10<sup>8</sup></code></li> </ul>
Geometry; Array; Math; Ordered Set; Sorting
Go
func minimumDistance(points [][]int) int { st1 := redblacktree.New[int, int]() st2 := redblacktree.New[int, int]() merge := func(st *redblacktree.Tree[int, int], x, v int) { c, _ := st.Get(x) if c+v == 0 { st.Remove(x) } else { st.Put(x, c+v) } } for _, p := range points { x, y := p[0], p[1] merge(st1, x+y, 1) merge(st2, x-y, 1) } ans := math.MaxInt for _, p := range points { x, y := p[0], p[1] merge(st1, x+y, -1) merge(st2, x-y, -1) ans = min(ans, max(st1.Right().Key-st1.Left().Key, st2.Right().Key-st2.Left().Key)) merge(st1, x+y, 1) merge(st2, x-y, 1) } return ans }
3,102
Minimize Manhattan Distances
Hard
<p>You are given an array <code>points</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>The distance between two points is defined as their <span data-keyword="manhattan-distance">Manhattan distance</span>.</p> <p>Return <em>the <strong>minimum</strong> possible value for <strong>maximum</strong> distance between any two points by removing exactly one point</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[3,10],[5,15],[10,2],[4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The maximum distance after removing each point is the following:</p> <ul> <li>After removing the 0<sup>th</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li> <li>After removing the 1<sup>st</sup> point the maximum distance is between points (3, 10) and (10, 2), which is <code>|3 - 10| + |10 - 2| = 15</code>.</li> <li>After removing the 2<sup>nd</sup> point the maximum distance is between points (5, 15) and (4, 4), which is <code>|5 - 4| + |15 - 4| = 12</code>.</li> <li>After removing the 3<sup>rd</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li> </ul> <p>12 is the minimum possible maximum distance between any two points after removing exactly one point.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Removing any of the points results in the maximum distance between any two points of 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= points.length &lt;= 10<sup>5</sup></code></li> <li><code>points[i].length == 2</code></li> <li><code>1 &lt;= points[i][0], points[i][1] &lt;= 10<sup>8</sup></code></li> </ul>
Geometry; Array; Math; Ordered Set; Sorting
Java
class Solution { public int minimumDistance(int[][] points) { TreeMap<Integer, Integer> tm1 = new TreeMap<>(); TreeMap<Integer, Integer> tm2 = new TreeMap<>(); for (int[] p : points) { int x = p[0], y = p[1]; tm1.merge(x + y, 1, Integer::sum); tm2.merge(x - y, 1, Integer::sum); } int ans = Integer.MAX_VALUE; for (int[] p : points) { int x = p[0], y = p[1]; if (tm1.merge(x + y, -1, Integer::sum) == 0) { tm1.remove(x + y); } if (tm2.merge(x - y, -1, Integer::sum) == 0) { tm2.remove(x - y); } ans = Math.min( ans, Math.max(tm1.lastKey() - tm1.firstKey(), tm2.lastKey() - tm2.firstKey())); tm1.merge(x + y, 1, Integer::sum); tm2.merge(x - y, 1, Integer::sum); } return ans; } }
3,102
Minimize Manhattan Distances
Hard
<p>You are given an array <code>points</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>The distance between two points is defined as their <span data-keyword="manhattan-distance">Manhattan distance</span>.</p> <p>Return <em>the <strong>minimum</strong> possible value for <strong>maximum</strong> distance between any two points by removing exactly one point</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[3,10],[5,15],[10,2],[4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The maximum distance after removing each point is the following:</p> <ul> <li>After removing the 0<sup>th</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li> <li>After removing the 1<sup>st</sup> point the maximum distance is between points (3, 10) and (10, 2), which is <code>|3 - 10| + |10 - 2| = 15</code>.</li> <li>After removing the 2<sup>nd</sup> point the maximum distance is between points (5, 15) and (4, 4), which is <code>|5 - 4| + |15 - 4| = 12</code>.</li> <li>After removing the 3<sup>rd</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li> </ul> <p>12 is the minimum possible maximum distance between any two points after removing exactly one point.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Removing any of the points results in the maximum distance between any two points of 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= points.length &lt;= 10<sup>5</sup></code></li> <li><code>points[i].length == 2</code></li> <li><code>1 &lt;= points[i][0], points[i][1] &lt;= 10<sup>8</sup></code></li> </ul>
Geometry; Array; Math; Ordered Set; Sorting
Python
class Solution: def minimumDistance(self, points: List[List[int]]) -> int: sl1 = SortedList() sl2 = SortedList() for x, y in points: sl1.add(x + y) sl2.add(x - y) ans = inf for x, y in points: sl1.remove(x + y) sl2.remove(x - y) ans = min(ans, max(sl1[-1] - sl1[0], sl2[-1] - sl2[0])) sl1.add(x + y) sl2.add(x - y) return ans
3,102
Minimize Manhattan Distances
Hard
<p>You are given an array <code>points</code> representing integer coordinates of some points on a 2D plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p> <p>The distance between two points is defined as their <span data-keyword="manhattan-distance">Manhattan distance</span>.</p> <p>Return <em>the <strong>minimum</strong> possible value for <strong>maximum</strong> distance between any two points by removing exactly one point</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[3,10],[5,15],[10,2],[4,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The maximum distance after removing each point is the following:</p> <ul> <li>After removing the 0<sup>th</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li> <li>After removing the 1<sup>st</sup> point the maximum distance is between points (3, 10) and (10, 2), which is <code>|3 - 10| + |10 - 2| = 15</code>.</li> <li>After removing the 2<sup>nd</sup> point the maximum distance is between points (5, 15) and (4, 4), which is <code>|5 - 4| + |15 - 4| = 12</code>.</li> <li>After removing the 3<sup>rd</sup> point the maximum distance is between points (5, 15) and (10, 2), which is <code>|5 - 10| + |15 - 2| = 18</code>.</li> </ul> <p>12 is the minimum possible maximum distance between any two points after removing exactly one point.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">points = [[1,1],[1,1],[1,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Removing any of the points results in the maximum distance between any two points of 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= points.length &lt;= 10<sup>5</sup></code></li> <li><code>points[i].length == 2</code></li> <li><code>1 &lt;= points[i][0], points[i][1] &lt;= 10<sup>8</sup></code></li> </ul>
Geometry; Array; Math; Ordered Set; Sorting
TypeScript
function minimumDistance(points: number[][]): number { const st1 = new TreapMultiSet<number>(); const st2 = new TreapMultiSet<number>(); for (const [x, y] of points) { st1.add(x + y); st2.add(x - y); } let ans = Infinity; for (const [x, y] of points) { st1.delete(x + y); st2.delete(x - y); ans = Math.min(ans, Math.max(st1.last() - st1.first(), st2.last() - st2.first())); st1.add(x + y); st2.add(x - y); } return ans; } type CompareFunction<T, R extends 'number' | 'boolean'> = ( a: T, b: T, ) => R extends 'number' ? number : boolean; interface ITreapMultiSet<T> extends Iterable<T> { add: (...value: T[]) => this; has: (value: T) => boolean; delete: (value: T) => void; bisectLeft: (value: T) => number; bisectRight: (value: T) => number; indexOf: (value: T) => number; lastIndexOf: (value: T) => number; at: (index: number) => T | undefined; first: () => T | undefined; last: () => T | undefined; lower: (value: T) => T | undefined; higher: (value: T) => T | undefined; floor: (value: T) => T | undefined; ceil: (value: T) => T | undefined; shift: () => T | undefined; pop: (index?: number) => T | undefined; count: (value: T) => number; keys: () => IterableIterator<T>; values: () => IterableIterator<T>; rvalues: () => IterableIterator<T>; entries: () => IterableIterator<[number, T]>; readonly size: number; } class TreapNode<T = number> { value: T; count: number; size: number; priority: number; left: TreapNode<T> | null; right: TreapNode<T> | null; constructor(value: T) { this.value = value; this.count = 1; this.size = 1; this.priority = Math.random(); this.left = null; this.right = null; } static getSize(node: TreapNode<any> | null): number { return node?.size ?? 0; } static getFac(node: TreapNode<any> | null): number { return node?.priority ?? 0; } pushUp(): void { let tmp = this.count; tmp += TreapNode.getSize(this.left); tmp += TreapNode.getSize(this.right); this.size = tmp; } rotateRight(): TreapNode<T> { // eslint-disable-next-line @typescript-eslint/no-this-alias let node: TreapNode<T> = this; const left = node.left; node.left = left?.right ?? null; left && (left.right = node); left && (node = left); node.right?.pushUp(); node.pushUp(); return node; } rotateLeft(): TreapNode<T> { // eslint-disable-next-line @typescript-eslint/no-this-alias let node: TreapNode<T> = this; const right = node.right; node.right = right?.left ?? null; right && (right.left = node); right && (node = right); node.left?.pushUp(); node.pushUp(); return node; } } class TreapMultiSet<T = number> implements ITreapMultiSet<T> { private readonly root: TreapNode<T>; private readonly compareFn: CompareFunction<T, 'number'>; private readonly leftBound: T; private readonly rightBound: T; constructor(compareFn?: CompareFunction<T, 'number'>); constructor(compareFn: CompareFunction<T, 'number'>, leftBound: T, rightBound: T); constructor( compareFn: CompareFunction<T, any> = (a: any, b: any) => a - b, leftBound: any = -Infinity, rightBound: any = Infinity, ) { this.root = new TreapNode<T>(rightBound); this.root.priority = Infinity; this.root.left = new TreapNode<T>(leftBound); this.root.left.priority = -Infinity; this.root.pushUp(); this.leftBound = leftBound; this.rightBound = rightBound; this.compareFn = compareFn; } get size(): number { return this.root.size - 2; } get height(): number { const getHeight = (node: TreapNode<T> | null): number => { if (node == null) return 0; return 1 + Math.max(getHeight(node.left), getHeight(node.right)); }; return getHeight(this.root); } /** * * @complexity `O(logn)` * @description Returns true if value is a member. */ has(value: T): boolean { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): boolean => { if (node == null) return false; if (compare(node.value, value) === 0) return true; if (compare(node.value, value) < 0) return dfs(node.right, value); return dfs(node.left, value); }; return dfs(this.root, value); } /** * * @complexity `O(logn)` * @description Add value to sorted set. */ add(...values: T[]): this { const compare = this.compareFn; const dfs = ( node: TreapNode<T> | null, value: T, parent: TreapNode<T>, direction: 'left' | 'right', ): void => { if (node == null) return; if (compare(node.value, value) === 0) { node.count++; node.pushUp(); } else if (compare(node.value, value) > 0) { if (node.left) { dfs(node.left, value, node, 'left'); } else { node.left = new TreapNode(value); node.pushUp(); } if (TreapNode.getFac(node.left) > node.priority) { parent[direction] = node.rotateRight(); } } else if (compare(node.value, value) < 0) { if (node.right) { dfs(node.right, value, node, 'right'); } else { node.right = new TreapNode(value); node.pushUp(); } if (TreapNode.getFac(node.right) > node.priority) { parent[direction] = node.rotateLeft(); } } parent.pushUp(); }; values.forEach(value => dfs(this.root.left, value, this.root, 'left')); return this; } /** * * @complexity `O(logn)` * @description Remove value from sorted set if it is a member. * If value is not a member, do nothing. */ delete(value: T): void { const compare = this.compareFn; const dfs = ( node: TreapNode<T> | null, value: T, parent: TreapNode<T>, direction: 'left' | 'right', ): void => { if (node == null) return; if (compare(node.value, value) === 0) { if (node.count > 1) { node.count--; node?.pushUp(); } else if (node.left == null && node.right == null) { parent[direction] = null; } else { // 旋到根节点 if ( node.right == null || TreapNode.getFac(node.left) > TreapNode.getFac(node.right) ) { parent[direction] = node.rotateRight(); dfs(parent[direction]?.right ?? null, value, parent[direction]!, 'right'); } else { parent[direction] = node.rotateLeft(); dfs(parent[direction]?.left ?? null, value, parent[direction]!, 'left'); } } } else if (compare(node.value, value) > 0) { dfs(node.left, value, node, 'left'); } else if (compare(node.value, value) < 0) { dfs(node.right, value, node, 'right'); } parent?.pushUp(); }; dfs(this.root.left, value, this.root, 'left'); } /** * * @complexity `O(logn)` * @description Returns an index to insert value in the sorted set. * If the value is already present, the insertion point will be before (to the left of) any existing values. */ bisectLeft(value: T): number { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) { return TreapNode.getSize(node.left); } else if (compare(node.value, value) > 0) { return dfs(node.left, value); } else if (compare(node.value, value) < 0) { return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; } return 0; }; return dfs(this.root, value) - 1; } /** * * @complexity `O(logn)` * @description Returns an index to insert value in the sorted set. * If the value is already present, the insertion point will be before (to the right of) any existing values. */ bisectRight(value: T): number { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) { return TreapNode.getSize(node.left) + node.count; } else if (compare(node.value, value) > 0) { return dfs(node.left, value); } else if (compare(node.value, value) < 0) { return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; } return 0; }; return dfs(this.root, value) - 1; } /** * * @complexity `O(logn)` * @description Returns the index of the first occurrence of a value in the set, or -1 if it is not present. */ indexOf(value: T): number { const compare = this.compareFn; let isExist = false; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) { isExist = true; return TreapNode.getSize(node.left); } else if (compare(node.value, value) > 0) { return dfs(node.left, value); } else if (compare(node.value, value) < 0) { return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; } return 0; }; const res = dfs(this.root, value) - 1; return isExist ? res : -1; } /** * * @complexity `O(logn)` * @description Returns the index of the last occurrence of a value in the set, or -1 if it is not present. */ lastIndexOf(value: T): number { const compare = this.compareFn; let isExist = false; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) { isExist = true; return TreapNode.getSize(node.left) + node.count - 1; } else if (compare(node.value, value) > 0) { return dfs(node.left, value); } else if (compare(node.value, value) < 0) { return dfs(node.right, value) + TreapNode.getSize(node.left) + node.count; } return 0; }; const res = dfs(this.root, value) - 1; return isExist ? res : -1; } /** * * @complexity `O(logn)` * @description Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. */ at(index: number): T | undefined { if (index < 0) index += this.size; if (index < 0 || index >= this.size) return undefined; const dfs = (node: TreapNode<T> | null, rank: number): T | undefined => { if (node == null) return undefined; if (TreapNode.getSize(node.left) >= rank) { return dfs(node.left, rank); } else if (TreapNode.getSize(node.left) + node.count >= rank) { return node.value; } else { return dfs(node.right, rank - TreapNode.getSize(node.left) - node.count); } }; const res = dfs(this.root, index + 2); return ([this.leftBound, this.rightBound] as any[]).includes(res) ? undefined : res; } /** * * @complexity `O(logn)` * @description Find and return the element less than `val`, return `undefined` if no such element found. */ lower(value: T): T | undefined { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): T | undefined => { if (node == null) return undefined; if (compare(node.value, value) >= 0) return dfs(node.left, value); const tmp = dfs(node.right, value); if (tmp == null || compare(node.value, tmp) > 0) { return node.value; } else { return tmp; } }; const res = dfs(this.root, value) as any; return res === this.leftBound ? undefined : res; } /** * * @complexity `O(logn)` * @description Find and return the element greater than `val`, return `undefined` if no such element found. */ higher(value: T): T | undefined { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): T | undefined => { if (node == null) return undefined; if (compare(node.value, value) <= 0) return dfs(node.right, value); const tmp = dfs(node.left, value); if (tmp == null || compare(node.value, tmp) < 0) { return node.value; } else { return tmp; } }; const res = dfs(this.root, value) as any; return res === this.rightBound ? undefined : res; } /** * * @complexity `O(logn)` * @description Find and return the element less than or equal to `val`, return `undefined` if no such element found. */ floor(value: T): T | undefined { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): T | undefined => { if (node == null) return undefined; if (compare(node.value, value) === 0) return node.value; if (compare(node.value, value) >= 0) return dfs(node.left, value); const tmp = dfs(node.right, value); if (tmp == null || compare(node.value, tmp) > 0) { return node.value; } else { return tmp; } }; const res = dfs(this.root, value) as any; return res === this.leftBound ? undefined : res; } /** * * @complexity `O(logn)` * @description Find and return the element greater than or equal to `val`, return `undefined` if no such element found. */ ceil(value: T): T | undefined { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): T | undefined => { if (node == null) return undefined; if (compare(node.value, value) === 0) return node.value; if (compare(node.value, value) <= 0) return dfs(node.right, value); const tmp = dfs(node.left, value); if (tmp == null || compare(node.value, tmp) < 0) { return node.value; } else { return tmp; } }; const res = dfs(this.root, value) as any; return res === this.rightBound ? undefined : res; } /** * @complexity `O(logn)` * @description * Returns the last element from set. * If the set is empty, undefined is returned. */ first(): T | undefined { const iter = this.inOrder(); iter.next(); const res = iter.next().value; return res === this.rightBound ? undefined : res; } /** * @complexity `O(logn)` * @description * Returns the last element from set. * If the set is empty, undefined is returned . */ last(): T | undefined { const iter = this.reverseInOrder(); iter.next(); const res = iter.next().value; return res === this.leftBound ? undefined : res; } /** * @complexity `O(logn)` * @description * Removes the first element from an set and returns it. * If the set is empty, undefined is returned and the set is not modified. */ shift(): T | undefined { const first = this.first(); if (first === undefined) return undefined; this.delete(first); return first; } /** * @complexity `O(logn)` * @description * Removes the last element from an set and returns it. * If the set is empty, undefined is returned and the set is not modified. */ pop(index?: number): T | undefined { if (index == null) { const last = this.last(); if (last === undefined) return undefined; this.delete(last); return last; } const toDelete = this.at(index); if (toDelete == null) return; this.delete(toDelete); return toDelete; } /** * * @complexity `O(logn)` * @description * Returns number of occurrences of value in the sorted set. */ count(value: T): number { const compare = this.compareFn; const dfs = (node: TreapNode<T> | null, value: T): number => { if (node == null) return 0; if (compare(node.value, value) === 0) return node.count; if (compare(node.value, value) < 0) return dfs(node.right, value); return dfs(node.left, value); }; return dfs(this.root, value); } *[Symbol.iterator](): Generator<T, any, any> { yield* this.values(); } /** * @description * Returns an iterable of keys in the set. */ *keys(): Generator<T, any, any> { yield* this.values(); } /** * @description * Returns an iterable of values in the set. */ *values(): Generator<T, any, any> { const iter = this.inOrder(); iter.next(); const steps = this.size; for (let _ = 0; _ < steps; _++) { yield iter.next().value; } } /** * @description * Returns a generator for reversed order traversing the set. */ *rvalues(): Generator<T, any, any> { const iter = this.reverseInOrder(); iter.next(); const steps = this.size; for (let _ = 0; _ < steps; _++) { yield iter.next().value; } } /** * @description * Returns an iterable of key, value pairs for every entry in the set. */ *entries(): IterableIterator<[number, T]> { const iter = this.inOrder(); iter.next(); const steps = this.size; for (let i = 0; i < steps; i++) { yield [i, iter.next().value]; } } private *inOrder(root: TreapNode<T> | null = this.root): Generator<T, any, any> { if (root == null) return; yield* this.inOrder(root.left); const count = root.count; for (let _ = 0; _ < count; _++) { yield root.value; } yield* this.inOrder(root.right); } private *reverseInOrder(root: TreapNode<T> | null = this.root): Generator<T, any, any> { if (root == null) return; yield* this.reverseInOrder(root.right); const count = root.count; for (let _ = 0; _ < count; _++) { yield root.value; } yield* this.reverseInOrder(root.left); } }
3,103
Find Trending Hashtags II
Hard
<p>Table: <code>Tweets</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | user_id | int | | tweet_id | int | | tweet_date | date | | tweet | varchar | +-------------+---------+ tweet_id is the primary key (column with unique values) for this table. Each row of this table contains user_id, tweet_id, tweet_date and tweet. It is guaranteed that all tweet_date are valid dates in February 2024. </pre> <p>Write a solution to find the <strong>top</strong> <code>3</code> trending <strong>hashtags</strong> in <strong>February</strong> <code>2024</code>. Every tweet may contain <strong>several</strong> <strong>hashtags</strong>.</p> <p>Return <em>the result table ordered by count of hashtag, hashtag in </em><strong>descending</strong><em> order.</em></p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Tweets table:</p> <pre class="example-io"> +---------+----------+------------------------------------------------------------+------------+ | user_id | tweet_id | tweet | tweet_date | +---------+----------+------------------------------------------------------------+------------+ | 135 | 13 | Enjoying a great start to the day. #HappyDay #MorningVibes | 2024-02-01 | | 136 | 14 | Another #HappyDay with good vibes! #FeelGood | 2024-02-03 | | 137 | 15 | Productivity peaks! #WorkLife #ProductiveDay | 2024-02-04 | | 138 | 16 | Exploring new tech frontiers. #TechLife #Innovation | 2024-02-04 | | 139 | 17 | Gratitude for today&#39;s moments. #HappyDay #Thankful | 2024-02-05 | | 140 | 18 | Innovation drives us. #TechLife #FutureTech | 2024-02-07 | | 141 | 19 | Connecting with nature&#39;s serenity. #Nature #Peaceful | 2024-02-09 | +---------+----------+------------------------------------------------------------+------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-----------+-------+ | hashtag | count | +-----------+-------+ | #HappyDay | 3 | | #TechLife | 2 | | #WorkLife | 1 | +-----------+-------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>#HappyDay:</strong> Appeared in tweet IDs 13, 14, and 17, with a total count of 3 mentions.</li> <li><strong>#TechLife:</strong> Appeared in tweet IDs 16 and 18, with a total count of 2 mentions.</li> <li><strong>#WorkLife:</strong> Appeared in tweet ID 15, with a total count of 1 mention.</li> </ul> <p><b>Note:</b> Output table is sorted in descending order by count and hashtag respectively.</p> </div>
Database
Python
import pandas as pd def find_trending_hashtags(tweets: pd.DataFrame) -> pd.DataFrame: # Filter tweets for February 2024 tweets_feb_2024 = tweets[tweets["tweet_date"].between("2024-02-01", "2024-02-29")] # Extract hashtags from tweets hashtags = tweets_feb_2024["tweet"].str.findall(r"#\w+") # Flatten list of hashtags all_hashtags = [tag for sublist in hashtags for tag in sublist] # Count occurrences of each hashtag hashtag_counts = pd.Series(all_hashtags).value_counts().reset_index() hashtag_counts.columns = ["hashtag", "count"] # Sort by count of hashtag in descending order hashtag_counts = hashtag_counts.sort_values( by=["count", "hashtag"], ascending=[False, False] ) # Get top 3 trending hashtags top_3_hashtags = hashtag_counts.head(3) return top_3_hashtags
3,104
Find Longest Self-Contained Substring
Hard
<p>Given a string <code>s</code>, your task is to find the length of the <strong>longest self-contained</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code>.</p> <p>A substring <code>t</code> of a string <code>s</code> is called <strong>self-contained </strong>if <code>t != s</code> and for every character in <code>t</code>, it doesn&#39;t exist in the <em>rest</em> of <code>s</code>.</p> <p>Return the length of the <em>longest<strong> </strong>self-contained </em>substring of <code>s</code> if it exists, otherwise, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong><br /> Let&#39;s check the substring <code>&quot;bb&quot;</code>. You can see that no other <code>&quot;b&quot;</code> is outside of this substring. Hence the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abab&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> Every substring we choose does not satisfy the described property (there is some character which is inside and outside of that substring). So the answer would be -1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abacd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong><br /> Let&#39;s check the substring <code>&quot;<span class="example-io">abac</span>&quot;</code>. There is only one character outside of this substring and that is <code>&quot;d&quot;</code>. There is no <code>&quot;d&quot;</code> inside the chosen substring, so it satisfies the condition and the answer is 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Binary Search; Prefix Sum
C++
class Solution { public: int maxSubstringLength(string s) { vector<int> first(26, -1); vector<int> last(26); int n = s.length(); for (int i = 0; i < n; ++i) { int j = s[i] - 'a'; if (first[j] == -1) { first[j] = i; } last[j] = i; } int ans = -1; for (int k = 0; k < 26; ++k) { int i = first[k]; if (i == -1) { continue; } int mx = last[k]; for (int j = i; j < n; ++j) { int a = first[s[j] - 'a']; int b = last[s[j] - 'a']; if (a < i) { break; } mx = max(mx, b); if (mx == j && j - i + 1 < n) { ans = max(ans, j - i + 1); } } } return ans; } };
3,104
Find Longest Self-Contained Substring
Hard
<p>Given a string <code>s</code>, your task is to find the length of the <strong>longest self-contained</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code>.</p> <p>A substring <code>t</code> of a string <code>s</code> is called <strong>self-contained </strong>if <code>t != s</code> and for every character in <code>t</code>, it doesn&#39;t exist in the <em>rest</em> of <code>s</code>.</p> <p>Return the length of the <em>longest<strong> </strong>self-contained </em>substring of <code>s</code> if it exists, otherwise, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong><br /> Let&#39;s check the substring <code>&quot;bb&quot;</code>. You can see that no other <code>&quot;b&quot;</code> is outside of this substring. Hence the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abab&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> Every substring we choose does not satisfy the described property (there is some character which is inside and outside of that substring). So the answer would be -1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abacd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong><br /> Let&#39;s check the substring <code>&quot;<span class="example-io">abac</span>&quot;</code>. There is only one character outside of this substring and that is <code>&quot;d&quot;</code>. There is no <code>&quot;d&quot;</code> inside the chosen substring, so it satisfies the condition and the answer is 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Binary Search; Prefix Sum
Go
func maxSubstringLength(s string) int { first := [26]int{} last := [26]int{} for i := range first { first[i] = -1 } n := len(s) for i, c := range s { j := int(c - 'a') if first[j] == -1 { first[j] = i } last[j] = i } ans := -1 for k := 0; k < 26; k++ { i := first[k] if i == -1 { continue } mx := last[k] for j := i; j < n; j++ { a, b := first[s[j]-'a'], last[s[j]-'a'] if a < i { break } mx = max(mx, b) if mx == j && j-i+1 < n { ans = max(ans, j-i+1) } } } return ans }
3,104
Find Longest Self-Contained Substring
Hard
<p>Given a string <code>s</code>, your task is to find the length of the <strong>longest self-contained</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code>.</p> <p>A substring <code>t</code> of a string <code>s</code> is called <strong>self-contained </strong>if <code>t != s</code> and for every character in <code>t</code>, it doesn&#39;t exist in the <em>rest</em> of <code>s</code>.</p> <p>Return the length of the <em>longest<strong> </strong>self-contained </em>substring of <code>s</code> if it exists, otherwise, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong><br /> Let&#39;s check the substring <code>&quot;bb&quot;</code>. You can see that no other <code>&quot;b&quot;</code> is outside of this substring. Hence the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abab&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> Every substring we choose does not satisfy the described property (there is some character which is inside and outside of that substring). So the answer would be -1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abacd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong><br /> Let&#39;s check the substring <code>&quot;<span class="example-io">abac</span>&quot;</code>. There is only one character outside of this substring and that is <code>&quot;d&quot;</code>. There is no <code>&quot;d&quot;</code> inside the chosen substring, so it satisfies the condition and the answer is 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Binary Search; Prefix Sum
Java
class Solution { public int maxSubstringLength(String s) { int[] first = new int[26]; int[] last = new int[26]; Arrays.fill(first, -1); int n = s.length(); for (int i = 0; i < n; ++i) { int j = s.charAt(i) - 'a'; if (first[j] == -1) { first[j] = i; } last[j] = i; } int ans = -1; for (int k = 0; k < 26; ++k) { int i = first[k]; if (i == -1) { continue; } int mx = last[k]; for (int j = i; j < n; ++j) { int a = first[s.charAt(j) - 'a']; int b = last[s.charAt(j) - 'a']; if (a < i) { break; } mx = Math.max(mx, b); if (mx == j && j - i + 1 < n) { ans = Math.max(ans, j - i + 1); } } } return ans; } }
3,104
Find Longest Self-Contained Substring
Hard
<p>Given a string <code>s</code>, your task is to find the length of the <strong>longest self-contained</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code>.</p> <p>A substring <code>t</code> of a string <code>s</code> is called <strong>self-contained </strong>if <code>t != s</code> and for every character in <code>t</code>, it doesn&#39;t exist in the <em>rest</em> of <code>s</code>.</p> <p>Return the length of the <em>longest<strong> </strong>self-contained </em>substring of <code>s</code> if it exists, otherwise, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong><br /> Let&#39;s check the substring <code>&quot;bb&quot;</code>. You can see that no other <code>&quot;b&quot;</code> is outside of this substring. Hence the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abab&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> Every substring we choose does not satisfy the described property (there is some character which is inside and outside of that substring). So the answer would be -1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abacd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong><br /> Let&#39;s check the substring <code>&quot;<span class="example-io">abac</span>&quot;</code>. There is only one character outside of this substring and that is <code>&quot;d&quot;</code>. There is no <code>&quot;d&quot;</code> inside the chosen substring, so it satisfies the condition and the answer is 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Binary Search; Prefix Sum
Python
class Solution: def maxSubstringLength(self, s: str) -> int: first, last = {}, {} for i, c in enumerate(s): if c not in first: first[c] = i last[c] = i ans, n = -1, len(s) for c, i in first.items(): mx = last[c] for j in range(i, n): a, b = first[s[j]], last[s[j]] if a < i: break mx = max(mx, b) if mx == j and j - i + 1 < n: ans = max(ans, j - i + 1) return ans
3,104
Find Longest Self-Contained Substring
Hard
<p>Given a string <code>s</code>, your task is to find the length of the <strong>longest self-contained</strong> <span data-keyword="substring-nonempty">substring</span> of <code>s</code>.</p> <p>A substring <code>t</code> of a string <code>s</code> is called <strong>self-contained </strong>if <code>t != s</code> and for every character in <code>t</code>, it doesn&#39;t exist in the <em>rest</em> of <code>s</code>.</p> <p>Return the length of the <em>longest<strong> </strong>self-contained </em>substring of <code>s</code> if it exists, otherwise, return -1.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong><br /> Let&#39;s check the substring <code>&quot;bb&quot;</code>. You can see that no other <code>&quot;b&quot;</code> is outside of this substring. Hence the answer is 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abab&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong><br /> Every substring we choose does not satisfy the described property (there is some character which is inside and outside of that substring). So the answer would be -1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abacd&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong><br /> Let&#39;s check the substring <code>&quot;<span class="example-io">abac</span>&quot;</code>. There is only one character outside of this substring and that is <code>&quot;d&quot;</code>. There is no <code>&quot;d&quot;</code> inside the chosen substring, so it satisfies the condition and the answer is 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Hash Table; String; Binary Search; Prefix Sum
TypeScript
function maxSubstringLength(s: string): number { const first: number[] = Array(26).fill(-1); const last: number[] = Array(26).fill(0); const n = s.length; for (let i = 0; i < n; ++i) { const j = s.charCodeAt(i) - 97; if (first[j] === -1) { first[j] = i; } last[j] = i; } let ans = -1; for (let k = 0; k < 26; ++k) { const i = first[k]; if (i === -1) { continue; } let mx = last[k]; for (let j = i; j < n; ++j) { const a = first[s.charCodeAt(j) - 97]; if (a < i) { break; } const b = last[s.charCodeAt(j) - 97]; mx = Math.max(mx, b); if (mx === j && j - i + 1 < n) { ans = Math.max(ans, j - i + 1); } } } return ans; }
3,105
Longest Strictly Increasing or Strictly Decreasing Subarray
Easy
<p>You are given an array of integers <code>nums</code>. Return <em>the length of the <strong>longest</strong> <span data-keyword="subarray-nonempty">subarray</span> of </em><code>nums</code><em> which is either <strong><span data-keyword="strictly-increasing-array">strictly increasing</span></strong> or <strong><span data-keyword="strictly-decreasing-array">strictly decreasing</span></strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, and <code>[1,4]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, <code>[3,2]</code>, and <code>[4,3]</code>.</p> <p>Hence, we return <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,3,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p> <p>Hence, we return <code>1</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, and <code>[1]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, <code>[1]</code>, <code>[3,2]</code>, <code>[2,1]</code>, and <code>[3,2,1]</code>.</p> <p>Hence, we return <code>3</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array
C++
class Solution { public: int longestMonotonicSubarray(vector<int>& nums) { int ans = 1; for (int i = 1, t = 1; i < nums.size(); ++i) { if (nums[i - 1] < nums[i]) { ans = max(ans, ++t); } else { t = 1; } } for (int i = 1, t = 1; i < nums.size(); ++i) { if (nums[i - 1] > nums[i]) { ans = max(ans, ++t); } else { t = 1; } } return ans; } };
3,105
Longest Strictly Increasing or Strictly Decreasing Subarray
Easy
<p>You are given an array of integers <code>nums</code>. Return <em>the length of the <strong>longest</strong> <span data-keyword="subarray-nonempty">subarray</span> of </em><code>nums</code><em> which is either <strong><span data-keyword="strictly-increasing-array">strictly increasing</span></strong> or <strong><span data-keyword="strictly-decreasing-array">strictly decreasing</span></strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, and <code>[1,4]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, <code>[3,2]</code>, and <code>[4,3]</code>.</p> <p>Hence, we return <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,3,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p> <p>Hence, we return <code>1</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, and <code>[1]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, <code>[1]</code>, <code>[3,2]</code>, <code>[2,1]</code>, and <code>[3,2,1]</code>.</p> <p>Hence, we return <code>3</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array
Go
func longestMonotonicSubarray(nums []int) int { ans := 1 t := 1 for i, x := range nums[1:] { if nums[i] < x { t++ ans = max(ans, t) } else { t = 1 } } t = 1 for i, x := range nums[1:] { if nums[i] > x { t++ ans = max(ans, t) } else { t = 1 } } return ans }
3,105
Longest Strictly Increasing or Strictly Decreasing Subarray
Easy
<p>You are given an array of integers <code>nums</code>. Return <em>the length of the <strong>longest</strong> <span data-keyword="subarray-nonempty">subarray</span> of </em><code>nums</code><em> which is either <strong><span data-keyword="strictly-increasing-array">strictly increasing</span></strong> or <strong><span data-keyword="strictly-decreasing-array">strictly decreasing</span></strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, and <code>[1,4]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, <code>[3,2]</code>, and <code>[4,3]</code>.</p> <p>Hence, we return <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,3,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p> <p>Hence, we return <code>1</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, and <code>[1]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, <code>[1]</code>, <code>[3,2]</code>, <code>[2,1]</code>, and <code>[3,2,1]</code>.</p> <p>Hence, we return <code>3</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array
Java
class Solution { public int longestMonotonicSubarray(int[] nums) { int ans = 1; for (int i = 1, t = 1; i < nums.length; ++i) { if (nums[i - 1] < nums[i]) { ans = Math.max(ans, ++t); } else { t = 1; } } for (int i = 1, t = 1; i < nums.length; ++i) { if (nums[i - 1] > nums[i]) { ans = Math.max(ans, ++t); } else { t = 1; } } return ans; } }
3,105
Longest Strictly Increasing or Strictly Decreasing Subarray
Easy
<p>You are given an array of integers <code>nums</code>. Return <em>the length of the <strong>longest</strong> <span data-keyword="subarray-nonempty">subarray</span> of </em><code>nums</code><em> which is either <strong><span data-keyword="strictly-increasing-array">strictly increasing</span></strong> or <strong><span data-keyword="strictly-decreasing-array">strictly decreasing</span></strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, and <code>[1,4]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, <code>[3,2]</code>, and <code>[4,3]</code>.</p> <p>Hence, we return <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,3,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p> <p>Hence, we return <code>1</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, and <code>[1]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, <code>[1]</code>, <code>[3,2]</code>, <code>[2,1]</code>, and <code>[3,2,1]</code>.</p> <p>Hence, we return <code>3</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array
JavaScript
function longestMonotonicSubarray(nums) { const n = nums.length; let ans = 1; for (let i = 1, t1 = 1, t2 = 1; i < n; i++) { t1 = nums[i] > nums[i - 1] ? t1 + 1 : 1; t2 = nums[i] < nums[i - 1] ? t2 + 1 : 1; ans = Math.max(ans, t1, t2); } return ans; }
3,105
Longest Strictly Increasing or Strictly Decreasing Subarray
Easy
<p>You are given an array of integers <code>nums</code>. Return <em>the length of the <strong>longest</strong> <span data-keyword="subarray-nonempty">subarray</span> of </em><code>nums</code><em> which is either <strong><span data-keyword="strictly-increasing-array">strictly increasing</span></strong> or <strong><span data-keyword="strictly-decreasing-array">strictly decreasing</span></strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, and <code>[1,4]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, <code>[3,2]</code>, and <code>[4,3]</code>.</p> <p>Hence, we return <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,3,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p> <p>Hence, we return <code>1</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, and <code>[1]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, <code>[1]</code>, <code>[3,2]</code>, <code>[2,1]</code>, and <code>[3,2,1]</code>.</p> <p>Hence, we return <code>3</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array
Python
class Solution: def longestMonotonicSubarray(self, nums: List[int]) -> int: ans = t = 1 for i, x in enumerate(nums[1:]): if nums[i] < x: t += 1 ans = max(ans, t) else: t = 1 t = 1 for i, x in enumerate(nums[1:]): if nums[i] > x: t += 1 ans = max(ans, t) else: t = 1 return ans
3,105
Longest Strictly Increasing or Strictly Decreasing Subarray
Easy
<p>You are given an array of integers <code>nums</code>. Return <em>the length of the <strong>longest</strong> <span data-keyword="subarray-nonempty">subarray</span> of </em><code>nums</code><em> which is either <strong><span data-keyword="strictly-increasing-array">strictly increasing</span></strong> or <strong><span data-keyword="strictly-decreasing-array">strictly decreasing</span></strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,4,3,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, and <code>[1,4]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[3]</code>, <code>[4]</code>, <code>[3,2]</code>, and <code>[4,3]</code>.</p> <p>Hence, we return <code>2</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,3,3,3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[3]</code>, <code>[3]</code>, and <code>[3]</code>.</p> <p>Hence, we return <code>1</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2,1]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The strictly increasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, and <code>[1]</code>.</p> <p>The strictly decreasing subarrays of <code>nums</code> are <code>[3]</code>, <code>[2]</code>, <code>[1]</code>, <code>[3,2]</code>, <code>[2,1]</code>, and <code>[3,2,1]</code>.</p> <p>Hence, we return <code>3</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array
TypeScript
function longestMonotonicSubarray(nums: number[]): number { const n = nums.length; let ans = 1; for (let i = 1, t1 = 1, t2 = 1; i < n; i++) { t1 = nums[i] > nums[i - 1] ? t1 + 1 : 1; t2 = nums[i] < nums[i - 1] ? t2 + 1 : 1; ans = Math.max(ans, t1, t2); } return ans; }
3,106
Lexicographically Smallest String After Operations With Constraint
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>Define a function <code>distance(s<sub>1</sub>, s<sub>2</sub>)</code> between two strings <code>s<sub>1</sub></code> and <code>s<sub>2</sub></code> of the same length <code>n</code> as:</p> <ul> <li>The<strong> sum</strong> of the <strong>minimum distance</strong> between <code>s<sub>1</sub>[i]</code> and <code>s<sub>2</sub>[i]</code> when the characters from <code>&#39;a&#39;</code> to <code>&#39;z&#39;</code> are placed in a <strong>cyclic</strong> order, for all <code>i</code> in the range <code>[0, n - 1]</code>.</li> </ul> <p>For example, <code>distance(&quot;ab&quot;, &quot;cd&quot;) == 4</code>, and <code>distance(&quot;a&quot;, &quot;z&quot;) == 1</code>.</p> <p>You can <strong>change</strong> any letter of <code>s</code> to <strong>any</strong> other lowercase English letter, <strong>any</strong> number of times.</p> <p>Return a string denoting the <strong><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></strong> string <code>t</code> you can get after some changes, such that <code>distance(s, t) &lt;= k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zbbz&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaaz&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s</code> to <code>&quot;aaaz&quot;</code>. The distance between <code>&quot;zbbz&quot;</code> and <code>&quot;aaaz&quot;</code> is equal to <code>k = 3</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;xaxcd&quot;, k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aawcd&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The distance between &quot;xaxcd&quot; and &quot;aawcd&quot; is equal to k = 4.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;lol&quot;, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;lol&quot;</span></p> <p><strong>Explanation:</strong></p> <p>It&#39;s impossible to change any character as <code>k = 0</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>0 &lt;= k &lt;= 2000</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; String
C++
class Solution { public: string getSmallestString(string s, int k) { for (int i = 0; i < s.size(); ++i) { char c1 = s[i]; for (char c2 = 'a'; c2 < c1; ++c2) { int d = min(c1 - c2, 26 - c1 + c2); if (d <= k) { s[i] = c2; k -= d; break; } } } return s; } };
3,106
Lexicographically Smallest String After Operations With Constraint
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>Define a function <code>distance(s<sub>1</sub>, s<sub>2</sub>)</code> between two strings <code>s<sub>1</sub></code> and <code>s<sub>2</sub></code> of the same length <code>n</code> as:</p> <ul> <li>The<strong> sum</strong> of the <strong>minimum distance</strong> between <code>s<sub>1</sub>[i]</code> and <code>s<sub>2</sub>[i]</code> when the characters from <code>&#39;a&#39;</code> to <code>&#39;z&#39;</code> are placed in a <strong>cyclic</strong> order, for all <code>i</code> in the range <code>[0, n - 1]</code>.</li> </ul> <p>For example, <code>distance(&quot;ab&quot;, &quot;cd&quot;) == 4</code>, and <code>distance(&quot;a&quot;, &quot;z&quot;) == 1</code>.</p> <p>You can <strong>change</strong> any letter of <code>s</code> to <strong>any</strong> other lowercase English letter, <strong>any</strong> number of times.</p> <p>Return a string denoting the <strong><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></strong> string <code>t</code> you can get after some changes, such that <code>distance(s, t) &lt;= k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zbbz&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaaz&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s</code> to <code>&quot;aaaz&quot;</code>. The distance between <code>&quot;zbbz&quot;</code> and <code>&quot;aaaz&quot;</code> is equal to <code>k = 3</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;xaxcd&quot;, k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aawcd&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The distance between &quot;xaxcd&quot; and &quot;aawcd&quot; is equal to k = 4.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;lol&quot;, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;lol&quot;</span></p> <p><strong>Explanation:</strong></p> <p>It&#39;s impossible to change any character as <code>k = 0</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>0 &lt;= k &lt;= 2000</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; String
Go
func getSmallestString(s string, k int) string { cs := []byte(s) for i, c1 := range cs { for c2 := byte('a'); c2 < c1; c2++ { d := int(min(c1-c2, 26-c1+c2)) if d <= k { cs[i] = c2 k -= d break } } } return string(cs) }
3,106
Lexicographically Smallest String After Operations With Constraint
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>Define a function <code>distance(s<sub>1</sub>, s<sub>2</sub>)</code> between two strings <code>s<sub>1</sub></code> and <code>s<sub>2</sub></code> of the same length <code>n</code> as:</p> <ul> <li>The<strong> sum</strong> of the <strong>minimum distance</strong> between <code>s<sub>1</sub>[i]</code> and <code>s<sub>2</sub>[i]</code> when the characters from <code>&#39;a&#39;</code> to <code>&#39;z&#39;</code> are placed in a <strong>cyclic</strong> order, for all <code>i</code> in the range <code>[0, n - 1]</code>.</li> </ul> <p>For example, <code>distance(&quot;ab&quot;, &quot;cd&quot;) == 4</code>, and <code>distance(&quot;a&quot;, &quot;z&quot;) == 1</code>.</p> <p>You can <strong>change</strong> any letter of <code>s</code> to <strong>any</strong> other lowercase English letter, <strong>any</strong> number of times.</p> <p>Return a string denoting the <strong><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></strong> string <code>t</code> you can get after some changes, such that <code>distance(s, t) &lt;= k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zbbz&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaaz&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s</code> to <code>&quot;aaaz&quot;</code>. The distance between <code>&quot;zbbz&quot;</code> and <code>&quot;aaaz&quot;</code> is equal to <code>k = 3</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;xaxcd&quot;, k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aawcd&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The distance between &quot;xaxcd&quot; and &quot;aawcd&quot; is equal to k = 4.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;lol&quot;, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;lol&quot;</span></p> <p><strong>Explanation:</strong></p> <p>It&#39;s impossible to change any character as <code>k = 0</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>0 &lt;= k &lt;= 2000</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; String
Java
class Solution { public String getSmallestString(String s, int k) { char[] cs = s.toCharArray(); for (int i = 0; i < cs.length; ++i) { char c1 = cs[i]; for (char c2 = 'a'; c2 < c1; ++c2) { int d = Math.min(c1 - c2, 26 - c1 + c2); if (d <= k) { cs[i] = c2; k -= d; break; } } } return new String(cs); } }
3,106
Lexicographically Smallest String After Operations With Constraint
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>Define a function <code>distance(s<sub>1</sub>, s<sub>2</sub>)</code> between two strings <code>s<sub>1</sub></code> and <code>s<sub>2</sub></code> of the same length <code>n</code> as:</p> <ul> <li>The<strong> sum</strong> of the <strong>minimum distance</strong> between <code>s<sub>1</sub>[i]</code> and <code>s<sub>2</sub>[i]</code> when the characters from <code>&#39;a&#39;</code> to <code>&#39;z&#39;</code> are placed in a <strong>cyclic</strong> order, for all <code>i</code> in the range <code>[0, n - 1]</code>.</li> </ul> <p>For example, <code>distance(&quot;ab&quot;, &quot;cd&quot;) == 4</code>, and <code>distance(&quot;a&quot;, &quot;z&quot;) == 1</code>.</p> <p>You can <strong>change</strong> any letter of <code>s</code> to <strong>any</strong> other lowercase English letter, <strong>any</strong> number of times.</p> <p>Return a string denoting the <strong><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></strong> string <code>t</code> you can get after some changes, such that <code>distance(s, t) &lt;= k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zbbz&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaaz&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s</code> to <code>&quot;aaaz&quot;</code>. The distance between <code>&quot;zbbz&quot;</code> and <code>&quot;aaaz&quot;</code> is equal to <code>k = 3</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;xaxcd&quot;, k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aawcd&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The distance between &quot;xaxcd&quot; and &quot;aawcd&quot; is equal to k = 4.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;lol&quot;, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;lol&quot;</span></p> <p><strong>Explanation:</strong></p> <p>It&#39;s impossible to change any character as <code>k = 0</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>0 &lt;= k &lt;= 2000</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; String
Python
class Solution: def getSmallestString(self, s: str, k: int) -> str: cs = list(s) for i, c1 in enumerate(s): for c2 in ascii_lowercase: if c2 >= c1: break d = min(ord(c1) - ord(c2), 26 - ord(c1) + ord(c2)) if d <= k: cs[i] = c2 k -= d break return "".join(cs)
3,106
Lexicographically Smallest String After Operations With Constraint
Medium
<p>You are given a string <code>s</code> and an integer <code>k</code>.</p> <p>Define a function <code>distance(s<sub>1</sub>, s<sub>2</sub>)</code> between two strings <code>s<sub>1</sub></code> and <code>s<sub>2</sub></code> of the same length <code>n</code> as:</p> <ul> <li>The<strong> sum</strong> of the <strong>minimum distance</strong> between <code>s<sub>1</sub>[i]</code> and <code>s<sub>2</sub>[i]</code> when the characters from <code>&#39;a&#39;</code> to <code>&#39;z&#39;</code> are placed in a <strong>cyclic</strong> order, for all <code>i</code> in the range <code>[0, n - 1]</code>.</li> </ul> <p>For example, <code>distance(&quot;ab&quot;, &quot;cd&quot;) == 4</code>, and <code>distance(&quot;a&quot;, &quot;z&quot;) == 1</code>.</p> <p>You can <strong>change</strong> any letter of <code>s</code> to <strong>any</strong> other lowercase English letter, <strong>any</strong> number of times.</p> <p>Return a string denoting the <strong><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></strong> string <code>t</code> you can get after some changes, such that <code>distance(s, t) &lt;= k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zbbz&quot;, k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aaaz&quot;</span></p> <p><strong>Explanation:</strong></p> <p>Change <code>s</code> to <code>&quot;aaaz&quot;</code>. The distance between <code>&quot;zbbz&quot;</code> and <code>&quot;aaaz&quot;</code> is equal to <code>k = 3</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;xaxcd&quot;, k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;aawcd&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The distance between &quot;xaxcd&quot; and &quot;aawcd&quot; is equal to k = 4.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;lol&quot;, k = 0</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;lol&quot;</span></p> <p><strong>Explanation:</strong></p> <p>It&#39;s impossible to change any character as <code>k = 0</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>0 &lt;= k &lt;= 2000</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
Greedy; String
TypeScript
function getSmallestString(s: string, k: number): string { const cs: string[] = s.split(''); for (let i = 0; i < s.length; ++i) { for (let j = 97; j < s[i].charCodeAt(0); ++j) { const d = Math.min(s[i].charCodeAt(0) - j, 26 - s[i].charCodeAt(0) + j); if (d <= k) { cs[i] = String.fromCharCode(j); k -= d; break; } } } return cs.join(''); }
3,107
Minimum Operations to Make Median of Array Equal to K
Medium
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. In one operation, you can increase or decrease any element by 1.</p> <p>Return the <strong>minimum</strong> number of operations needed to make the <strong>median</strong> of <code>nums</code> <em>equal</em> to <code>k</code>.</p> <p>The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can subtract one from <code>nums[1]</code> and <code>nums[4]</code> to obtain <code>[2, 4, 6, 8, 4]</code>. The median of the resulting array is equal to <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 7</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can add one to <code>nums[1]</code> twice and add one to <code>nums[2]</code> once to obtain <code>[2, 7, 7, 8, 5]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,6], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The median of the array is already equal to <code>k</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 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;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: long long minOperationsToMakeMedianK(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); int n = nums.size(); int m = n >> 1; long long ans = abs(nums[m] - k); if (nums[m] > k) { for (int i = m - 1; i >= 0 && nums[i] > k; --i) { ans += nums[i] - k; } } else { for (int i = m + 1; i < n && nums[i] < k; ++i) { ans += k - nums[i]; } } return ans; } };
3,107
Minimum Operations to Make Median of Array Equal to K
Medium
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. In one operation, you can increase or decrease any element by 1.</p> <p>Return the <strong>minimum</strong> number of operations needed to make the <strong>median</strong> of <code>nums</code> <em>equal</em> to <code>k</code>.</p> <p>The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can subtract one from <code>nums[1]</code> and <code>nums[4]</code> to obtain <code>[2, 4, 6, 8, 4]</code>. The median of the resulting array is equal to <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 7</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can add one to <code>nums[1]</code> twice and add one to <code>nums[2]</code> once to obtain <code>[2, 7, 7, 8, 5]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,6], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The median of the array is already equal to <code>k</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 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;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
Go
func minOperationsToMakeMedianK(nums []int, k int) (ans int64) { sort.Ints(nums) n := len(nums) m := n >> 1 ans = int64(abs(nums[m] - k)) if nums[m] > k { for i := m - 1; i >= 0 && nums[i] > k; i-- { ans += int64(nums[i] - k) } } else { for i := m + 1; i < n && nums[i] < k; i++ { ans += int64(k - nums[i]) } } return } func abs(x int) int { if x < 0 { return -x } return x }
3,107
Minimum Operations to Make Median of Array Equal to K
Medium
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. In one operation, you can increase or decrease any element by 1.</p> <p>Return the <strong>minimum</strong> number of operations needed to make the <strong>median</strong> of <code>nums</code> <em>equal</em> to <code>k</code>.</p> <p>The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can subtract one from <code>nums[1]</code> and <code>nums[4]</code> to obtain <code>[2, 4, 6, 8, 4]</code>. The median of the resulting array is equal to <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 7</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can add one to <code>nums[1]</code> twice and add one to <code>nums[2]</code> once to obtain <code>[2, 7, 7, 8, 5]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,6], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The median of the array is already equal to <code>k</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 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;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
Java
class Solution { public long minOperationsToMakeMedianK(int[] nums, int k) { Arrays.sort(nums); int n = nums.length; int m = n >> 1; long ans = Math.abs(nums[m] - k); if (nums[m] > k) { for (int i = m - 1; i >= 0 && nums[i] > k; --i) { ans += nums[i] - k; } } else { for (int i = m + 1; i < n && nums[i] < k; ++i) { ans += k - nums[i]; } } return ans; } }
3,107
Minimum Operations to Make Median of Array Equal to K
Medium
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. In one operation, you can increase or decrease any element by 1.</p> <p>Return the <strong>minimum</strong> number of operations needed to make the <strong>median</strong> of <code>nums</code> <em>equal</em> to <code>k</code>.</p> <p>The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can subtract one from <code>nums[1]</code> and <code>nums[4]</code> to obtain <code>[2, 4, 6, 8, 4]</code>. The median of the resulting array is equal to <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 7</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can add one to <code>nums[1]</code> twice and add one to <code>nums[2]</code> once to obtain <code>[2, 7, 7, 8, 5]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,6], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The median of the array is already equal to <code>k</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 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;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
Python
class Solution: def minOperationsToMakeMedianK(self, nums: List[int], k: int) -> int: nums.sort() n = len(nums) m = n >> 1 ans = abs(nums[m] - k) if nums[m] > k: for i in range(m - 1, -1, -1): if nums[i] <= k: break ans += nums[i] - k else: for i in range(m + 1, n): if nums[i] >= k: break ans += k - nums[i] return ans
3,107
Minimum Operations to Make Median of Array Equal to K
Medium
<p>You are given an integer array <code>nums</code> and a <strong>non-negative</strong> integer <code>k</code>. In one operation, you can increase or decrease any element by 1.</p> <p>Return the <strong>minimum</strong> number of operations needed to make the <strong>median</strong> of <code>nums</code> <em>equal</em> to <code>k</code>.</p> <p>The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>We can subtract one from <code>nums[1]</code> and <code>nums[4]</code> to obtain <code>[2, 4, 6, 8, 4]</code>. The median of the resulting array is equal to <code>k</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,5,6,8,5], k = 7</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>We can add one to <code>nums[1]</code> twice and add one to <code>nums[2]</code> once to obtain <code>[2, 7, 7, 8, 5]</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5,6], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The median of the array is already equal to <code>k</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 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;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Sorting
TypeScript
function minOperationsToMakeMedianK(nums: number[], k: number): number { nums.sort((a, b) => a - b); const n = nums.length; const m = n >> 1; let ans = Math.abs(nums[m] - k); if (nums[m] > k) { for (let i = m - 1; i >= 0 && nums[i] > k; --i) { ans += nums[i] - k; } } else { for (let i = m + 1; i < n && nums[i] < k; ++i) { ans += k - nums[i]; } } return ans; }
3,108
Minimum Cost Walk in Weighted Graph
Hard
<p>There is an undirected weighted graph with <code>n</code> vertices labeled from <code>0</code> to <code>n - 1</code>.</p> <p>You are given the integer <code>n</code> and an array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between vertices <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with a weight of <code>w<sub>i</sub></code>.</p> <p>A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It&#39;s important to note that a walk may visit the same edge or vertex more than once.</p> <p>The <strong>cost</strong> of a walk starting at node <code>u</code> and ending at node <code>v</code> is defined as the bitwise <code>AND</code> of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is <code>w<sub>0</sub>, w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>k</sub></code>, then the cost is calculated as <code>w<sub>0</sub> &amp; w<sub>1</sub> &amp; w<sub>2</sub> &amp; ... &amp; w<sub>k</sub></code>, where <code>&amp;</code> denotes the bitwise <code>AND</code> operator.</p> <p>You are also given a 2D array <code>query</code>, where <code>query[i] = [s<sub>i</sub>, t<sub>i</sub>]</code>. For each query, you need to find the minimum cost of the walk starting at vertex <code>s<sub>i</sub></code> and ending at vertex <code>t<sub>i</sub></code>. If there exists no such walk, the answer is <code>-1</code>.</p> <p>Return <em>the array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> denotes the <strong>minimum</strong> cost of a walk for query </em><code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,-1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example1-1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 351px; height: 141px;" /> <p>To achieve the cost of 1 in the first query, we need to move on the following edges: <code>0-&gt;1</code> (weight 7), <code>1-&gt;2</code> (weight 1), <code>2-&gt;1</code> (weight 1), <code>1-&gt;3</code> (weight 7).</p> <p>In the second query, there is no walk between nodes 3 and 4, so the answer is -1.</p> <p><strong class="example">Example 2:</strong></p> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example2e.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 211px; height: 181px;" /> <p>To achieve the cost of 0 in the first query, we need to move on the following edges: <code>1-&gt;2</code> (weight 1), <code>2-&gt;1</code> (weight 6), <code>1-&gt;2</code> (weight 1).</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= edges.length &lt;= 10<sup>5</sup></code></li> <li><code>edges[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>0 &lt;= w<sub>i</sub> &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= query.length &lt;= 10<sup>5</sup></code></li> <li><code>query[i].length == 2</code></li> <li><code>0 &lt;= s<sub>i</sub>, t<sub>i</sub> &lt;= n - 1</code></li> <li><code>s<sub>i</sub> !=&nbsp;t<sub>i</sub></code></li> </ul>
Bit Manipulation; Union Find; Graph; Array
C++
class UnionFind { public: UnionFind(int n) { p = vector<int>(n); size = vector<int>(n, 1); iota(p.begin(), p.end(), 0); } bool unite(int a, int b) { int pa = find(a), pb = find(b); if (pa == pb) { return false; } if (size[pa] > size[pb]) { p[pb] = pa; size[pa] += size[pb]; } else { p[pa] = pb; size[pb] += size[pa]; } return true; } int find(int x) { if (p[x] != x) { p[x] = find(p[x]); } return p[x]; } int getSize(int x) { return size[find(x)]; } private: vector<int> p, size; }; class Solution { public: vector<int> minimumCost(int n, vector<vector<int>>& edges, vector<vector<int>>& query) { g = vector<int>(n, -1); uf = new UnionFind(n); for (auto& e : edges) { uf->unite(e[0], e[1]); } for (auto& e : edges) { int root = uf->find(e[0]); g[root] &= e[2]; } vector<int> ans; for (auto& q : query) { ans.push_back(f(q[0], q[1])); } return ans; } private: UnionFind* uf; vector<int> g; int f(int u, int v) { if (u == v) { return 0; } int a = uf->find(u), b = uf->find(v); return a == b ? g[a] : -1; } };
3,108
Minimum Cost Walk in Weighted Graph
Hard
<p>There is an undirected weighted graph with <code>n</code> vertices labeled from <code>0</code> to <code>n - 1</code>.</p> <p>You are given the integer <code>n</code> and an array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between vertices <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with a weight of <code>w<sub>i</sub></code>.</p> <p>A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It&#39;s important to note that a walk may visit the same edge or vertex more than once.</p> <p>The <strong>cost</strong> of a walk starting at node <code>u</code> and ending at node <code>v</code> is defined as the bitwise <code>AND</code> of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is <code>w<sub>0</sub>, w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>k</sub></code>, then the cost is calculated as <code>w<sub>0</sub> &amp; w<sub>1</sub> &amp; w<sub>2</sub> &amp; ... &amp; w<sub>k</sub></code>, where <code>&amp;</code> denotes the bitwise <code>AND</code> operator.</p> <p>You are also given a 2D array <code>query</code>, where <code>query[i] = [s<sub>i</sub>, t<sub>i</sub>]</code>. For each query, you need to find the minimum cost of the walk starting at vertex <code>s<sub>i</sub></code> and ending at vertex <code>t<sub>i</sub></code>. If there exists no such walk, the answer is <code>-1</code>.</p> <p>Return <em>the array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> denotes the <strong>minimum</strong> cost of a walk for query </em><code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,-1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example1-1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 351px; height: 141px;" /> <p>To achieve the cost of 1 in the first query, we need to move on the following edges: <code>0-&gt;1</code> (weight 7), <code>1-&gt;2</code> (weight 1), <code>2-&gt;1</code> (weight 1), <code>1-&gt;3</code> (weight 7).</p> <p>In the second query, there is no walk between nodes 3 and 4, so the answer is -1.</p> <p><strong class="example">Example 2:</strong></p> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example2e.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 211px; height: 181px;" /> <p>To achieve the cost of 0 in the first query, we need to move on the following edges: <code>1-&gt;2</code> (weight 1), <code>2-&gt;1</code> (weight 6), <code>1-&gt;2</code> (weight 1).</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= edges.length &lt;= 10<sup>5</sup></code></li> <li><code>edges[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>0 &lt;= w<sub>i</sub> &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= query.length &lt;= 10<sup>5</sup></code></li> <li><code>query[i].length == 2</code></li> <li><code>0 &lt;= s<sub>i</sub>, t<sub>i</sub> &lt;= n - 1</code></li> <li><code>s<sub>i</sub> !=&nbsp;t<sub>i</sub></code></li> </ul>
Bit Manipulation; Union Find; Graph; Array
Go
type unionFind struct { p, size []int } func newUnionFind(n int) *unionFind { p := make([]int, n) size := make([]int, n) for i := range p { p[i] = i size[i] = 1 } return &unionFind{p, size} } func (uf *unionFind) find(x int) int { if uf.p[x] != x { uf.p[x] = uf.find(uf.p[x]) } return uf.p[x] } func (uf *unionFind) union(a, b int) bool { pa, pb := uf.find(a), uf.find(b) if pa == pb { return false } if uf.size[pa] > uf.size[pb] { uf.p[pb] = pa uf.size[pa] += uf.size[pb] } else { uf.p[pa] = pb uf.size[pb] += uf.size[pa] } return true } func (uf *unionFind) getSize(x int) int { return uf.size[uf.find(x)] } func minimumCost(n int, edges [][]int, query [][]int) (ans []int) { uf := newUnionFind(n) g := make([]int, n) for i := range g { g[i] = -1 } for _, e := range edges { uf.union(e[0], e[1]) } for _, e := range edges { root := uf.find(e[0]) g[root] &= e[2] } f := func(u, v int) int { if u == v { return 0 } a, b := uf.find(u), uf.find(v) if a == b { return g[a] } return -1 } for _, q := range query { ans = append(ans, f(q[0], q[1])) } return }
3,108
Minimum Cost Walk in Weighted Graph
Hard
<p>There is an undirected weighted graph with <code>n</code> vertices labeled from <code>0</code> to <code>n - 1</code>.</p> <p>You are given the integer <code>n</code> and an array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between vertices <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with a weight of <code>w<sub>i</sub></code>.</p> <p>A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It&#39;s important to note that a walk may visit the same edge or vertex more than once.</p> <p>The <strong>cost</strong> of a walk starting at node <code>u</code> and ending at node <code>v</code> is defined as the bitwise <code>AND</code> of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is <code>w<sub>0</sub>, w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>k</sub></code>, then the cost is calculated as <code>w<sub>0</sub> &amp; w<sub>1</sub> &amp; w<sub>2</sub> &amp; ... &amp; w<sub>k</sub></code>, where <code>&amp;</code> denotes the bitwise <code>AND</code> operator.</p> <p>You are also given a 2D array <code>query</code>, where <code>query[i] = [s<sub>i</sub>, t<sub>i</sub>]</code>. For each query, you need to find the minimum cost of the walk starting at vertex <code>s<sub>i</sub></code> and ending at vertex <code>t<sub>i</sub></code>. If there exists no such walk, the answer is <code>-1</code>.</p> <p>Return <em>the array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> denotes the <strong>minimum</strong> cost of a walk for query </em><code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,-1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example1-1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 351px; height: 141px;" /> <p>To achieve the cost of 1 in the first query, we need to move on the following edges: <code>0-&gt;1</code> (weight 7), <code>1-&gt;2</code> (weight 1), <code>2-&gt;1</code> (weight 1), <code>1-&gt;3</code> (weight 7).</p> <p>In the second query, there is no walk between nodes 3 and 4, so the answer is -1.</p> <p><strong class="example">Example 2:</strong></p> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example2e.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 211px; height: 181px;" /> <p>To achieve the cost of 0 in the first query, we need to move on the following edges: <code>1-&gt;2</code> (weight 1), <code>2-&gt;1</code> (weight 6), <code>1-&gt;2</code> (weight 1).</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= edges.length &lt;= 10<sup>5</sup></code></li> <li><code>edges[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>0 &lt;= w<sub>i</sub> &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= query.length &lt;= 10<sup>5</sup></code></li> <li><code>query[i].length == 2</code></li> <li><code>0 &lt;= s<sub>i</sub>, t<sub>i</sub> &lt;= n - 1</code></li> <li><code>s<sub>i</sub> !=&nbsp;t<sub>i</sub></code></li> </ul>
Bit Manipulation; Union Find; Graph; Array
Java
class UnionFind { private final int[] p; private final int[] size; public UnionFind(int n) { p = new int[n]; size = new int[n]; for (int i = 0; i < n; ++i) { p[i] = i; size[i] = 1; } } public int find(int x) { if (p[x] != x) { p[x] = find(p[x]); } return p[x]; } public boolean union(int a, int b) { int pa = find(a), pb = find(b); if (pa == pb) { return false; } if (size[pa] > size[pb]) { p[pb] = pa; size[pa] += size[pb]; } else { p[pa] = pb; size[pb] += size[pa]; } return true; } public int size(int x) { return size[find(x)]; } } class Solution { private UnionFind uf; private int[] g; public int[] minimumCost(int n, int[][] edges, int[][] query) { uf = new UnionFind(n); for (var e : edges) { uf.union(e[0], e[1]); } g = new int[n]; Arrays.fill(g, -1); for (var e : edges) { int root = uf.find(e[0]); g[root] &= e[2]; } int m = query.length; int[] ans = new int[m]; for (int i = 0; i < m; ++i) { int s = query[i][0], t = query[i][1]; ans[i] = f(s, t); } return ans; } private int f(int u, int v) { if (u == v) { return 0; } int a = uf.find(u), b = uf.find(v); return a == b ? g[a] : -1; } }
3,108
Minimum Cost Walk in Weighted Graph
Hard
<p>There is an undirected weighted graph with <code>n</code> vertices labeled from <code>0</code> to <code>n - 1</code>.</p> <p>You are given the integer <code>n</code> and an array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between vertices <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with a weight of <code>w<sub>i</sub></code>.</p> <p>A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It&#39;s important to note that a walk may visit the same edge or vertex more than once.</p> <p>The <strong>cost</strong> of a walk starting at node <code>u</code> and ending at node <code>v</code> is defined as the bitwise <code>AND</code> of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is <code>w<sub>0</sub>, w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>k</sub></code>, then the cost is calculated as <code>w<sub>0</sub> &amp; w<sub>1</sub> &amp; w<sub>2</sub> &amp; ... &amp; w<sub>k</sub></code>, where <code>&amp;</code> denotes the bitwise <code>AND</code> operator.</p> <p>You are also given a 2D array <code>query</code>, where <code>query[i] = [s<sub>i</sub>, t<sub>i</sub>]</code>. For each query, you need to find the minimum cost of the walk starting at vertex <code>s<sub>i</sub></code> and ending at vertex <code>t<sub>i</sub></code>. If there exists no such walk, the answer is <code>-1</code>.</p> <p>Return <em>the array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> denotes the <strong>minimum</strong> cost of a walk for query </em><code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,-1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example1-1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 351px; height: 141px;" /> <p>To achieve the cost of 1 in the first query, we need to move on the following edges: <code>0-&gt;1</code> (weight 7), <code>1-&gt;2</code> (weight 1), <code>2-&gt;1</code> (weight 1), <code>1-&gt;3</code> (weight 7).</p> <p>In the second query, there is no walk between nodes 3 and 4, so the answer is -1.</p> <p><strong class="example">Example 2:</strong></p> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example2e.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 211px; height: 181px;" /> <p>To achieve the cost of 0 in the first query, we need to move on the following edges: <code>1-&gt;2</code> (weight 1), <code>2-&gt;1</code> (weight 6), <code>1-&gt;2</code> (weight 1).</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= edges.length &lt;= 10<sup>5</sup></code></li> <li><code>edges[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>0 &lt;= w<sub>i</sub> &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= query.length &lt;= 10<sup>5</sup></code></li> <li><code>query[i].length == 2</code></li> <li><code>0 &lt;= s<sub>i</sub>, t<sub>i</sub> &lt;= n - 1</code></li> <li><code>s<sub>i</sub> !=&nbsp;t<sub>i</sub></code></li> </ul>
Bit Manipulation; Union Find; Graph; Array
Python
class UnionFind: def __init__(self, n): self.p = list(range(n)) self.size = [1] * n def find(self, x): if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, a, b): pa, pb = self.find(a), self.find(b) if pa == pb: return False if self.size[pa] > self.size[pb]: self.p[pb] = pa self.size[pa] += self.size[pb] else: self.p[pa] = pb self.size[pb] += self.size[pa] return True class Solution: def minimumCost( self, n: int, edges: List[List[int]], query: List[List[int]] ) -> List[int]: g = [-1] * n uf = UnionFind(n) for u, v, _ in edges: uf.union(u, v) for u, _, w in edges: root = uf.find(u) g[root] &= w def f(u: int, v: int) -> int: if u == v: return 0 a, b = uf.find(u), uf.find(v) return g[a] if a == b else -1 return [f(s, t) for s, t in query]
3,108
Minimum Cost Walk in Weighted Graph
Hard
<p>There is an undirected weighted graph with <code>n</code> vertices labeled from <code>0</code> to <code>n - 1</code>.</p> <p>You are given the integer <code>n</code> and an array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>]</code> indicates that there is an edge between vertices <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code> with a weight of <code>w<sub>i</sub></code>.</p> <p>A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It&#39;s important to note that a walk may visit the same edge or vertex more than once.</p> <p>The <strong>cost</strong> of a walk starting at node <code>u</code> and ending at node <code>v</code> is defined as the bitwise <code>AND</code> of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is <code>w<sub>0</sub>, w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>k</sub></code>, then the cost is calculated as <code>w<sub>0</sub> &amp; w<sub>1</sub> &amp; w<sub>2</sub> &amp; ... &amp; w<sub>k</sub></code>, where <code>&amp;</code> denotes the bitwise <code>AND</code> operator.</p> <p>You are also given a 2D array <code>query</code>, where <code>query[i] = [s<sub>i</sub>, t<sub>i</sub>]</code>. For each query, you need to find the minimum cost of the walk starting at vertex <code>s<sub>i</sub></code> and ending at vertex <code>t<sub>i</sub></code>. If there exists no such walk, the answer is <code>-1</code>.</p> <p>Return <em>the array </em><code>answer</code><em>, where </em><code>answer[i]</code><em> denotes the <strong>minimum</strong> cost of a walk for query </em><code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,-1]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example1-1.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 351px; height: 141px;" /> <p>To achieve the cost of 1 in the first query, we need to move on the following edges: <code>0-&gt;1</code> (weight 7), <code>1-&gt;2</code> (weight 1), <code>2-&gt;1</code> (weight 1), <code>1-&gt;3</code> (weight 7).</p> <p>In the second query, there is no walk between nodes 3 and 4, so the answer is -1.</p> <p><strong class="example">Example 2:</strong></p> </div> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3100-3199/3108.Minimum%20Cost%20Walk%20in%20Weighted%20Graph/images/q4_example2e.png" style="padding: 10px; background: rgb(255, 255, 255); border-radius: 0.5rem; width: 211px; height: 181px;" /> <p>To achieve the cost of 0 in the first query, we need to move on the following edges: <code>1-&gt;2</code> (weight 1), <code>2-&gt;1</code> (weight 6), <code>1-&gt;2</code> (weight 1).</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= edges.length &lt;= 10<sup>5</sup></code></li> <li><code>edges[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>0 &lt;= w<sub>i</sub> &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= query.length &lt;= 10<sup>5</sup></code></li> <li><code>query[i].length == 2</code></li> <li><code>0 &lt;= s<sub>i</sub>, t<sub>i</sub> &lt;= n - 1</code></li> <li><code>s<sub>i</sub> !=&nbsp;t<sub>i</sub></code></li> </ul>
Bit Manipulation; Union Find; Graph; Array
TypeScript
class UnionFind { p: number[]; size: number[]; constructor(n: number) { this.p = Array(n) .fill(0) .map((_, i) => i); this.size = Array(n).fill(1); } find(x: number): number { if (this.p[x] !== x) { this.p[x] = this.find(this.p[x]); } return this.p[x]; } union(a: number, b: number): boolean { const [pa, pb] = [this.find(a), this.find(b)]; if (pa === pb) { return false; } if (this.size[pa] > this.size[pb]) { this.p[pb] = pa; this.size[pa] += this.size[pb]; } else { this.p[pa] = pb; this.size[pb] += this.size[pa]; } return true; } getSize(x: number): number { return this.size[this.find(x)]; } } function minimumCost(n: number, edges: number[][], query: number[][]): number[] { const uf = new UnionFind(n); const g: number[] = Array(n).fill(-1); for (const [u, v, _] of edges) { uf.union(u, v); } for (const [u, _, w] of edges) { const root = uf.find(u); g[root] &= w; } const f = (u: number, v: number): number => { if (u === v) { return 0; } const [a, b] = [uf.find(u), uf.find(v)]; return a === b ? g[a] : -1; }; return query.map(([u, v]) => f(u, v)); }
3,109
Find the Index of Permutation
Medium
<p>Given an array <code>perm</code> of length <code>n</code> which is a permutation of <code>[1, 2, ..., n]</code>, return the index of <code>perm</code> in the <span data-keyword="lexicographically-sorted-array">lexicographically sorted</span> array of all of the permutations of <code>[1, 2, ..., n]</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup>&nbsp;+ 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">perm = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are only two permutations in the following order:</p> <p><code>[1,2]</code>, <code>[2,1]</code><br /> <br /> And <code>[1,2]</code> is at index 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">perm = [3,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There are only six permutations in the following order:</p> <p><code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[2,1,3]</code>, <code>[2,3,1]</code>, <code>[3,1,2]</code>, <code>[3,2,1]</code><br /> <br /> And <code>[3,1,2]</code> is at index 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == perm.length &lt;= 10<sup>5</sup></code></li> <li><code>perm</code> is a permutation of <code>[1, 2, ..., n]</code>.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
C++
class BinaryIndexedTree { private: int n; vector<int> c; public: BinaryIndexedTree(int n) : n(n) , c(n + 1) {} void update(int x, int delta) { for (; x <= n; x += x & -x) { c[x] += delta; } } int query(int x) { int s = 0; for (; x > 0; x -= x & -x) { s += c[x]; } return s; } }; class Solution { public: int getPermutationIndex(vector<int>& perm) { const int mod = 1e9 + 7; using ll = long long; ll ans = 0; int n = perm.size(); BinaryIndexedTree tree(n + 1); ll f[n]; f[0] = 1; for (int i = 1; i < n; ++i) { f[i] = f[i - 1] * i % mod; } for (int i = 0; i < n; ++i) { int cnt = perm[i] - 1 - tree.query(perm[i]); ans += cnt * f[n - i - 1] % mod; tree.update(perm[i], 1); } return ans % mod; } };
3,109
Find the Index of Permutation
Medium
<p>Given an array <code>perm</code> of length <code>n</code> which is a permutation of <code>[1, 2, ..., n]</code>, return the index of <code>perm</code> in the <span data-keyword="lexicographically-sorted-array">lexicographically sorted</span> array of all of the permutations of <code>[1, 2, ..., n]</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup>&nbsp;+ 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">perm = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are only two permutations in the following order:</p> <p><code>[1,2]</code>, <code>[2,1]</code><br /> <br /> And <code>[1,2]</code> is at index 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">perm = [3,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There are only six permutations in the following order:</p> <p><code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[2,1,3]</code>, <code>[2,3,1]</code>, <code>[3,1,2]</code>, <code>[3,2,1]</code><br /> <br /> And <code>[3,1,2]</code> is at index 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == perm.length &lt;= 10<sup>5</sup></code></li> <li><code>perm</code> is a permutation of <code>[1, 2, ..., n]</code>.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
Go
type BinaryIndexedTree struct { n int c []int } func NewBinaryIndexedTree(n int) *BinaryIndexedTree { return &BinaryIndexedTree{n: n, c: make([]int, n+1)} } func (bit *BinaryIndexedTree) update(x, delta int) { for ; x <= bit.n; x += x & -x { bit.c[x] += delta } } func (bit *BinaryIndexedTree) query(x int) int { s := 0 for ; x > 0; x -= x & -x { s += bit.c[x] } return s } func getPermutationIndex(perm []int) (ans int) { const mod int = 1e9 + 7 n := len(perm) tree := NewBinaryIndexedTree(n + 1) f := make([]int, n) f[0] = 1 for i := 1; i < n; i++ { f[i] = f[i-1] * i % mod } for i, x := range perm { cnt := x - 1 - tree.query(x) ans += cnt * f[n-1-i] % mod tree.update(x, 1) } return ans % mod }
3,109
Find the Index of Permutation
Medium
<p>Given an array <code>perm</code> of length <code>n</code> which is a permutation of <code>[1, 2, ..., n]</code>, return the index of <code>perm</code> in the <span data-keyword="lexicographically-sorted-array">lexicographically sorted</span> array of all of the permutations of <code>[1, 2, ..., n]</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup>&nbsp;+ 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">perm = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are only two permutations in the following order:</p> <p><code>[1,2]</code>, <code>[2,1]</code><br /> <br /> And <code>[1,2]</code> is at index 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">perm = [3,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There are only six permutations in the following order:</p> <p><code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[2,1,3]</code>, <code>[2,3,1]</code>, <code>[3,1,2]</code>, <code>[3,2,1]</code><br /> <br /> And <code>[3,1,2]</code> is at index 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == perm.length &lt;= 10<sup>5</sup></code></li> <li><code>perm</code> is a permutation of <code>[1, 2, ..., n]</code>.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
Java
class BinaryIndexedTree { private int n; private int[] c; public BinaryIndexedTree(int n) { this.n = n; this.c = new int[n + 1]; } public void update(int x, int delta) { for (; x <= n; x += x & -x) { c[x] += delta; } } public int query(int x) { int s = 0; for (; x > 0; x -= x & -x) { s += c[x]; } return s; } } class Solution { public int getPermutationIndex(int[] perm) { final int mod = (int) 1e9 + 7; long ans = 0; int n = perm.length; BinaryIndexedTree tree = new BinaryIndexedTree(n + 1); long[] f = new long[n]; f[0] = 1; for (int i = 1; i < n; ++i) { f[i] = f[i - 1] * i % mod; } for (int i = 0; i < n; ++i) { int cnt = perm[i] - 1 - tree.query(perm[i]); ans = (ans + cnt * f[n - i - 1] % mod) % mod; tree.update(perm[i], 1); } return (int) ans; } }
3,109
Find the Index of Permutation
Medium
<p>Given an array <code>perm</code> of length <code>n</code> which is a permutation of <code>[1, 2, ..., n]</code>, return the index of <code>perm</code> in the <span data-keyword="lexicographically-sorted-array">lexicographically sorted</span> array of all of the permutations of <code>[1, 2, ..., n]</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup>&nbsp;+ 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">perm = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are only two permutations in the following order:</p> <p><code>[1,2]</code>, <code>[2,1]</code><br /> <br /> And <code>[1,2]</code> is at index 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">perm = [3,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There are only six permutations in the following order:</p> <p><code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[2,1,3]</code>, <code>[2,3,1]</code>, <code>[3,1,2]</code>, <code>[3,2,1]</code><br /> <br /> And <code>[3,1,2]</code> is at index 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == perm.length &lt;= 10<sup>5</sup></code></li> <li><code>perm</code> is a permutation of <code>[1, 2, ..., n]</code>.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
Python
class BinaryIndexedTree: __slots__ = "n", "c" def __init__(self, n: int): self.n = n self.c = [0] * (n + 1) def update(self, x: int, delta: int) -> None: while x <= self.n: self.c[x] += delta x += x & -x def query(self, x: int) -> int: s = 0 while x: s += self.c[x] x -= x & -x return s class Solution: def getPermutationIndex(self, perm: List[int]) -> int: mod = 10**9 + 7 ans, n = 0, len(perm) tree = BinaryIndexedTree(n + 1) f = [1] * n for i in range(1, n): f[i] = f[i - 1] * i % mod for i, x in enumerate(perm): cnt = x - 1 - tree.query(x) ans += cnt * f[n - i - 1] % mod tree.update(x, 1) return ans % mod
3,109
Find the Index of Permutation
Medium
<p>Given an array <code>perm</code> of length <code>n</code> which is a permutation of <code>[1, 2, ..., n]</code>, return the index of <code>perm</code> in the <span data-keyword="lexicographically-sorted-array">lexicographically sorted</span> array of all of the permutations of <code>[1, 2, ..., n]</code>.</p> <p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup>&nbsp;+ 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">perm = [1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>There are only two permutations in the following order:</p> <p><code>[1,2]</code>, <code>[2,1]</code><br /> <br /> And <code>[1,2]</code> is at index 0.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">perm = [3,1,2]</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>There are only six permutations in the following order:</p> <p><code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[2,1,3]</code>, <code>[2,3,1]</code>, <code>[3,1,2]</code>, <code>[3,2,1]</code><br /> <br /> And <code>[3,1,2]</code> is at index 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == perm.length &lt;= 10<sup>5</sup></code></li> <li><code>perm</code> is a permutation of <code>[1, 2, ..., n]</code>.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Binary Search; Divide and Conquer; Ordered Set; Merge Sort
TypeScript
class BinaryIndexedTree { private n: number; private c: number[]; constructor(n: number) { this.n = n; this.c = Array(n + 1).fill(0); } update(x: number, delta: number): void { for (; x <= this.n; x += x & -x) { this.c[x] += delta; } } query(x: number): number { let s = 0; for (; x > 0; x -= x & -x) { s += this.c[x]; } return s; } } function getPermutationIndex(perm: number[]): number { const mod = 1e9 + 7; const n = perm.length; const tree = new BinaryIndexedTree(n + 1); let ans = 0; const f: number[] = Array(n).fill(1); for (let i = 1; i < n; ++i) { f[i] = (f[i - 1] * i) % mod; } for (let i = 0; i < n; ++i) { const cnt = perm[i] - 1 - tree.query(perm[i]); ans = (ans + cnt * f[n - i - 1]) % mod; tree.update(perm[i], 1); } return ans % mod; }
3,110
Score of a String
Easy
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p> <p>Return the <strong>score</strong> of<em> </em><code>s</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">s = &quot;hello&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;h&#39; = 104</code>, <code>&#39;e&#39; = 101</code>, <code>&#39;l&#39; = 108</code>, <code>&#39;o&#39; = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zaz&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">50</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;z&#39; = 122</code>, <code>&#39;a&#39; = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String
C++
class Solution { public: int scoreOfString(string s) { int ans = 0; for (int i = 1; i < s.size(); ++i) { ans += abs(s[i] - s[i - 1]); } return ans; } };
3,110
Score of a String
Easy
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p> <p>Return the <strong>score</strong> of<em> </em><code>s</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">s = &quot;hello&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;h&#39; = 104</code>, <code>&#39;e&#39; = 101</code>, <code>&#39;l&#39; = 108</code>, <code>&#39;o&#39; = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zaz&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">50</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;z&#39; = 122</code>, <code>&#39;a&#39; = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String
C#
public class Solution { public int ScoreOfString(string s) { int ans = 0; for (int i = 1; i < s.Length; ++i) { ans += Math.Abs(s[i] - s[i - 1]); } return ans; } }
3,110
Score of a String
Easy
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p> <p>Return the <strong>score</strong> of<em> </em><code>s</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">s = &quot;hello&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;h&#39; = 104</code>, <code>&#39;e&#39; = 101</code>, <code>&#39;l&#39; = 108</code>, <code>&#39;o&#39; = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zaz&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">50</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;z&#39; = 122</code>, <code>&#39;a&#39; = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String
Go
func scoreOfString(s string) (ans int) { for i := 1; i < len(s); i++ { ans += abs(int(s[i-1]) - int(s[i])) } return } func abs(x int) int { if x < 0 { return -x } return x }
3,110
Score of a String
Easy
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p> <p>Return the <strong>score</strong> of<em> </em><code>s</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">s = &quot;hello&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;h&#39; = 104</code>, <code>&#39;e&#39; = 101</code>, <code>&#39;l&#39; = 108</code>, <code>&#39;o&#39; = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zaz&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">50</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;z&#39; = 122</code>, <code>&#39;a&#39; = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String
Java
class Solution { public int scoreOfString(String s) { int ans = 0; for (int i = 1; i < s.length(); ++i) { ans += Math.abs(s.charAt(i - 1) - s.charAt(i)); } return ans; } }
3,110
Score of a String
Easy
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p> <p>Return the <strong>score</strong> of<em> </em><code>s</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">s = &quot;hello&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;h&#39; = 104</code>, <code>&#39;e&#39; = 101</code>, <code>&#39;l&#39; = 108</code>, <code>&#39;o&#39; = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zaz&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">50</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;z&#39; = 122</code>, <code>&#39;a&#39; = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String
PHP
class Solution { /** * @param String $s * @return Integer */ function scoreOfString($s) { $ans = 0; $n = strlen($s); for ($i = 1; $i < $n; ++$i) { $ans += abs(ord($s[$i]) - ord($s[$i - 1])); } return $ans; } }
3,110
Score of a String
Easy
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p> <p>Return the <strong>score</strong> of<em> </em><code>s</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">s = &quot;hello&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;h&#39; = 104</code>, <code>&#39;e&#39; = 101</code>, <code>&#39;l&#39; = 108</code>, <code>&#39;o&#39; = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zaz&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">50</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;z&#39; = 122</code>, <code>&#39;a&#39; = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String
Python
class Solution: def scoreOfString(self, s: str) -> int: return sum(abs(a - b) for a, b in pairwise(map(ord, s)))
3,110
Score of a String
Easy
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p> <p>Return the <strong>score</strong> of<em> </em><code>s</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">s = &quot;hello&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;h&#39; = 104</code>, <code>&#39;e&#39; = 101</code>, <code>&#39;l&#39; = 108</code>, <code>&#39;o&#39; = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zaz&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">50</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;z&#39; = 122</code>, <code>&#39;a&#39; = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String
Rust
impl Solution { pub fn score_of_string(s: String) -> i32 { s.as_bytes() .windows(2) .map(|w| (w[0] as i32 - w[1] as i32).abs()) .sum() } }
3,110
Score of a String
Easy
<p>You are given a string <code>s</code>. The <strong>score</strong> of a string is defined as the sum of the absolute difference between the <strong>ASCII</strong> values of adjacent characters.</p> <p>Return the <strong>score</strong> of<em> </em><code>s</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">s = &quot;hello&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">13</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;h&#39; = 104</code>, <code>&#39;e&#39; = 101</code>, <code>&#39;l&#39; = 108</code>, <code>&#39;o&#39; = 111</code>. So, the score of <code>s</code> would be <code>|104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zaz&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">50</span></p> <p><strong>Explanation:</strong></p> <p>The <strong>ASCII</strong> values of the characters in <code>s</code> are: <code>&#39;z&#39; = 122</code>, <code>&#39;a&#39; = 97</code>. So, the score of <code>s</code> would be <code>|122 - 97| + |97 - 122| = 25 + 25 = 50</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= s.length &lt;= 100</code></li> <li><code>s</code> consists only of lowercase English letters.</li> </ul>
String
TypeScript
function scoreOfString(s: string): number { let ans = 0; for (let i = 1; i < s.length; ++i) { ans += Math.abs(s.charCodeAt(i) - s.charCodeAt(i - 1)); } return ans; }