id
int64
1
3.71k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
2,600
K Items With the Maximum Sum
Easy
<p>There is a bag that consists of items, each item&nbsp;has a number <code>1</code>, <code>0</code>, or <code>-1</code> written on it.</p> <p>You are given four <strong>non-negative </strong>integers <code>numOnes</code>, <code>numZeros</code>, <code>numNegOnes</code>, and <code>k</code>.</p> <p>The bag initially contains:</p> <ul> <li><code>numOnes</code> items with <code>1</code>s written on them.</li> <li><code>numZeroes</code> items with <code>0</code>s written on them.</li> <li><code>numNegOnes</code> items with <code>-1</code>s written on them.</li> </ul> <p>We want to pick exactly <code>k</code> items among the available items. Return <em>the <strong>maximum</strong> possible sum of numbers written on the items</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2. It can be proven that 2 is the maximum possible sum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3. It can be proven that 3 is the maximum possible sum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= numOnes, numZeros, numNegOnes &lt;= 50</code></li> <li><code>0 &lt;= k &lt;= numOnes + numZeros + numNegOnes</code></li> </ul>
Greedy; Math
C++
class Solution { public: int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { if (numOnes >= k) { return k; } if (numZeros >= k - numOnes) { return numOnes; } return numOnes - (k - numOnes - numZeros); } };
2,600
K Items With the Maximum Sum
Easy
<p>There is a bag that consists of items, each item&nbsp;has a number <code>1</code>, <code>0</code>, or <code>-1</code> written on it.</p> <p>You are given four <strong>non-negative </strong>integers <code>numOnes</code>, <code>numZeros</code>, <code>numNegOnes</code>, and <code>k</code>.</p> <p>The bag initially contains:</p> <ul> <li><code>numOnes</code> items with <code>1</code>s written on them.</li> <li><code>numZeroes</code> items with <code>0</code>s written on them.</li> <li><code>numNegOnes</code> items with <code>-1</code>s written on them.</li> </ul> <p>We want to pick exactly <code>k</code> items among the available items. Return <em>the <strong>maximum</strong> possible sum of numbers written on the items</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2. It can be proven that 2 is the maximum possible sum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3. It can be proven that 3 is the maximum possible sum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= numOnes, numZeros, numNegOnes &lt;= 50</code></li> <li><code>0 &lt;= k &lt;= numOnes + numZeros + numNegOnes</code></li> </ul>
Greedy; Math
C#
public class Solution { public int KItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { if (numOnes >= k) { return k; } if (numZeros >= k - numOnes) { return numOnes; } return numOnes - (k - numOnes - numZeros); } }
2,600
K Items With the Maximum Sum
Easy
<p>There is a bag that consists of items, each item&nbsp;has a number <code>1</code>, <code>0</code>, or <code>-1</code> written on it.</p> <p>You are given four <strong>non-negative </strong>integers <code>numOnes</code>, <code>numZeros</code>, <code>numNegOnes</code>, and <code>k</code>.</p> <p>The bag initially contains:</p> <ul> <li><code>numOnes</code> items with <code>1</code>s written on them.</li> <li><code>numZeroes</code> items with <code>0</code>s written on them.</li> <li><code>numNegOnes</code> items with <code>-1</code>s written on them.</li> </ul> <p>We want to pick exactly <code>k</code> items among the available items. Return <em>the <strong>maximum</strong> possible sum of numbers written on the items</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2. It can be proven that 2 is the maximum possible sum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3. It can be proven that 3 is the maximum possible sum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= numOnes, numZeros, numNegOnes &lt;= 50</code></li> <li><code>0 &lt;= k &lt;= numOnes + numZeros + numNegOnes</code></li> </ul>
Greedy; Math
Go
func kItemsWithMaximumSum(numOnes int, numZeros int, numNegOnes int, k int) int { if numOnes >= k { return k } if numZeros >= k-numOnes { return numOnes } return numOnes - (k - numOnes - numZeros) }
2,600
K Items With the Maximum Sum
Easy
<p>There is a bag that consists of items, each item&nbsp;has a number <code>1</code>, <code>0</code>, or <code>-1</code> written on it.</p> <p>You are given four <strong>non-negative </strong>integers <code>numOnes</code>, <code>numZeros</code>, <code>numNegOnes</code>, and <code>k</code>.</p> <p>The bag initially contains:</p> <ul> <li><code>numOnes</code> items with <code>1</code>s written on them.</li> <li><code>numZeroes</code> items with <code>0</code>s written on them.</li> <li><code>numNegOnes</code> items with <code>-1</code>s written on them.</li> </ul> <p>We want to pick exactly <code>k</code> items among the available items. Return <em>the <strong>maximum</strong> possible sum of numbers written on the items</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2. It can be proven that 2 is the maximum possible sum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3. It can be proven that 3 is the maximum possible sum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= numOnes, numZeros, numNegOnes &lt;= 50</code></li> <li><code>0 &lt;= k &lt;= numOnes + numZeros + numNegOnes</code></li> </ul>
Greedy; Math
Java
class Solution { public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { if (numOnes >= k) { return k; } if (numZeros >= k - numOnes) { return numOnes; } return numOnes - (k - numOnes - numZeros); } }
2,600
K Items With the Maximum Sum
Easy
<p>There is a bag that consists of items, each item&nbsp;has a number <code>1</code>, <code>0</code>, or <code>-1</code> written on it.</p> <p>You are given four <strong>non-negative </strong>integers <code>numOnes</code>, <code>numZeros</code>, <code>numNegOnes</code>, and <code>k</code>.</p> <p>The bag initially contains:</p> <ul> <li><code>numOnes</code> items with <code>1</code>s written on them.</li> <li><code>numZeroes</code> items with <code>0</code>s written on them.</li> <li><code>numNegOnes</code> items with <code>-1</code>s written on them.</li> </ul> <p>We want to pick exactly <code>k</code> items among the available items. Return <em>the <strong>maximum</strong> possible sum of numbers written on the items</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2. It can be proven that 2 is the maximum possible sum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3. It can be proven that 3 is the maximum possible sum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= numOnes, numZeros, numNegOnes &lt;= 50</code></li> <li><code>0 &lt;= k &lt;= numOnes + numZeros + numNegOnes</code></li> </ul>
Greedy; Math
Python
class Solution: def kItemsWithMaximumSum( self, numOnes: int, numZeros: int, numNegOnes: int, k: int ) -> int: if numOnes >= k: return k if numZeros >= k - numOnes: return numOnes return numOnes - (k - numOnes - numZeros)
2,600
K Items With the Maximum Sum
Easy
<p>There is a bag that consists of items, each item&nbsp;has a number <code>1</code>, <code>0</code>, or <code>-1</code> written on it.</p> <p>You are given four <strong>non-negative </strong>integers <code>numOnes</code>, <code>numZeros</code>, <code>numNegOnes</code>, and <code>k</code>.</p> <p>The bag initially contains:</p> <ul> <li><code>numOnes</code> items with <code>1</code>s written on them.</li> <li><code>numZeroes</code> items with <code>0</code>s written on them.</li> <li><code>numNegOnes</code> items with <code>-1</code>s written on them.</li> </ul> <p>We want to pick exactly <code>k</code> items among the available items. Return <em>the <strong>maximum</strong> possible sum of numbers written on the items</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2. It can be proven that 2 is the maximum possible sum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3. It can be proven that 3 is the maximum possible sum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= numOnes, numZeros, numNegOnes &lt;= 50</code></li> <li><code>0 &lt;= k &lt;= numOnes + numZeros + numNegOnes</code></li> </ul>
Greedy; Math
Rust
impl Solution { pub fn k_items_with_maximum_sum( num_ones: i32, num_zeros: i32, num_neg_ones: i32, k: i32, ) -> i32 { if num_ones > k { return k; } if num_ones + num_zeros > k { return num_ones; } num_ones - (k - num_ones - num_zeros) } }
2,600
K Items With the Maximum Sum
Easy
<p>There is a bag that consists of items, each item&nbsp;has a number <code>1</code>, <code>0</code>, or <code>-1</code> written on it.</p> <p>You are given four <strong>non-negative </strong>integers <code>numOnes</code>, <code>numZeros</code>, <code>numNegOnes</code>, and <code>k</code>.</p> <p>The bag initially contains:</p> <ul> <li><code>numOnes</code> items with <code>1</code>s written on them.</li> <li><code>numZeroes</code> items with <code>0</code>s written on them.</li> <li><code>numNegOnes</code> items with <code>-1</code>s written on them.</li> </ul> <p>We want to pick exactly <code>k</code> items among the available items. Return <em>the <strong>maximum</strong> possible sum of numbers written on the items</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2. It can be proven that 2 is the maximum possible sum. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3. It can be proven that 3 is the maximum possible sum. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= numOnes, numZeros, numNegOnes &lt;= 50</code></li> <li><code>0 &lt;= k &lt;= numOnes + numZeros + numNegOnes</code></li> </ul>
Greedy; Math
TypeScript
function kItemsWithMaximumSum( numOnes: number, numZeros: number, numNegOnes: number, k: number, ): number { if (numOnes >= k) { return k; } if (numZeros >= k - numOnes) { return numOnes; } return numOnes - (k - numOnes - numZeros); }
2,601
Prime Subtraction Operation
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p> <p>You can perform the following operation as many times as you want:</p> <ul> <li>Pick an index <code>i</code> that you haven&rsquo;t picked before, and pick a prime <code>p</code> <strong>strictly less than</strong> <code>nums[i]</code>, then subtract <code>p</code> from <code>nums[i]</code>.</li> </ul> <p>Return <em>true if you can make <code>nums</code> a strictly increasing array using the above operation and false otherwise.</em></p> <p>A <strong>strictly increasing array</strong> is an array whose each element is strictly greater than its preceding element.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,9,6,10] <strong>Output:</strong> true <strong>Explanation:</strong> In the first operation: Pick i = 0 and p = 3, and then subtract 3 from nums[0], so that nums becomes [1,9,6,10]. In the second operation: i = 1, p = 7, subtract 7 from nums[1], so nums becomes equal to [1,2,6,10]. After the second operation, nums is sorted in strictly increasing order, so the answer is true.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,8,11,12] <strong>Output:</strong> true <strong>Explanation: </strong>Initially nums is sorted in strictly increasing order, so we don&#39;t need to make any operations.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,8,3] <strong>Output:</strong> false <strong>Explanation:</strong> It can be proven that there is no way to perform operations to make nums sorted in strictly increasing order, so the answer is false.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code><font face="monospace">nums.length == n</font></code></li> </ul>
Greedy; Array; Math; Binary Search; Number Theory
C++
class Solution { public: bool primeSubOperation(vector<int>& nums) { vector<int> p; for (int i = 2; i <= 1000; ++i) { bool ok = true; for (int j : p) { if (i % j == 0) { ok = false; break; } } if (ok) { p.push_back(i); } } int n = nums.size(); for (int i = n - 2; i >= 0; --i) { if (nums[i] < nums[i + 1]) { continue; } int j = upper_bound(p.begin(), p.end(), nums[i] - nums[i + 1]) - p.begin(); if (j == p.size() || p[j] >= nums[i]) { return false; } nums[i] -= p[j]; } return true; } };
2,601
Prime Subtraction Operation
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p> <p>You can perform the following operation as many times as you want:</p> <ul> <li>Pick an index <code>i</code> that you haven&rsquo;t picked before, and pick a prime <code>p</code> <strong>strictly less than</strong> <code>nums[i]</code>, then subtract <code>p</code> from <code>nums[i]</code>.</li> </ul> <p>Return <em>true if you can make <code>nums</code> a strictly increasing array using the above operation and false otherwise.</em></p> <p>A <strong>strictly increasing array</strong> is an array whose each element is strictly greater than its preceding element.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,9,6,10] <strong>Output:</strong> true <strong>Explanation:</strong> In the first operation: Pick i = 0 and p = 3, and then subtract 3 from nums[0], so that nums becomes [1,9,6,10]. In the second operation: i = 1, p = 7, subtract 7 from nums[1], so nums becomes equal to [1,2,6,10]. After the second operation, nums is sorted in strictly increasing order, so the answer is true.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,8,11,12] <strong>Output:</strong> true <strong>Explanation: </strong>Initially nums is sorted in strictly increasing order, so we don&#39;t need to make any operations.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,8,3] <strong>Output:</strong> false <strong>Explanation:</strong> It can be proven that there is no way to perform operations to make nums sorted in strictly increasing order, so the answer is false.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code><font face="monospace">nums.length == n</font></code></li> </ul>
Greedy; Array; Math; Binary Search; Number Theory
Go
func primeSubOperation(nums []int) bool { p := []int{} for i := 2; i <= 1000; i++ { ok := true for _, j := range p { if i%j == 0 { ok = false break } } if ok { p = append(p, i) } } for i := len(nums) - 2; i >= 0; i-- { if nums[i] < nums[i+1] { continue } j := sort.SearchInts(p, nums[i]-nums[i+1]+1) if j == len(p) || p[j] >= nums[i] { return false } nums[i] -= p[j] } return true }
2,601
Prime Subtraction Operation
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p> <p>You can perform the following operation as many times as you want:</p> <ul> <li>Pick an index <code>i</code> that you haven&rsquo;t picked before, and pick a prime <code>p</code> <strong>strictly less than</strong> <code>nums[i]</code>, then subtract <code>p</code> from <code>nums[i]</code>.</li> </ul> <p>Return <em>true if you can make <code>nums</code> a strictly increasing array using the above operation and false otherwise.</em></p> <p>A <strong>strictly increasing array</strong> is an array whose each element is strictly greater than its preceding element.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,9,6,10] <strong>Output:</strong> true <strong>Explanation:</strong> In the first operation: Pick i = 0 and p = 3, and then subtract 3 from nums[0], so that nums becomes [1,9,6,10]. In the second operation: i = 1, p = 7, subtract 7 from nums[1], so nums becomes equal to [1,2,6,10]. After the second operation, nums is sorted in strictly increasing order, so the answer is true.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,8,11,12] <strong>Output:</strong> true <strong>Explanation: </strong>Initially nums is sorted in strictly increasing order, so we don&#39;t need to make any operations.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,8,3] <strong>Output:</strong> false <strong>Explanation:</strong> It can be proven that there is no way to perform operations to make nums sorted in strictly increasing order, so the answer is false.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code><font face="monospace">nums.length == n</font></code></li> </ul>
Greedy; Array; Math; Binary Search; Number Theory
Java
class Solution { public boolean primeSubOperation(int[] nums) { List<Integer> p = new ArrayList<>(); for (int i = 2; i <= 1000; ++i) { boolean ok = true; for (int j : p) { if (i % j == 0) { ok = false; break; } } if (ok) { p.add(i); } } int n = nums.length; for (int i = n - 2; i >= 0; --i) { if (nums[i] < nums[i + 1]) { continue; } int j = search(p, nums[i] - nums[i + 1]); if (j == p.size() || p.get(j) >= nums[i]) { return false; } nums[i] -= p.get(j); } return true; } private int search(List<Integer> nums, int x) { int l = 0, r = nums.size(); while (l < r) { int mid = (l + r) >> 1; if (nums.get(mid) > x) { r = mid; } else { l = mid + 1; } } return l; } }
2,601
Prime Subtraction Operation
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p> <p>You can perform the following operation as many times as you want:</p> <ul> <li>Pick an index <code>i</code> that you haven&rsquo;t picked before, and pick a prime <code>p</code> <strong>strictly less than</strong> <code>nums[i]</code>, then subtract <code>p</code> from <code>nums[i]</code>.</li> </ul> <p>Return <em>true if you can make <code>nums</code> a strictly increasing array using the above operation and false otherwise.</em></p> <p>A <strong>strictly increasing array</strong> is an array whose each element is strictly greater than its preceding element.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,9,6,10] <strong>Output:</strong> true <strong>Explanation:</strong> In the first operation: Pick i = 0 and p = 3, and then subtract 3 from nums[0], so that nums becomes [1,9,6,10]. In the second operation: i = 1, p = 7, subtract 7 from nums[1], so nums becomes equal to [1,2,6,10]. After the second operation, nums is sorted in strictly increasing order, so the answer is true.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,8,11,12] <strong>Output:</strong> true <strong>Explanation: </strong>Initially nums is sorted in strictly increasing order, so we don&#39;t need to make any operations.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,8,3] <strong>Output:</strong> false <strong>Explanation:</strong> It can be proven that there is no way to perform operations to make nums sorted in strictly increasing order, so the answer is false.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code><font face="monospace">nums.length == n</font></code></li> </ul>
Greedy; Array; Math; Binary Search; Number Theory
Python
class Solution: def primeSubOperation(self, nums: List[int]) -> bool: p = [] for i in range(2, max(nums)): for j in p: if i % j == 0: break else: p.append(i) n = len(nums) for i in range(n - 2, -1, -1): if nums[i] < nums[i + 1]: continue j = bisect_right(p, nums[i] - nums[i + 1]) if j == len(p) or p[j] >= nums[i]: return False nums[i] -= p[j] return True
2,601
Prime Subtraction Operation
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code>.</p> <p>You can perform the following operation as many times as you want:</p> <ul> <li>Pick an index <code>i</code> that you haven&rsquo;t picked before, and pick a prime <code>p</code> <strong>strictly less than</strong> <code>nums[i]</code>, then subtract <code>p</code> from <code>nums[i]</code>.</li> </ul> <p>Return <em>true if you can make <code>nums</code> a strictly increasing array using the above operation and false otherwise.</em></p> <p>A <strong>strictly increasing array</strong> is an array whose each element is strictly greater than its preceding element.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,9,6,10] <strong>Output:</strong> true <strong>Explanation:</strong> In the first operation: Pick i = 0 and p = 3, and then subtract 3 from nums[0], so that nums becomes [1,9,6,10]. In the second operation: i = 1, p = 7, subtract 7 from nums[1], so nums becomes equal to [1,2,6,10]. After the second operation, nums is sorted in strictly increasing order, so the answer is true.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,8,11,12] <strong>Output:</strong> true <strong>Explanation: </strong>Initially nums is sorted in strictly increasing order, so we don&#39;t need to make any operations.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [5,8,3] <strong>Output:</strong> false <strong>Explanation:</strong> It can be proven that there is no way to perform operations to make nums sorted in strictly increasing order, so the answer is false.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code><font face="monospace">nums.length == n</font></code></li> </ul>
Greedy; Array; Math; Binary Search; Number Theory
TypeScript
function primeSubOperation(nums: number[]): boolean { const p: number[] = []; for (let i = 2; i <= 1000; ++i) { let ok = true; for (const j of p) { if (i % j === 0) { ok = false; break; } } if (ok) { p.push(i); } } const search = (x: number): number => { let l = 0; let r = p.length; while (l < r) { const mid = (l + r) >> 1; if (p[mid] > x) { r = mid; } else { l = mid + 1; } } return l; }; const n = nums.length; for (let i = n - 2; i >= 0; --i) { if (nums[i] < nums[i + 1]) { continue; } const j = search(nums[i] - nums[i + 1]); if (j === p.length || p[j] >= nums[i]) { return false; } nums[i] -= p[j]; } return true; }
2,602
Minimum Operations to Make All Array Elements Equal
Medium
<p>You are given an array <code>nums</code> consisting of positive integers.</p> <p>You are also given an integer array <code>queries</code> of size <code>m</code>. For the <code>i<sup>th</sup></code> query, you want to make all of the elements of <code>nums</code> equal to<code> queries[i]</code>. You can perform the following operation on the array <strong>any</strong> number of times:</p> <ul> <li><strong>Increase</strong> or <strong>decrease</strong> an element of the array by <code>1</code>.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>minimum</strong> number of operations to make all elements of </em><code>nums</code><em> equal to </em><code>queries[i]</code>.</p> <p><strong>Note</strong> that after each query the array is reset to its original state.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,6,8], queries = [1,5] <strong>Output:</strong> [14,10] <strong>Explanation:</strong> For the first query we can do the following operations: - Decrease nums[0] 2 times, so that nums = [1,1,6,8]. - Decrease nums[2] 5 times, so that nums = [1,1,1,8]. - Decrease nums[3] 7 times, so that nums = [1,1,1,1]. So the total number of operations for the first query is 2 + 5 + 7 = 14. For the second query we can do the following operations: - Increase nums[0] 2 times, so that nums = [5,1,6,8]. - Increase nums[1] 4 times, so that nums = [5,5,6,8]. - Decrease nums[2] 1 time, so that nums = [5,5,5,8]. - Decrease nums[3] 3 times, so that nums = [5,5,5,5]. So the total number of operations for the second query is 2 + 4 + 1 + 3 = 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,9,6,3], queries = [10] <strong>Output:</strong> [20] <strong>Explanation:</strong> We can increase each value in the array to 10. The total number of operations will be 8 + 1 + 4 + 7 = 20. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>m == queries.length</code></li> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i], queries[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting
C++
class Solution { public: vector<long long> minOperations(vector<int>& nums, vector<int>& queries) { sort(nums.begin(), nums.end()); int n = nums.size(); vector<long long> s(n + 1); for (int i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } vector<long long> ans; for (auto& x : queries) { int i = lower_bound(nums.begin(), nums.end(), x + 1) - nums.begin(); long long t = s[n] - s[i] - 1LL * (n - i) * x; i = lower_bound(nums.begin(), nums.end(), x) - nums.begin(); t += 1LL * x * i - s[i]; ans.push_back(t); } return ans; } };
2,602
Minimum Operations to Make All Array Elements Equal
Medium
<p>You are given an array <code>nums</code> consisting of positive integers.</p> <p>You are also given an integer array <code>queries</code> of size <code>m</code>. For the <code>i<sup>th</sup></code> query, you want to make all of the elements of <code>nums</code> equal to<code> queries[i]</code>. You can perform the following operation on the array <strong>any</strong> number of times:</p> <ul> <li><strong>Increase</strong> or <strong>decrease</strong> an element of the array by <code>1</code>.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>minimum</strong> number of operations to make all elements of </em><code>nums</code><em> equal to </em><code>queries[i]</code>.</p> <p><strong>Note</strong> that after each query the array is reset to its original state.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,6,8], queries = [1,5] <strong>Output:</strong> [14,10] <strong>Explanation:</strong> For the first query we can do the following operations: - Decrease nums[0] 2 times, so that nums = [1,1,6,8]. - Decrease nums[2] 5 times, so that nums = [1,1,1,8]. - Decrease nums[3] 7 times, so that nums = [1,1,1,1]. So the total number of operations for the first query is 2 + 5 + 7 = 14. For the second query we can do the following operations: - Increase nums[0] 2 times, so that nums = [5,1,6,8]. - Increase nums[1] 4 times, so that nums = [5,5,6,8]. - Decrease nums[2] 1 time, so that nums = [5,5,5,8]. - Decrease nums[3] 3 times, so that nums = [5,5,5,5]. So the total number of operations for the second query is 2 + 4 + 1 + 3 = 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,9,6,3], queries = [10] <strong>Output:</strong> [20] <strong>Explanation:</strong> We can increase each value in the array to 10. The total number of operations will be 8 + 1 + 4 + 7 = 20. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>m == queries.length</code></li> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i], queries[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting
Go
func minOperations(nums []int, queries []int) (ans []int64) { sort.Ints(nums) n := len(nums) s := make([]int, n+1) for i, x := range nums { s[i+1] = s[i] + x } for _, x := range queries { i := sort.SearchInts(nums, x+1) t := s[n] - s[i] - (n-i)*x i = sort.SearchInts(nums, x) t += x*i - s[i] ans = append(ans, int64(t)) } return }
2,602
Minimum Operations to Make All Array Elements Equal
Medium
<p>You are given an array <code>nums</code> consisting of positive integers.</p> <p>You are also given an integer array <code>queries</code> of size <code>m</code>. For the <code>i<sup>th</sup></code> query, you want to make all of the elements of <code>nums</code> equal to<code> queries[i]</code>. You can perform the following operation on the array <strong>any</strong> number of times:</p> <ul> <li><strong>Increase</strong> or <strong>decrease</strong> an element of the array by <code>1</code>.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>minimum</strong> number of operations to make all elements of </em><code>nums</code><em> equal to </em><code>queries[i]</code>.</p> <p><strong>Note</strong> that after each query the array is reset to its original state.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,6,8], queries = [1,5] <strong>Output:</strong> [14,10] <strong>Explanation:</strong> For the first query we can do the following operations: - Decrease nums[0] 2 times, so that nums = [1,1,6,8]. - Decrease nums[2] 5 times, so that nums = [1,1,1,8]. - Decrease nums[3] 7 times, so that nums = [1,1,1,1]. So the total number of operations for the first query is 2 + 5 + 7 = 14. For the second query we can do the following operations: - Increase nums[0] 2 times, so that nums = [5,1,6,8]. - Increase nums[1] 4 times, so that nums = [5,5,6,8]. - Decrease nums[2] 1 time, so that nums = [5,5,5,8]. - Decrease nums[3] 3 times, so that nums = [5,5,5,5]. So the total number of operations for the second query is 2 + 4 + 1 + 3 = 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,9,6,3], queries = [10] <strong>Output:</strong> [20] <strong>Explanation:</strong> We can increase each value in the array to 10. The total number of operations will be 8 + 1 + 4 + 7 = 20. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>m == queries.length</code></li> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i], queries[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting
Java
class Solution { public List<Long> minOperations(int[] nums, int[] queries) { Arrays.sort(nums); int n = nums.length; long[] s = new long[n + 1]; for (int i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } List<Long> ans = new ArrayList<>(); for (int x : queries) { int i = search(nums, x + 1); long t = s[n] - s[i] - 1L * (n - i) * x; i = search(nums, x); t += 1L * x * i - s[i]; ans.add(t); } return ans; } private int search(int[] nums, int x) { int l = 0, r = nums.length; while (l < r) { int mid = (l + r) >> 1; if (nums[mid] >= x) { r = mid; } else { l = mid + 1; } } return l; } }
2,602
Minimum Operations to Make All Array Elements Equal
Medium
<p>You are given an array <code>nums</code> consisting of positive integers.</p> <p>You are also given an integer array <code>queries</code> of size <code>m</code>. For the <code>i<sup>th</sup></code> query, you want to make all of the elements of <code>nums</code> equal to<code> queries[i]</code>. You can perform the following operation on the array <strong>any</strong> number of times:</p> <ul> <li><strong>Increase</strong> or <strong>decrease</strong> an element of the array by <code>1</code>.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>minimum</strong> number of operations to make all elements of </em><code>nums</code><em> equal to </em><code>queries[i]</code>.</p> <p><strong>Note</strong> that after each query the array is reset to its original state.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,6,8], queries = [1,5] <strong>Output:</strong> [14,10] <strong>Explanation:</strong> For the first query we can do the following operations: - Decrease nums[0] 2 times, so that nums = [1,1,6,8]. - Decrease nums[2] 5 times, so that nums = [1,1,1,8]. - Decrease nums[3] 7 times, so that nums = [1,1,1,1]. So the total number of operations for the first query is 2 + 5 + 7 = 14. For the second query we can do the following operations: - Increase nums[0] 2 times, so that nums = [5,1,6,8]. - Increase nums[1] 4 times, so that nums = [5,5,6,8]. - Decrease nums[2] 1 time, so that nums = [5,5,5,8]. - Decrease nums[3] 3 times, so that nums = [5,5,5,5]. So the total number of operations for the second query is 2 + 4 + 1 + 3 = 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,9,6,3], queries = [10] <strong>Output:</strong> [20] <strong>Explanation:</strong> We can increase each value in the array to 10. The total number of operations will be 8 + 1 + 4 + 7 = 20. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>m == queries.length</code></li> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i], queries[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting
Python
class Solution: def minOperations(self, nums: List[int], queries: List[int]) -> List[int]: nums.sort() s = list(accumulate(nums, initial=0)) ans = [] for x in queries: i = bisect_left(nums, x + 1) t = s[-1] - s[i] - (len(nums) - i) * x i = bisect_left(nums, x) t += x * i - s[i] ans.append(t) return ans
2,602
Minimum Operations to Make All Array Elements Equal
Medium
<p>You are given an array <code>nums</code> consisting of positive integers.</p> <p>You are also given an integer array <code>queries</code> of size <code>m</code>. For the <code>i<sup>th</sup></code> query, you want to make all of the elements of <code>nums</code> equal to<code> queries[i]</code>. You can perform the following operation on the array <strong>any</strong> number of times:</p> <ul> <li><strong>Increase</strong> or <strong>decrease</strong> an element of the array by <code>1</code>.</li> </ul> <p>Return <em>an array </em><code>answer</code><em> of size </em><code>m</code><em> where </em><code>answer[i]</code><em> is the <strong>minimum</strong> number of operations to make all elements of </em><code>nums</code><em> equal to </em><code>queries[i]</code>.</p> <p><strong>Note</strong> that after each query the array is reset to its original state.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,6,8], queries = [1,5] <strong>Output:</strong> [14,10] <strong>Explanation:</strong> For the first query we can do the following operations: - Decrease nums[0] 2 times, so that nums = [1,1,6,8]. - Decrease nums[2] 5 times, so that nums = [1,1,1,8]. - Decrease nums[3] 7 times, so that nums = [1,1,1,1]. So the total number of operations for the first query is 2 + 5 + 7 = 14. For the second query we can do the following operations: - Increase nums[0] 2 times, so that nums = [5,1,6,8]. - Increase nums[1] 4 times, so that nums = [5,5,6,8]. - Decrease nums[2] 1 time, so that nums = [5,5,5,8]. - Decrease nums[3] 3 times, so that nums = [5,5,5,5]. So the total number of operations for the second query is 2 + 4 + 1 + 3 = 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,9,6,3], queries = [10] <strong>Output:</strong> [20] <strong>Explanation:</strong> We can increase each value in the array to 10. The total number of operations will be 8 + 1 + 4 + 7 = 20. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>m == queries.length</code></li> <li><code>1 &lt;= n, m &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i], queries[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search; Prefix Sum; Sorting
TypeScript
function minOperations(nums: number[], queries: number[]): number[] { nums.sort((a, b) => a - b); const n = nums.length; const s: number[] = new Array(n + 1).fill(0); for (let i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } const search = (x: number): number => { let l = 0; let r = n; while (l < r) { const mid = (l + r) >> 1; if (nums[mid] >= x) { r = mid; } else { l = mid + 1; } } return l; }; const ans: number[] = []; for (const x of queries) { const i = search(x + 1); let t = s[n] - s[i] - (n - i) * x; const j = search(x); t += x * j - s[j]; ans.push(t); } return ans; }
2,603
Collect Coins in a Tree
Hard
<p>There exists an undirected and unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given an integer <code>n</code> and a 2D integer array edges of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree. You are also given&nbsp;an array <code>coins</code> of size <code>n</code> where <code>coins[i]</code> can be either <code>0</code> or <code>1</code>, where <code>1</code> indicates the presence of a coin in the vertex <code>i</code>.</p> <p>Initially, you choose to start at any vertex in&nbsp;the tree.&nbsp;Then, you can perform&nbsp;the following operations any number of times:&nbsp;</p> <ul> <li>Collect all the coins that are at a distance of at most <code>2</code> from the current vertex, or</li> <li>Move to any adjacent vertex in the tree.</li> </ul> <p>Find <em>the minimum number of edges you need to go through to collect all the coins and go back to the initial vertex</em>.</p> <p>Note that if you pass an edge several times, you need to count it into the answer several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/images/graph-2.png" style="width: 522px; height: 522px;" /> <pre> <strong>Input:</strong> coins = [1,0,0,0,0,1], edges = [[0,1],[1,2],[2,3],[3,4],[4,5]] <strong>Output:</strong> 2 <strong>Explanation:</strong> Start at vertex 2, collect the coin at vertex 0, move to vertex 3, collect the coin at vertex 5 then move back to vertex 2. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/images/graph-4.png" style="width: 522px; height: 522px;" /> <pre> <strong>Input:</strong> coins = [0,0,0,1,1,0,0,1], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[5,6],[5,7]] <strong>Output:</strong> 2 <strong>Explanation:</strong> Start at vertex 0, collect the coins at vertices 4 and 3, move to vertex 2, collect the coin at vertex 7, then move back to vertex 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == coins.length</code></li> <li><code>1 &lt;= n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= coins[i] &lt;= 1</code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li><code>edges</code> represents a valid tree.</li> </ul>
Tree; Graph; Topological Sort; Array
C++
class Solution { public: int collectTheCoins(vector<int>& coins, vector<vector<int>>& edges) { int n = coins.size(); unordered_set<int> g[n]; for (auto& e : edges) { int a = e[0], b = e[1]; g[a].insert(b); g[b].insert(a); } queue<int> q; for (int i = 0; i < n; ++i) { if (coins[i] == 0 && g[i].size() == 1) { q.push(i); } } while (!q.empty()) { int i = q.front(); q.pop(); for (int j : g[i]) { g[j].erase(i); if (coins[j] == 0 && g[j].size() == 1) { q.push(j); } } g[i].clear(); } for (int k = 0; k < 2; ++k) { vector<int> q; for (int i = 0; i < n; ++i) { if (g[i].size() == 1) { q.push_back(i); } } for (int i : q) { for (int j : g[i]) { g[j].erase(i); } g[i].clear(); } } int ans = 0; for (auto& e : edges) { int a = e[0], b = e[1]; if (g[a].size() && g[b].size()) { ans += 2; } } return ans; } };
2,603
Collect Coins in a Tree
Hard
<p>There exists an undirected and unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given an integer <code>n</code> and a 2D integer array edges of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree. You are also given&nbsp;an array <code>coins</code> of size <code>n</code> where <code>coins[i]</code> can be either <code>0</code> or <code>1</code>, where <code>1</code> indicates the presence of a coin in the vertex <code>i</code>.</p> <p>Initially, you choose to start at any vertex in&nbsp;the tree.&nbsp;Then, you can perform&nbsp;the following operations any number of times:&nbsp;</p> <ul> <li>Collect all the coins that are at a distance of at most <code>2</code> from the current vertex, or</li> <li>Move to any adjacent vertex in the tree.</li> </ul> <p>Find <em>the minimum number of edges you need to go through to collect all the coins and go back to the initial vertex</em>.</p> <p>Note that if you pass an edge several times, you need to count it into the answer several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/images/graph-2.png" style="width: 522px; height: 522px;" /> <pre> <strong>Input:</strong> coins = [1,0,0,0,0,1], edges = [[0,1],[1,2],[2,3],[3,4],[4,5]] <strong>Output:</strong> 2 <strong>Explanation:</strong> Start at vertex 2, collect the coin at vertex 0, move to vertex 3, collect the coin at vertex 5 then move back to vertex 2. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/images/graph-4.png" style="width: 522px; height: 522px;" /> <pre> <strong>Input:</strong> coins = [0,0,0,1,1,0,0,1], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[5,6],[5,7]] <strong>Output:</strong> 2 <strong>Explanation:</strong> Start at vertex 0, collect the coins at vertices 4 and 3, move to vertex 2, collect the coin at vertex 7, then move back to vertex 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == coins.length</code></li> <li><code>1 &lt;= n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= coins[i] &lt;= 1</code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li><code>edges</code> represents a valid tree.</li> </ul>
Tree; Graph; Topological Sort; Array
Go
func collectTheCoins(coins []int, edges [][]int) int { n := len(coins) g := make([]map[int]bool, n) for i := range g { g[i] = map[int]bool{} } for _, e := range edges { a, b := e[0], e[1] g[a][b] = true g[b][a] = true } q := []int{} for i, c := range coins { if c == 0 && len(g[i]) == 1 { q = append(q, i) } } for len(q) > 0 { i := q[0] q = q[1:] for j := range g[i] { delete(g[j], i) if coins[j] == 0 && len(g[j]) == 1 { q = append(q, j) } } g[i] = map[int]bool{} } for k := 0; k < 2; k++ { q := []int{} for i := range coins { if len(g[i]) == 1 { q = append(q, i) } } for _, i := range q { for j := range g[i] { delete(g[j], i) } g[i] = map[int]bool{} } } ans := 0 for _, e := range edges { a, b := e[0], e[1] if len(g[a]) > 0 && len(g[b]) > 0 { ans += 2 } } return ans }
2,603
Collect Coins in a Tree
Hard
<p>There exists an undirected and unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given an integer <code>n</code> and a 2D integer array edges of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree. You are also given&nbsp;an array <code>coins</code> of size <code>n</code> where <code>coins[i]</code> can be either <code>0</code> or <code>1</code>, where <code>1</code> indicates the presence of a coin in the vertex <code>i</code>.</p> <p>Initially, you choose to start at any vertex in&nbsp;the tree.&nbsp;Then, you can perform&nbsp;the following operations any number of times:&nbsp;</p> <ul> <li>Collect all the coins that are at a distance of at most <code>2</code> from the current vertex, or</li> <li>Move to any adjacent vertex in the tree.</li> </ul> <p>Find <em>the minimum number of edges you need to go through to collect all the coins and go back to the initial vertex</em>.</p> <p>Note that if you pass an edge several times, you need to count it into the answer several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/images/graph-2.png" style="width: 522px; height: 522px;" /> <pre> <strong>Input:</strong> coins = [1,0,0,0,0,1], edges = [[0,1],[1,2],[2,3],[3,4],[4,5]] <strong>Output:</strong> 2 <strong>Explanation:</strong> Start at vertex 2, collect the coin at vertex 0, move to vertex 3, collect the coin at vertex 5 then move back to vertex 2. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/images/graph-4.png" style="width: 522px; height: 522px;" /> <pre> <strong>Input:</strong> coins = [0,0,0,1,1,0,0,1], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[5,6],[5,7]] <strong>Output:</strong> 2 <strong>Explanation:</strong> Start at vertex 0, collect the coins at vertices 4 and 3, move to vertex 2, collect the coin at vertex 7, then move back to vertex 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == coins.length</code></li> <li><code>1 &lt;= n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= coins[i] &lt;= 1</code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li><code>edges</code> represents a valid tree.</li> </ul>
Tree; Graph; Topological Sort; Array
Java
class Solution { public int collectTheCoins(int[] coins, int[][] edges) { int n = coins.length; Set<Integer>[] g = new Set[n]; Arrays.setAll(g, k -> new HashSet<>()); for (var e : edges) { int a = e[0], b = e[1]; g[a].add(b); g[b].add(a); } Deque<Integer> q = new ArrayDeque<>(); for (int i = 0; i < n; ++i) { if (coins[i] == 0 && g[i].size() == 1) { q.offer(i); } } while (!q.isEmpty()) { int i = q.poll(); for (int j : g[i]) { g[j].remove(i); if (coins[j] == 0 && g[j].size() == 1) { q.offer(j); } } g[i].clear(); } q.clear(); for (int k = 0; k < 2; ++k) { for (int i = 0; i < n; ++i) { if (g[i].size() == 1) { q.offer(i); } } for (int i : q) { for (int j : g[i]) { g[j].remove(i); } g[i].clear(); } } int ans = 0; for (var e : edges) { int a = e[0], b = e[1]; if (g[a].size() > 0 && g[b].size() > 0) { ans += 2; } } return ans; } }
2,603
Collect Coins in a Tree
Hard
<p>There exists an undirected and unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given an integer <code>n</code> and a 2D integer array edges of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree. You are also given&nbsp;an array <code>coins</code> of size <code>n</code> where <code>coins[i]</code> can be either <code>0</code> or <code>1</code>, where <code>1</code> indicates the presence of a coin in the vertex <code>i</code>.</p> <p>Initially, you choose to start at any vertex in&nbsp;the tree.&nbsp;Then, you can perform&nbsp;the following operations any number of times:&nbsp;</p> <ul> <li>Collect all the coins that are at a distance of at most <code>2</code> from the current vertex, or</li> <li>Move to any adjacent vertex in the tree.</li> </ul> <p>Find <em>the minimum number of edges you need to go through to collect all the coins and go back to the initial vertex</em>.</p> <p>Note that if you pass an edge several times, you need to count it into the answer several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/images/graph-2.png" style="width: 522px; height: 522px;" /> <pre> <strong>Input:</strong> coins = [1,0,0,0,0,1], edges = [[0,1],[1,2],[2,3],[3,4],[4,5]] <strong>Output:</strong> 2 <strong>Explanation:</strong> Start at vertex 2, collect the coin at vertex 0, move to vertex 3, collect the coin at vertex 5 then move back to vertex 2. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/images/graph-4.png" style="width: 522px; height: 522px;" /> <pre> <strong>Input:</strong> coins = [0,0,0,1,1,0,0,1], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[5,6],[5,7]] <strong>Output:</strong> 2 <strong>Explanation:</strong> Start at vertex 0, collect the coins at vertices 4 and 3, move to vertex 2, collect the coin at vertex 7, then move back to vertex 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == coins.length</code></li> <li><code>1 &lt;= n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= coins[i] &lt;= 1</code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li><code>edges</code> represents a valid tree.</li> </ul>
Tree; Graph; Topological Sort; Array
Python
class Solution: def collectTheCoins(self, coins: List[int], edges: List[List[int]]) -> int: g = defaultdict(set) for a, b in edges: g[a].add(b) g[b].add(a) n = len(coins) q = deque(i for i in range(n) if len(g[i]) == 1 and coins[i] == 0) while q: i = q.popleft() for j in g[i]: g[j].remove(i) if coins[j] == 0 and len(g[j]) == 1: q.append(j) g[i].clear() for k in range(2): q = [i for i in range(n) if len(g[i]) == 1] for i in q: for j in g[i]: g[j].remove(i) g[i].clear() return sum(len(g[a]) > 0 and len(g[b]) > 0 for a, b in edges) * 2
2,603
Collect Coins in a Tree
Hard
<p>There exists an undirected and unrooted tree with <code>n</code> nodes indexed from <code>0</code> to <code>n - 1</code>. You are given an integer <code>n</code> and a 2D integer array edges of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree. You are also given&nbsp;an array <code>coins</code> of size <code>n</code> where <code>coins[i]</code> can be either <code>0</code> or <code>1</code>, where <code>1</code> indicates the presence of a coin in the vertex <code>i</code>.</p> <p>Initially, you choose to start at any vertex in&nbsp;the tree.&nbsp;Then, you can perform&nbsp;the following operations any number of times:&nbsp;</p> <ul> <li>Collect all the coins that are at a distance of at most <code>2</code> from the current vertex, or</li> <li>Move to any adjacent vertex in the tree.</li> </ul> <p>Find <em>the minimum number of edges you need to go through to collect all the coins and go back to the initial vertex</em>.</p> <p>Note that if you pass an edge several times, you need to count it into the answer several times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/images/graph-2.png" style="width: 522px; height: 522px;" /> <pre> <strong>Input:</strong> coins = [1,0,0,0,0,1], edges = [[0,1],[1,2],[2,3],[3,4],[4,5]] <strong>Output:</strong> 2 <strong>Explanation:</strong> Start at vertex 2, collect the coin at vertex 0, move to vertex 3, collect the coin at vertex 5 then move back to vertex 2. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2603.Collect%20Coins%20in%20a%20Tree/images/graph-4.png" style="width: 522px; height: 522px;" /> <pre> <strong>Input:</strong> coins = [0,0,0,1,1,0,0,1], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[5,6],[5,7]] <strong>Output:</strong> 2 <strong>Explanation:</strong> Start at vertex 0, collect the coins at vertices 4 and 3, move to vertex 2, collect the coin at vertex 7, then move back to vertex 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == coins.length</code></li> <li><code>1 &lt;= n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= coins[i] &lt;= 1</code></li> <li><code>edges.length == n - 1</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li><code>edges</code> represents a valid tree.</li> </ul>
Tree; Graph; Topological Sort; Array
TypeScript
function collectTheCoins(coins: number[], edges: number[][]): number { const n = coins.length; const g: Set<number>[] = new Array(n).fill(0).map(() => new Set<number>()); for (const [a, b] of edges) { g[a].add(b); g[b].add(a); } let q: number[] = []; for (let i = 0; i < n; ++i) { if (coins[i] === 0 && g[i].size === 1) { q.push(i); } } while (q.length) { const i = q.pop()!; for (const j of g[i]) { g[j].delete(i); if (coins[j] === 0 && g[j].size === 1) { q.push(j); } } g[i].clear(); } q = []; for (let k = 0; k < 2; ++k) { for (let i = 0; i < n; ++i) { if (g[i].size === 1) { q.push(i); } } for (const i of q) { for (const j of g[i]) { g[j].delete(i); } g[i].clear(); } } let ans = 0; for (const [a, b] of edges) { if (g[a].size > 0 && g[b].size > 0) { ans += 2; } } return ans; }
2,604
Minimum Time to Eat All Grains
Hard
<p>There are <code>n</code> hens and <code>m</code> grains on a line. You are given the initial positions of the hens and the grains in two integer arrays <code>hens</code> and <code>grains</code> of size <code>n</code> and <code>m</code> respectively.</p> <p>Any hen can eat a grain if they are on the same position. The time taken for this is negligible. One hen can also eat multiple grains.</p> <p>In <code>1</code> second, a hen can move right or left by <code>1</code> unit. The hens can move simultaneously and independently of each other.</p> <p>Return <em>the <strong>minimum</strong> time to eat all grains if the hens act optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> hens = [3,6,7], grains = [2,4,7,9] <strong>Output:</strong> 2 <strong>Explanation:</strong> One of the ways hens eat all grains in 2 seconds is described below: - The first hen eats the grain at position 2 in 1 second. - The second hen eats the grain at position 4 in 2 seconds. - The third hen eats the grains at positions 7 and 9 in 2 seconds. So, the maximum time needed is 2. It can be proven that the hens cannot eat all grains before 2 seconds.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> hens = [4,6,109,111,213,215], grains = [5,110,214] <strong>Output:</strong> 1 <strong>Explanation:</strong> One of the ways hens eat all grains in 1 second is described below: - The first hen eats the grain at position 5 in 1 second. - The fourth hen eats the grain at position 110 in 1 second. - The sixth hen eats the grain at position 214 in 1 second. - The other hens do not move. So, the maximum time needed is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= hens.length, grains.length &lt;= 2*10<sup>4</sup></code></li> <li><code>0 &lt;= hens[i], grains[j] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
C++
class Solution { public: int minimumTime(vector<int>& hens, vector<int>& grains) { int m = grains.size(); sort(hens.begin(), hens.end()); sort(grains.begin(), grains.end()); int l = 0; int r = abs(hens[0] - grains[0]) + grains[m - 1] - grains[0]; auto check = [&](int t) -> bool { int j = 0; for (int x : hens) { if (j == m) { return true; } int y = grains[j]; if (y <= x) { int d = x - y; if (d > t) { return false; } while (j < m && grains[j] <= x) { ++j; } while (j < m && min(d, grains[j] - x) + grains[j] - y <= t) { ++j; } } else { while (j < m && grains[j] - x <= t) { ++j; } } } return j == m; }; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } };
2,604
Minimum Time to Eat All Grains
Hard
<p>There are <code>n</code> hens and <code>m</code> grains on a line. You are given the initial positions of the hens and the grains in two integer arrays <code>hens</code> and <code>grains</code> of size <code>n</code> and <code>m</code> respectively.</p> <p>Any hen can eat a grain if they are on the same position. The time taken for this is negligible. One hen can also eat multiple grains.</p> <p>In <code>1</code> second, a hen can move right or left by <code>1</code> unit. The hens can move simultaneously and independently of each other.</p> <p>Return <em>the <strong>minimum</strong> time to eat all grains if the hens act optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> hens = [3,6,7], grains = [2,4,7,9] <strong>Output:</strong> 2 <strong>Explanation:</strong> One of the ways hens eat all grains in 2 seconds is described below: - The first hen eats the grain at position 2 in 1 second. - The second hen eats the grain at position 4 in 2 seconds. - The third hen eats the grains at positions 7 and 9 in 2 seconds. So, the maximum time needed is 2. It can be proven that the hens cannot eat all grains before 2 seconds.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> hens = [4,6,109,111,213,215], grains = [5,110,214] <strong>Output:</strong> 1 <strong>Explanation:</strong> One of the ways hens eat all grains in 1 second is described below: - The first hen eats the grain at position 5 in 1 second. - The fourth hen eats the grain at position 110 in 1 second. - The sixth hen eats the grain at position 214 in 1 second. - The other hens do not move. So, the maximum time needed is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= hens.length, grains.length &lt;= 2*10<sup>4</sup></code></li> <li><code>0 &lt;= hens[i], grains[j] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
Go
func minimumTime(hens []int, grains []int) int { sort.Ints(hens) sort.Ints(grains) m := len(grains) l, r := 0, abs(hens[0]-grains[0])+grains[m-1]-grains[0] check := func(t int) bool { j := 0 for _, x := range hens { if j == m { return true } y := grains[j] if y <= x { d := x - y if d > t { return false } for j < m && grains[j] <= x { j++ } for j < m && min(d, grains[j]-x)+grains[j]-y <= t { j++ } } else { for j < m && grains[j]-x <= t { j++ } } } return j == m } for l < r { mid := (l + r) >> 1 if check(mid) { r = mid } else { l = mid + 1 } } return l } func abs(x int) int { if x < 0 { return -x } return x }
2,604
Minimum Time to Eat All Grains
Hard
<p>There are <code>n</code> hens and <code>m</code> grains on a line. You are given the initial positions of the hens and the grains in two integer arrays <code>hens</code> and <code>grains</code> of size <code>n</code> and <code>m</code> respectively.</p> <p>Any hen can eat a grain if they are on the same position. The time taken for this is negligible. One hen can also eat multiple grains.</p> <p>In <code>1</code> second, a hen can move right or left by <code>1</code> unit. The hens can move simultaneously and independently of each other.</p> <p>Return <em>the <strong>minimum</strong> time to eat all grains if the hens act optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> hens = [3,6,7], grains = [2,4,7,9] <strong>Output:</strong> 2 <strong>Explanation:</strong> One of the ways hens eat all grains in 2 seconds is described below: - The first hen eats the grain at position 2 in 1 second. - The second hen eats the grain at position 4 in 2 seconds. - The third hen eats the grains at positions 7 and 9 in 2 seconds. So, the maximum time needed is 2. It can be proven that the hens cannot eat all grains before 2 seconds.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> hens = [4,6,109,111,213,215], grains = [5,110,214] <strong>Output:</strong> 1 <strong>Explanation:</strong> One of the ways hens eat all grains in 1 second is described below: - The first hen eats the grain at position 5 in 1 second. - The fourth hen eats the grain at position 110 in 1 second. - The sixth hen eats the grain at position 214 in 1 second. - The other hens do not move. So, the maximum time needed is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= hens.length, grains.length &lt;= 2*10<sup>4</sup></code></li> <li><code>0 &lt;= hens[i], grains[j] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
Java
class Solution { private int[] hens; private int[] grains; private int m; public int minimumTime(int[] hens, int[] grains) { m = grains.length; this.hens = hens; this.grains = grains; Arrays.sort(hens); Arrays.sort(grains); int l = 0; int r = Math.abs(hens[0] - grains[0]) + grains[m - 1] - grains[0]; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } private boolean check(int t) { int j = 0; for (int x : hens) { if (j == m) { return true; } int y = grains[j]; if (y <= x) { int d = x - y; if (d > t) { return false; } while (j < m && grains[j] <= x) { ++j; } while (j < m && Math.min(d, grains[j] - x) + grains[j] - y <= t) { ++j; } } else { while (j < m && grains[j] - x <= t) { ++j; } } } return j == m; } }
2,604
Minimum Time to Eat All Grains
Hard
<p>There are <code>n</code> hens and <code>m</code> grains on a line. You are given the initial positions of the hens and the grains in two integer arrays <code>hens</code> and <code>grains</code> of size <code>n</code> and <code>m</code> respectively.</p> <p>Any hen can eat a grain if they are on the same position. The time taken for this is negligible. One hen can also eat multiple grains.</p> <p>In <code>1</code> second, a hen can move right or left by <code>1</code> unit. The hens can move simultaneously and independently of each other.</p> <p>Return <em>the <strong>minimum</strong> time to eat all grains if the hens act optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> hens = [3,6,7], grains = [2,4,7,9] <strong>Output:</strong> 2 <strong>Explanation:</strong> One of the ways hens eat all grains in 2 seconds is described below: - The first hen eats the grain at position 2 in 1 second. - The second hen eats the grain at position 4 in 2 seconds. - The third hen eats the grains at positions 7 and 9 in 2 seconds. So, the maximum time needed is 2. It can be proven that the hens cannot eat all grains before 2 seconds.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> hens = [4,6,109,111,213,215], grains = [5,110,214] <strong>Output:</strong> 1 <strong>Explanation:</strong> One of the ways hens eat all grains in 1 second is described below: - The first hen eats the grain at position 5 in 1 second. - The fourth hen eats the grain at position 110 in 1 second. - The sixth hen eats the grain at position 214 in 1 second. - The other hens do not move. So, the maximum time needed is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= hens.length, grains.length &lt;= 2*10<sup>4</sup></code></li> <li><code>0 &lt;= hens[i], grains[j] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
Python
class Solution: def minimumTime(self, hens: List[int], grains: List[int]) -> int: def check(t): j = 0 for x in hens: if j == m: return True y = grains[j] if y <= x: d = x - y if d > t: return False while j < m and grains[j] <= x: j += 1 while j < m and min(d, grains[j] - x) + grains[j] - y <= t: j += 1 else: while j < m and grains[j] - x <= t: j += 1 return j == m hens.sort() grains.sort() m = len(grains) r = abs(hens[0] - grains[0]) + grains[-1] - grains[0] + 1 return bisect_left(range(r), True, key=check)
2,604
Minimum Time to Eat All Grains
Hard
<p>There are <code>n</code> hens and <code>m</code> grains on a line. You are given the initial positions of the hens and the grains in two integer arrays <code>hens</code> and <code>grains</code> of size <code>n</code> and <code>m</code> respectively.</p> <p>Any hen can eat a grain if they are on the same position. The time taken for this is negligible. One hen can also eat multiple grains.</p> <p>In <code>1</code> second, a hen can move right or left by <code>1</code> unit. The hens can move simultaneously and independently of each other.</p> <p>Return <em>the <strong>minimum</strong> time to eat all grains if the hens act optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> hens = [3,6,7], grains = [2,4,7,9] <strong>Output:</strong> 2 <strong>Explanation:</strong> One of the ways hens eat all grains in 2 seconds is described below: - The first hen eats the grain at position 2 in 1 second. - The second hen eats the grain at position 4 in 2 seconds. - The third hen eats the grains at positions 7 and 9 in 2 seconds. So, the maximum time needed is 2. It can be proven that the hens cannot eat all grains before 2 seconds.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> hens = [4,6,109,111,213,215], grains = [5,110,214] <strong>Output:</strong> 1 <strong>Explanation:</strong> One of the ways hens eat all grains in 1 second is described below: - The first hen eats the grain at position 5 in 1 second. - The fourth hen eats the grain at position 110 in 1 second. - The sixth hen eats the grain at position 214 in 1 second. - The other hens do not move. So, the maximum time needed is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= hens.length, grains.length &lt;= 2*10<sup>4</sup></code></li> <li><code>0 &lt;= hens[i], grains[j] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Binary Search; Sorting
TypeScript
function minimumTime(hens: number[], grains: number[]): number { hens.sort((a, b) => a - b); grains.sort((a, b) => a - b); const m = grains.length; let l = 0; let r = Math.abs(hens[0] - grains[0]) + grains[m - 1] - grains[0] + 1; const check = (t: number): boolean => { let j = 0; for (const x of hens) { if (j === m) { return true; } const y = grains[j]; if (y <= x) { const d = x - y; if (d > t) { return false; } while (j < m && grains[j] <= x) { ++j; } while (j < m && Math.min(d, grains[j] - x) + grains[j] - y <= t) { ++j; } } else { while (j < m && grains[j] - x <= t) { ++j; } } } return j === m; }; while (l < r) { const mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; }
2,605
Form Smallest Number From Two Digit Arrays
Easy
Given two arrays of <strong>unique</strong> digits <code>nums1</code> and <code>nums2</code>, return <em>the <strong>smallest</strong> number that contains <strong>at least</strong> one digit from each array</em>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,1,3], nums2 = [5,7] <strong>Output:</strong> 15 <strong>Explanation:</strong> The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [3,5,2,6], nums2 = [3,1,7] <strong>Output:</strong> 3 <strong>Explanation:</strong> The number 3 contains the digit 3 which exists in both arrays. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 9</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 9</code></li> <li>All digits in each array are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Enumeration
C++
class Solution { public: int minNumber(vector<int>& nums1, vector<int>& nums2) { int ans = 100; for (int a : nums1) { for (int b : nums2) { if (a == b) { ans = min(ans, a); } else { ans = min({ans, a * 10 + b, b * 10 + a}); } } } return ans; } };
2,605
Form Smallest Number From Two Digit Arrays
Easy
Given two arrays of <strong>unique</strong> digits <code>nums1</code> and <code>nums2</code>, return <em>the <strong>smallest</strong> number that contains <strong>at least</strong> one digit from each array</em>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,1,3], nums2 = [5,7] <strong>Output:</strong> 15 <strong>Explanation:</strong> The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [3,5,2,6], nums2 = [3,1,7] <strong>Output:</strong> 3 <strong>Explanation:</strong> The number 3 contains the digit 3 which exists in both arrays. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 9</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 9</code></li> <li>All digits in each array are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Enumeration
Go
func minNumber(nums1 []int, nums2 []int) int { ans := 100 for _, a := range nums1 { for _, b := range nums2 { if a == b { ans = min(ans, a) } else { ans = min(ans, min(a*10+b, b*10+a)) } } } return ans }
2,605
Form Smallest Number From Two Digit Arrays
Easy
Given two arrays of <strong>unique</strong> digits <code>nums1</code> and <code>nums2</code>, return <em>the <strong>smallest</strong> number that contains <strong>at least</strong> one digit from each array</em>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,1,3], nums2 = [5,7] <strong>Output:</strong> 15 <strong>Explanation:</strong> The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [3,5,2,6], nums2 = [3,1,7] <strong>Output:</strong> 3 <strong>Explanation:</strong> The number 3 contains the digit 3 which exists in both arrays. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 9</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 9</code></li> <li>All digits in each array are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Enumeration
Java
class Solution { public int minNumber(int[] nums1, int[] nums2) { int ans = 100; for (int a : nums1) { for (int b : nums2) { if (a == b) { ans = Math.min(ans, a); } else { ans = Math.min(ans, Math.min(a * 10 + b, b * 10 + a)); } } } return ans; } }
2,605
Form Smallest Number From Two Digit Arrays
Easy
Given two arrays of <strong>unique</strong> digits <code>nums1</code> and <code>nums2</code>, return <em>the <strong>smallest</strong> number that contains <strong>at least</strong> one digit from each array</em>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,1,3], nums2 = [5,7] <strong>Output:</strong> 15 <strong>Explanation:</strong> The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [3,5,2,6], nums2 = [3,1,7] <strong>Output:</strong> 3 <strong>Explanation:</strong> The number 3 contains the digit 3 which exists in both arrays. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 9</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 9</code></li> <li>All digits in each array are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Enumeration
Python
class Solution: def minNumber(self, nums1: List[int], nums2: List[int]) -> int: ans = 100 for a in nums1: for b in nums2: if a == b: ans = min(ans, a) else: ans = min(ans, 10 * a + b, 10 * b + a) return ans
2,605
Form Smallest Number From Two Digit Arrays
Easy
Given two arrays of <strong>unique</strong> digits <code>nums1</code> and <code>nums2</code>, return <em>the <strong>smallest</strong> number that contains <strong>at least</strong> one digit from each array</em>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,1,3], nums2 = [5,7] <strong>Output:</strong> 15 <strong>Explanation:</strong> The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [3,5,2,6], nums2 = [3,1,7] <strong>Output:</strong> 3 <strong>Explanation:</strong> The number 3 contains the digit 3 which exists in both arrays. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 9</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 9</code></li> <li>All digits in each array are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Enumeration
Rust
impl Solution { pub fn min_number(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 { let mut ans = 100; for &a in &nums1 { for &b in &nums2 { if a == b { ans = std::cmp::min(ans, a); } else { ans = std::cmp::min(ans, std::cmp::min(a * 10 + b, b * 10 + a)); } } } ans } }
2,605
Form Smallest Number From Two Digit Arrays
Easy
Given two arrays of <strong>unique</strong> digits <code>nums1</code> and <code>nums2</code>, return <em>the <strong>smallest</strong> number that contains <strong>at least</strong> one digit from each array</em>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,1,3], nums2 = [5,7] <strong>Output:</strong> 15 <strong>Explanation:</strong> The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [3,5,2,6], nums2 = [3,1,7] <strong>Output:</strong> 3 <strong>Explanation:</strong> The number 3 contains the digit 3 which exists in both arrays. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 9</code></li> <li><code>1 &lt;= nums1[i], nums2[i] &lt;= 9</code></li> <li>All digits in each array are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Enumeration
TypeScript
function minNumber(nums1: number[], nums2: number[]): number { let ans = 100; for (const a of nums1) { for (const b of nums2) { if (a === b) { ans = Math.min(ans, a); } else { ans = Math.min(ans, a * 10 + b, b * 10 + a); } } } return ans; }
2,606
Find the Substring With Maximum Cost
Medium
<p>You are given a string <code>s</code>, a string <code>chars</code> of <strong>distinct</strong> characters and an integer array <code>vals</code> of the same length as <code>chars</code>.</p> <p>The <strong>cost of the substring </strong>is the sum of the values of each character in the substring. The cost of an empty string is considered <code>0</code>.</p> <p>The <strong>value of the character </strong>is defined in the following way:</p> <ul> <li>If the character is not in the string <code>chars</code>, then its value is its corresponding position <strong>(1-indexed)</strong> in the alphabet. <ul> <li>For example, the value of <code>&#39;a&#39;</code> is <code>1</code>, the value of <code>&#39;b&#39;</code> is <code>2</code>, and so on. The value of <code>&#39;z&#39;</code> is <code>26</code>.</li> </ul> </li> <li>Otherwise, assuming <code>i</code> is the index where the character occurs in the string <code>chars</code>, then its value is <code>vals[i]</code>.</li> </ul> <p>Return <em>the maximum cost among all substrings of the string</em> <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;adaa&quot;, chars = &quot;d&quot;, vals = [-1000] <strong>Output:</strong> 2 <strong>Explanation:</strong> The value of the characters &quot;a&quot; and &quot;d&quot; is 1 and -1000 respectively. The substring with the maximum cost is &quot;aa&quot; and its cost is 1 + 1 = 2. It can be proven that 2 is the maximum cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abc&quot;, chars = &quot;abc&quot;, vals = [-1,-1,-1] <strong>Output:</strong> 0 <strong>Explanation:</strong> The value of the characters &quot;a&quot;, &quot;b&quot; and &quot;c&quot; is -1, -1, and -1 respectively. The substring with the maximum cost is the empty substring &quot;&quot; and its cost is 0. It can be proven that 0 is the maximum cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consist of lowercase English letters.</li> <li><code>1 &lt;= chars.length &lt;= 26</code></li> <li><code>chars</code> consist of <strong>distinct</strong> lowercase English letters.</li> <li><code>vals.length == chars.length</code></li> <li><code>-1000 &lt;= vals[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; String; Dynamic Programming
C++
class Solution { public: int maximumCostSubstring(string s, string chars, vector<int>& vals) { vector<int> d(26); iota(d.begin(), d.end(), 1); int m = chars.size(); for (int i = 0; i < m; ++i) { d[chars[i] - 'a'] = vals[i]; } int ans = 0, tot = 0, mi = 0; for (char& c : s) { int v = d[c - 'a']; tot += v; ans = max(ans, tot - mi); mi = min(mi, tot); } return ans; } };
2,606
Find the Substring With Maximum Cost
Medium
<p>You are given a string <code>s</code>, a string <code>chars</code> of <strong>distinct</strong> characters and an integer array <code>vals</code> of the same length as <code>chars</code>.</p> <p>The <strong>cost of the substring </strong>is the sum of the values of each character in the substring. The cost of an empty string is considered <code>0</code>.</p> <p>The <strong>value of the character </strong>is defined in the following way:</p> <ul> <li>If the character is not in the string <code>chars</code>, then its value is its corresponding position <strong>(1-indexed)</strong> in the alphabet. <ul> <li>For example, the value of <code>&#39;a&#39;</code> is <code>1</code>, the value of <code>&#39;b&#39;</code> is <code>2</code>, and so on. The value of <code>&#39;z&#39;</code> is <code>26</code>.</li> </ul> </li> <li>Otherwise, assuming <code>i</code> is the index where the character occurs in the string <code>chars</code>, then its value is <code>vals[i]</code>.</li> </ul> <p>Return <em>the maximum cost among all substrings of the string</em> <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;adaa&quot;, chars = &quot;d&quot;, vals = [-1000] <strong>Output:</strong> 2 <strong>Explanation:</strong> The value of the characters &quot;a&quot; and &quot;d&quot; is 1 and -1000 respectively. The substring with the maximum cost is &quot;aa&quot; and its cost is 1 + 1 = 2. It can be proven that 2 is the maximum cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abc&quot;, chars = &quot;abc&quot;, vals = [-1,-1,-1] <strong>Output:</strong> 0 <strong>Explanation:</strong> The value of the characters &quot;a&quot;, &quot;b&quot; and &quot;c&quot; is -1, -1, and -1 respectively. The substring with the maximum cost is the empty substring &quot;&quot; and its cost is 0. It can be proven that 0 is the maximum cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consist of lowercase English letters.</li> <li><code>1 &lt;= chars.length &lt;= 26</code></li> <li><code>chars</code> consist of <strong>distinct</strong> lowercase English letters.</li> <li><code>vals.length == chars.length</code></li> <li><code>-1000 &lt;= vals[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; String; Dynamic Programming
Go
func maximumCostSubstring(s string, chars string, vals []int) (ans int) { d := [26]int{} for i := range d { d[i] = i + 1 } for i, c := range chars { d[c-'a'] = vals[i] } tot, mi := 0, 0 for _, c := range s { v := d[c-'a'] tot += v ans = max(ans, tot-mi) mi = min(mi, tot) } return }
2,606
Find the Substring With Maximum Cost
Medium
<p>You are given a string <code>s</code>, a string <code>chars</code> of <strong>distinct</strong> characters and an integer array <code>vals</code> of the same length as <code>chars</code>.</p> <p>The <strong>cost of the substring </strong>is the sum of the values of each character in the substring. The cost of an empty string is considered <code>0</code>.</p> <p>The <strong>value of the character </strong>is defined in the following way:</p> <ul> <li>If the character is not in the string <code>chars</code>, then its value is its corresponding position <strong>(1-indexed)</strong> in the alphabet. <ul> <li>For example, the value of <code>&#39;a&#39;</code> is <code>1</code>, the value of <code>&#39;b&#39;</code> is <code>2</code>, and so on. The value of <code>&#39;z&#39;</code> is <code>26</code>.</li> </ul> </li> <li>Otherwise, assuming <code>i</code> is the index where the character occurs in the string <code>chars</code>, then its value is <code>vals[i]</code>.</li> </ul> <p>Return <em>the maximum cost among all substrings of the string</em> <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;adaa&quot;, chars = &quot;d&quot;, vals = [-1000] <strong>Output:</strong> 2 <strong>Explanation:</strong> The value of the characters &quot;a&quot; and &quot;d&quot; is 1 and -1000 respectively. The substring with the maximum cost is &quot;aa&quot; and its cost is 1 + 1 = 2. It can be proven that 2 is the maximum cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abc&quot;, chars = &quot;abc&quot;, vals = [-1,-1,-1] <strong>Output:</strong> 0 <strong>Explanation:</strong> The value of the characters &quot;a&quot;, &quot;b&quot; and &quot;c&quot; is -1, -1, and -1 respectively. The substring with the maximum cost is the empty substring &quot;&quot; and its cost is 0. It can be proven that 0 is the maximum cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consist of lowercase English letters.</li> <li><code>1 &lt;= chars.length &lt;= 26</code></li> <li><code>chars</code> consist of <strong>distinct</strong> lowercase English letters.</li> <li><code>vals.length == chars.length</code></li> <li><code>-1000 &lt;= vals[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; String; Dynamic Programming
Java
class Solution { public int maximumCostSubstring(String s, String chars, int[] vals) { int[] d = new int[26]; for (int i = 0; i < d.length; ++i) { d[i] = i + 1; } int m = chars.length(); for (int i = 0; i < m; ++i) { d[chars.charAt(i) - 'a'] = vals[i]; } int ans = 0, tot = 0, mi = 0; int n = s.length(); for (int i = 0; i < n; ++i) { int v = d[s.charAt(i) - 'a']; tot += v; ans = Math.max(ans, tot - mi); mi = Math.min(mi, tot); } return ans; } }
2,606
Find the Substring With Maximum Cost
Medium
<p>You are given a string <code>s</code>, a string <code>chars</code> of <strong>distinct</strong> characters and an integer array <code>vals</code> of the same length as <code>chars</code>.</p> <p>The <strong>cost of the substring </strong>is the sum of the values of each character in the substring. The cost of an empty string is considered <code>0</code>.</p> <p>The <strong>value of the character </strong>is defined in the following way:</p> <ul> <li>If the character is not in the string <code>chars</code>, then its value is its corresponding position <strong>(1-indexed)</strong> in the alphabet. <ul> <li>For example, the value of <code>&#39;a&#39;</code> is <code>1</code>, the value of <code>&#39;b&#39;</code> is <code>2</code>, and so on. The value of <code>&#39;z&#39;</code> is <code>26</code>.</li> </ul> </li> <li>Otherwise, assuming <code>i</code> is the index where the character occurs in the string <code>chars</code>, then its value is <code>vals[i]</code>.</li> </ul> <p>Return <em>the maximum cost among all substrings of the string</em> <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;adaa&quot;, chars = &quot;d&quot;, vals = [-1000] <strong>Output:</strong> 2 <strong>Explanation:</strong> The value of the characters &quot;a&quot; and &quot;d&quot; is 1 and -1000 respectively. The substring with the maximum cost is &quot;aa&quot; and its cost is 1 + 1 = 2. It can be proven that 2 is the maximum cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abc&quot;, chars = &quot;abc&quot;, vals = [-1,-1,-1] <strong>Output:</strong> 0 <strong>Explanation:</strong> The value of the characters &quot;a&quot;, &quot;b&quot; and &quot;c&quot; is -1, -1, and -1 respectively. The substring with the maximum cost is the empty substring &quot;&quot; and its cost is 0. It can be proven that 0 is the maximum cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consist of lowercase English letters.</li> <li><code>1 &lt;= chars.length &lt;= 26</code></li> <li><code>chars</code> consist of <strong>distinct</strong> lowercase English letters.</li> <li><code>vals.length == chars.length</code></li> <li><code>-1000 &lt;= vals[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; String; Dynamic Programming
Python
class Solution: def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int: d = {c: v for c, v in zip(chars, vals)} ans = tot = mi = 0 for c in s: v = d.get(c, ord(c) - ord('a') + 1) tot += v ans = max(ans, tot - mi) mi = min(mi, tot) return ans
2,606
Find the Substring With Maximum Cost
Medium
<p>You are given a string <code>s</code>, a string <code>chars</code> of <strong>distinct</strong> characters and an integer array <code>vals</code> of the same length as <code>chars</code>.</p> <p>The <strong>cost of the substring </strong>is the sum of the values of each character in the substring. The cost of an empty string is considered <code>0</code>.</p> <p>The <strong>value of the character </strong>is defined in the following way:</p> <ul> <li>If the character is not in the string <code>chars</code>, then its value is its corresponding position <strong>(1-indexed)</strong> in the alphabet. <ul> <li>For example, the value of <code>&#39;a&#39;</code> is <code>1</code>, the value of <code>&#39;b&#39;</code> is <code>2</code>, and so on. The value of <code>&#39;z&#39;</code> is <code>26</code>.</li> </ul> </li> <li>Otherwise, assuming <code>i</code> is the index where the character occurs in the string <code>chars</code>, then its value is <code>vals[i]</code>.</li> </ul> <p>Return <em>the maximum cost among all substrings of the string</em> <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;adaa&quot;, chars = &quot;d&quot;, vals = [-1000] <strong>Output:</strong> 2 <strong>Explanation:</strong> The value of the characters &quot;a&quot; and &quot;d&quot; is 1 and -1000 respectively. The substring with the maximum cost is &quot;aa&quot; and its cost is 1 + 1 = 2. It can be proven that 2 is the maximum cost. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abc&quot;, chars = &quot;abc&quot;, vals = [-1,-1,-1] <strong>Output:</strong> 0 <strong>Explanation:</strong> The value of the characters &quot;a&quot;, &quot;b&quot; and &quot;c&quot; is -1, -1, and -1 respectively. The substring with the maximum cost is the empty substring &quot;&quot; and its cost is 0. It can be proven that 0 is the maximum cost. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consist of lowercase English letters.</li> <li><code>1 &lt;= chars.length &lt;= 26</code></li> <li><code>chars</code> consist of <strong>distinct</strong> lowercase English letters.</li> <li><code>vals.length == chars.length</code></li> <li><code>-1000 &lt;= vals[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; String; Dynamic Programming
TypeScript
function maximumCostSubstring(s: string, chars: string, vals: number[]): number { const d: number[] = Array.from({ length: 26 }, (_, i) => i + 1); for (let i = 0; i < chars.length; ++i) { d[chars.charCodeAt(i) - 97] = vals[i]; } let ans = 0; let tot = 0; let mi = 0; for (const c of s) { tot += d[c.charCodeAt(0) - 97]; ans = Math.max(ans, tot - mi); mi = Math.min(mi, tot); } return ans; }
2,607
Make K-Subarray Sums Equal
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>arr</code> and an integer <code>k</code>. The array <code>arr</code> is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.</p> <p>You can do the following operation any number of times:</p> <ul> <li>Pick any element from <code>arr</code> and increase or decrease it by <code>1</code>.</li> </ul> <p>Return <em>the minimum number of operations such that the sum of each <strong>subarray</strong> of length </em><code>k</code><em> is equal</em>.</p> <p>A <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [1,4,1,3], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> we can do one operation on index 1 to make its value equal to 3. The array after the operation is [1,3,1,3] - Subarray starts at index 0 is [1, 3], and its sum is 4 - Subarray starts at index 1 is [3, 1], and its sum is 4 - Subarray starts at index 2 is [1, 3], and its sum is 4 - Subarray starts at index 3 is [3, 1], and its sum is 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [2,5,5,7], k = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> we can do three operations on index 0 to make its value equal to 5 and two operations on index 3 to make its value equal to 5. The array after the operations is [5,5,5,5] - Subarray starts at index 0 is [5, 5, 5], and its sum is 15 - Subarray starts at index 1 is [5, 5, 5], and its sum is 15 - Subarray starts at index 2 is [5, 5, 5], and its sum is 15 - Subarray starts at index 3 is [5, 5, 5], and its sum is 15 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= arr.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arr[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Number Theory; Sorting
C++
class Solution { public: long long makeSubKSumEqual(vector<int>& arr, int k) { int n = arr.size(); int g = gcd(n, k); long long ans = 0; for (int i = 0; i < g; ++i) { vector<int> t; for (int j = i; j < n; j += g) { t.push_back(arr[j]); } sort(t.begin(), t.end()); int mid = t[t.size() / 2]; for (int x : t) { ans += abs(x - mid); } } return ans; } };
2,607
Make K-Subarray Sums Equal
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>arr</code> and an integer <code>k</code>. The array <code>arr</code> is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.</p> <p>You can do the following operation any number of times:</p> <ul> <li>Pick any element from <code>arr</code> and increase or decrease it by <code>1</code>.</li> </ul> <p>Return <em>the minimum number of operations such that the sum of each <strong>subarray</strong> of length </em><code>k</code><em> is equal</em>.</p> <p>A <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [1,4,1,3], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> we can do one operation on index 1 to make its value equal to 3. The array after the operation is [1,3,1,3] - Subarray starts at index 0 is [1, 3], and its sum is 4 - Subarray starts at index 1 is [3, 1], and its sum is 4 - Subarray starts at index 2 is [1, 3], and its sum is 4 - Subarray starts at index 3 is [3, 1], and its sum is 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [2,5,5,7], k = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> we can do three operations on index 0 to make its value equal to 5 and two operations on index 3 to make its value equal to 5. The array after the operations is [5,5,5,5] - Subarray starts at index 0 is [5, 5, 5], and its sum is 15 - Subarray starts at index 1 is [5, 5, 5], and its sum is 15 - Subarray starts at index 2 is [5, 5, 5], and its sum is 15 - Subarray starts at index 3 is [5, 5, 5], and its sum is 15 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= arr.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arr[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Number Theory; Sorting
Go
func makeSubKSumEqual(arr []int, k int) (ans int64) { n := len(arr) g := gcd(n, k) for i := 0; i < g; i++ { t := []int{} for j := i; j < n; j += g { t = append(t, arr[j]) } sort.Ints(t) mid := t[len(t)/2] for _, x := range t { ans += int64(abs(x - mid)) } } return } func abs(x int) int { if x < 0 { return -x } return x } func gcd(a, b int) int { if b == 0 { return a } return gcd(b, a%b) }
2,607
Make K-Subarray Sums Equal
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>arr</code> and an integer <code>k</code>. The array <code>arr</code> is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.</p> <p>You can do the following operation any number of times:</p> <ul> <li>Pick any element from <code>arr</code> and increase or decrease it by <code>1</code>.</li> </ul> <p>Return <em>the minimum number of operations such that the sum of each <strong>subarray</strong> of length </em><code>k</code><em> is equal</em>.</p> <p>A <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [1,4,1,3], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> we can do one operation on index 1 to make its value equal to 3. The array after the operation is [1,3,1,3] - Subarray starts at index 0 is [1, 3], and its sum is 4 - Subarray starts at index 1 is [3, 1], and its sum is 4 - Subarray starts at index 2 is [1, 3], and its sum is 4 - Subarray starts at index 3 is [3, 1], and its sum is 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [2,5,5,7], k = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> we can do three operations on index 0 to make its value equal to 5 and two operations on index 3 to make its value equal to 5. The array after the operations is [5,5,5,5] - Subarray starts at index 0 is [5, 5, 5], and its sum is 15 - Subarray starts at index 1 is [5, 5, 5], and its sum is 15 - Subarray starts at index 2 is [5, 5, 5], and its sum is 15 - Subarray starts at index 3 is [5, 5, 5], and its sum is 15 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= arr.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arr[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Number Theory; Sorting
Java
class Solution { public long makeSubKSumEqual(int[] arr, int k) { int n = arr.length; int g = gcd(n, k); long ans = 0; for (int i = 0; i < g; ++i) { List<Integer> t = new ArrayList<>(); for (int j = i; j < n; j += g) { t.add(arr[j]); } t.sort((a, b) -> a - b); int mid = t.get(t.size() >> 1); for (int x : t) { ans += Math.abs(x - mid); } } return ans; } private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } }
2,607
Make K-Subarray Sums Equal
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>arr</code> and an integer <code>k</code>. The array <code>arr</code> is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.</p> <p>You can do the following operation any number of times:</p> <ul> <li>Pick any element from <code>arr</code> and increase or decrease it by <code>1</code>.</li> </ul> <p>Return <em>the minimum number of operations such that the sum of each <strong>subarray</strong> of length </em><code>k</code><em> is equal</em>.</p> <p>A <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [1,4,1,3], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> we can do one operation on index 1 to make its value equal to 3. The array after the operation is [1,3,1,3] - Subarray starts at index 0 is [1, 3], and its sum is 4 - Subarray starts at index 1 is [3, 1], and its sum is 4 - Subarray starts at index 2 is [1, 3], and its sum is 4 - Subarray starts at index 3 is [3, 1], and its sum is 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [2,5,5,7], k = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> we can do three operations on index 0 to make its value equal to 5 and two operations on index 3 to make its value equal to 5. The array after the operations is [5,5,5,5] - Subarray starts at index 0 is [5, 5, 5], and its sum is 15 - Subarray starts at index 1 is [5, 5, 5], and its sum is 15 - Subarray starts at index 2 is [5, 5, 5], and its sum is 15 - Subarray starts at index 3 is [5, 5, 5], and its sum is 15 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= arr.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arr[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Number Theory; Sorting
Python
class Solution: def makeSubKSumEqual(self, arr: List[int], k: int) -> int: n = len(arr) g = gcd(n, k) ans = 0 for i in range(g): t = sorted(arr[i:n:g]) mid = t[len(t) >> 1] ans += sum(abs(x - mid) for x in t) return ans
2,607
Make K-Subarray Sums Equal
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>arr</code> and an integer <code>k</code>. The array <code>arr</code> is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.</p> <p>You can do the following operation any number of times:</p> <ul> <li>Pick any element from <code>arr</code> and increase or decrease it by <code>1</code>.</li> </ul> <p>Return <em>the minimum number of operations such that the sum of each <strong>subarray</strong> of length </em><code>k</code><em> is equal</em>.</p> <p>A <strong>subarray</strong> is a contiguous part of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [1,4,1,3], k = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> we can do one operation on index 1 to make its value equal to 3. The array after the operation is [1,3,1,3] - Subarray starts at index 0 is [1, 3], and its sum is 4 - Subarray starts at index 1 is [3, 1], and its sum is 4 - Subarray starts at index 2 is [1, 3], and its sum is 4 - Subarray starts at index 3 is [3, 1], and its sum is 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [2,5,5,7], k = 3 <strong>Output:</strong> 5 <strong>Explanation:</strong> we can do three operations on index 0 to make its value equal to 5 and two operations on index 3 to make its value equal to 5. The array after the operations is [5,5,5,5] - Subarray starts at index 0 is [5, 5, 5], and its sum is 15 - Subarray starts at index 1 is [5, 5, 5], and its sum is 15 - Subarray starts at index 2 is [5, 5, 5], and its sum is 15 - Subarray starts at index 3 is [5, 5, 5], and its sum is 15 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= arr.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arr[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Number Theory; Sorting
TypeScript
function makeSubKSumEqual(arr: number[], k: number): number { const n = arr.length; const g = gcd(n, k); let ans = 0; for (let i = 0; i < g; ++i) { const t: number[] = []; for (let j = i; j < n; j += g) { t.push(arr[j]); } t.sort((a, b) => a - b); const mid = t[t.length >> 1]; for (const x of t) { ans += Math.abs(x - mid); } } return ans; } function gcd(a: number, b: number): number { if (b === 0) { return a; } return gcd(b, a % b); }
2,608
Shortest Cycle in a Graph
Hard
<p>There is a <strong>bi-directional </strong>graph with <code>n</code> vertices, where each vertex is labeled from <code>0</code> to <code>n - 1</code>. The edges in the graph are represented by a given 2D integer array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> denotes an edge between vertex <code>u<sub>i</sub></code> and vertex <code>v<sub>i</sub></code>. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.</p> <p>Return <em>the length of the <strong>shortest </strong>cycle in the graph</em>. If no cycle exists, return <code>-1</code>.</p> <p>A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/images/cropped.png" style="width: 387px; height: 331px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The cycle with the smallest length is : 0 -&gt; 1 -&gt; 2 -&gt; 0 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/images/croppedagin.png" style="width: 307px; height: 307px;" /> <pre> <strong>Input:</strong> n = 4, edges = [[0,1],[0,2]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There are no cycles in this graph. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= edges.length &lt;= 1000</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li>There are no repeated edges.</li> </ul>
Breadth-First Search; Graph
C++
class Solution { public: int findShortestCycle(int n, vector<vector<int>>& edges) { vector<vector<int>> g(n); for (auto& e : edges) { int u = e[0], v = e[1]; g[u].push_back(v); g[v].push_back(u); } const int inf = 1 << 30; auto bfs = [&](int u, int v) -> int { int dist[n]; fill(dist, dist + n, inf); dist[u] = 0; queue<int> q{{u}}; while (!q.empty()) { int i = q.front(); q.pop(); for (int j : g[i]) { if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { continue; } dist[j] = dist[i] + 1; q.push(j); } } return dist[v] + 1; }; int ans = inf; for (auto& e : edges) { int u = e[0], v = e[1]; ans = min(ans, bfs(u, v)); } return ans < inf ? ans : -1; } };
2,608
Shortest Cycle in a Graph
Hard
<p>There is a <strong>bi-directional </strong>graph with <code>n</code> vertices, where each vertex is labeled from <code>0</code> to <code>n - 1</code>. The edges in the graph are represented by a given 2D integer array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> denotes an edge between vertex <code>u<sub>i</sub></code> and vertex <code>v<sub>i</sub></code>. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.</p> <p>Return <em>the length of the <strong>shortest </strong>cycle in the graph</em>. If no cycle exists, return <code>-1</code>.</p> <p>A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/images/cropped.png" style="width: 387px; height: 331px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The cycle with the smallest length is : 0 -&gt; 1 -&gt; 2 -&gt; 0 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/images/croppedagin.png" style="width: 307px; height: 307px;" /> <pre> <strong>Input:</strong> n = 4, edges = [[0,1],[0,2]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There are no cycles in this graph. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= edges.length &lt;= 1000</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li>There are no repeated edges.</li> </ul>
Breadth-First Search; Graph
Go
func findShortestCycle(n int, edges [][]int) int { g := make([][]int, n) for _, e := range edges { u, v := e[0], e[1] g[u] = append(g[u], v) g[v] = append(g[v], u) } const inf = 1 << 30 bfs := func(u, v int) int { dist := make([]int, n) for i := range dist { dist[i] = inf } dist[u] = 0 q := []int{u} for len(q) > 0 { i := q[0] q = q[1:] for _, j := range g[i] { if (i == u && j == v) || (i == v && j == u) || dist[j] != inf { continue } dist[j] = dist[i] + 1 q = append(q, j) } } return dist[v] + 1 } ans := inf for _, e := range edges { u, v := e[0], e[1] ans = min(ans, bfs(u, v)) } if ans < inf { return ans } return -1 }
2,608
Shortest Cycle in a Graph
Hard
<p>There is a <strong>bi-directional </strong>graph with <code>n</code> vertices, where each vertex is labeled from <code>0</code> to <code>n - 1</code>. The edges in the graph are represented by a given 2D integer array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> denotes an edge between vertex <code>u<sub>i</sub></code> and vertex <code>v<sub>i</sub></code>. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.</p> <p>Return <em>the length of the <strong>shortest </strong>cycle in the graph</em>. If no cycle exists, return <code>-1</code>.</p> <p>A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/images/cropped.png" style="width: 387px; height: 331px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The cycle with the smallest length is : 0 -&gt; 1 -&gt; 2 -&gt; 0 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/images/croppedagin.png" style="width: 307px; height: 307px;" /> <pre> <strong>Input:</strong> n = 4, edges = [[0,1],[0,2]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There are no cycles in this graph. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= edges.length &lt;= 1000</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li>There are no repeated edges.</li> </ul>
Breadth-First Search; Graph
Java
class Solution { private List<Integer>[] g; private final int inf = 1 << 30; public int findShortestCycle(int n, int[][] edges) { g = new List[n]; Arrays.setAll(g, k -> new ArrayList<>()); for (var e : edges) { int u = e[0], v = e[1]; g[u].add(v); g[v].add(u); } int ans = inf; for (var e : edges) { int u = e[0], v = e[1]; ans = Math.min(ans, bfs(u, v)); } return ans < inf ? ans : -1; } private int bfs(int u, int v) { int[] dist = new int[g.length]; Arrays.fill(dist, inf); dist[u] = 0; Deque<Integer> q = new ArrayDeque<>(); q.offer(u); while (!q.isEmpty()) { int i = q.poll(); for (int j : g[i]) { if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { continue; } dist[j] = dist[i] + 1; q.offer(j); } } return dist[v] + 1; } }
2,608
Shortest Cycle in a Graph
Hard
<p>There is a <strong>bi-directional </strong>graph with <code>n</code> vertices, where each vertex is labeled from <code>0</code> to <code>n - 1</code>. The edges in the graph are represented by a given 2D integer array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> denotes an edge between vertex <code>u<sub>i</sub></code> and vertex <code>v<sub>i</sub></code>. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.</p> <p>Return <em>the length of the <strong>shortest </strong>cycle in the graph</em>. If no cycle exists, return <code>-1</code>.</p> <p>A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/images/cropped.png" style="width: 387px; height: 331px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The cycle with the smallest length is : 0 -&gt; 1 -&gt; 2 -&gt; 0 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/images/croppedagin.png" style="width: 307px; height: 307px;" /> <pre> <strong>Input:</strong> n = 4, edges = [[0,1],[0,2]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There are no cycles in this graph. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= edges.length &lt;= 1000</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li>There are no repeated edges.</li> </ul>
Breadth-First Search; Graph
Python
class Solution: def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: def bfs(u: int, v: int) -> int: dist = [inf] * n dist[u] = 0 q = deque([u]) while q: i = q.popleft() for j in g[i]: if (i, j) != (u, v) and (j, i) != (u, v) and dist[j] == inf: dist[j] = dist[i] + 1 q.append(j) return dist[v] + 1 g = defaultdict(set) for u, v in edges: g[u].add(v) g[v].add(u) ans = min(bfs(u, v) for u, v in edges) return ans if ans < inf else -1
2,608
Shortest Cycle in a Graph
Hard
<p>There is a <strong>bi-directional </strong>graph with <code>n</code> vertices, where each vertex is labeled from <code>0</code> to <code>n - 1</code>. The edges in the graph are represented by a given 2D integer array <code>edges</code>, where <code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code> denotes an edge between vertex <code>u<sub>i</sub></code> and vertex <code>v<sub>i</sub></code>. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.</p> <p>Return <em>the length of the <strong>shortest </strong>cycle in the graph</em>. If no cycle exists, return <code>-1</code>.</p> <p>A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/images/cropped.png" style="width: 387px; height: 331px;" /> <pre> <strong>Input:</strong> n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The cycle with the smallest length is : 0 -&gt; 1 -&gt; 2 -&gt; 0 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2608.Shortest%20Cycle%20in%20a%20Graph/images/croppedagin.png" style="width: 307px; height: 307px;" /> <pre> <strong>Input:</strong> n = 4, edges = [[0,1],[0,2]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There are no cycles in this graph. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= edges.length &lt;= 1000</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt; n</code></li> <li><code>u<sub>i</sub> != v<sub>i</sub></code></li> <li>There are no repeated edges.</li> </ul>
Breadth-First Search; Graph
TypeScript
function findShortestCycle(n: number, edges: number[][]): number { const g: number[][] = new Array(n).fill(0).map(() => []); for (const [u, v] of edges) { g[u].push(v); g[v].push(u); } const inf = 1 << 30; let ans = inf; const bfs = (u: number, v: number) => { const dist: number[] = new Array(n).fill(inf); dist[u] = 0; const q: number[] = [u]; while (q.length) { const i = q.shift()!; for (const j of g[i]) { if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { continue; } dist[j] = dist[i] + 1; q.push(j); } } return 1 + dist[v]; }; for (const [u, v] of edges) { ans = Math.min(ans, bfs(u, v)); } return ans < inf ? ans : -1; }
2,609
Find the Longest Balanced Substring of a Binary String
Easy
<p>You are given a binary string <code>s</code> consisting only of zeroes and ones.</p> <p>A substring of <code>s</code> is considered balanced if<strong> all zeroes are before ones</strong> and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring.</p> <p>Return <em>the length of the longest balanced substring of </em><code>s</code>.</p> <p>A <b>substring</b> is a contiguous sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;01000111&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The longest balanced substring is &quot;000111&quot;, which has length 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;00111&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest balanced substring is &quot;0011&quot;, which has length 4.&nbsp; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;111&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no balanced substring except the empty substring, so the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>&#39;0&#39; &lt;= s[i] &lt;= &#39;1&#39;</code></li> </ul>
String
C++
class Solution { public: int findTheLongestBalancedSubstring(string s) { int n = s.size(); int ans = 0; auto check = [&](int i, int j) -> bool { int cnt = 0; for (int k = i; k <= j; ++k) { if (s[k] == '1') { ++cnt; } else if (cnt) { return false; } } return cnt * 2 == j - i + 1; }; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (check(i, j)) { ans = max(ans, j - i + 1); } } } return ans; } };
2,609
Find the Longest Balanced Substring of a Binary String
Easy
<p>You are given a binary string <code>s</code> consisting only of zeroes and ones.</p> <p>A substring of <code>s</code> is considered balanced if<strong> all zeroes are before ones</strong> and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring.</p> <p>Return <em>the length of the longest balanced substring of </em><code>s</code>.</p> <p>A <b>substring</b> is a contiguous sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;01000111&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The longest balanced substring is &quot;000111&quot;, which has length 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;00111&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest balanced substring is &quot;0011&quot;, which has length 4.&nbsp; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;111&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no balanced substring except the empty substring, so the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>&#39;0&#39; &lt;= s[i] &lt;= &#39;1&#39;</code></li> </ul>
String
Go
func findTheLongestBalancedSubstring(s string) (ans int) { n := len(s) check := func(i, j int) bool { cnt := 0 for k := i; k <= j; k++ { if s[k] == '1' { cnt++ } else if cnt > 0 { return false } } return cnt*2 == j-i+1 } for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { if check(i, j) { ans = max(ans, j-i+1) } } } return }
2,609
Find the Longest Balanced Substring of a Binary String
Easy
<p>You are given a binary string <code>s</code> consisting only of zeroes and ones.</p> <p>A substring of <code>s</code> is considered balanced if<strong> all zeroes are before ones</strong> and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring.</p> <p>Return <em>the length of the longest balanced substring of </em><code>s</code>.</p> <p>A <b>substring</b> is a contiguous sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;01000111&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The longest balanced substring is &quot;000111&quot;, which has length 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;00111&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest balanced substring is &quot;0011&quot;, which has length 4.&nbsp; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;111&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no balanced substring except the empty substring, so the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>&#39;0&#39; &lt;= s[i] &lt;= &#39;1&#39;</code></li> </ul>
String
Java
class Solution { public int findTheLongestBalancedSubstring(String s) { int n = s.length(); int ans = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (check(s, i, j)) { ans = Math.max(ans, j - i + 1); } } } return ans; } private boolean check(String s, int i, int j) { int cnt = 0; for (int k = i; k <= j; ++k) { if (s.charAt(k) == '1') { ++cnt; } else if (cnt > 0) { return false; } } return cnt * 2 == j - i + 1; } }
2,609
Find the Longest Balanced Substring of a Binary String
Easy
<p>You are given a binary string <code>s</code> consisting only of zeroes and ones.</p> <p>A substring of <code>s</code> is considered balanced if<strong> all zeroes are before ones</strong> and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring.</p> <p>Return <em>the length of the longest balanced substring of </em><code>s</code>.</p> <p>A <b>substring</b> is a contiguous sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;01000111&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The longest balanced substring is &quot;000111&quot;, which has length 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;00111&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest balanced substring is &quot;0011&quot;, which has length 4.&nbsp; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;111&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no balanced substring except the empty substring, so the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>&#39;0&#39; &lt;= s[i] &lt;= &#39;1&#39;</code></li> </ul>
String
Python
class Solution: def findTheLongestBalancedSubstring(self, s: str) -> int: def check(i, j): cnt = 0 for k in range(i, j + 1): if s[k] == '1': cnt += 1 elif cnt: return False return cnt * 2 == (j - i + 1) n = len(s) ans = 0 for i in range(n): for j in range(i + 1, n): if check(i, j): ans = max(ans, j - i + 1) return ans
2,609
Find the Longest Balanced Substring of a Binary String
Easy
<p>You are given a binary string <code>s</code> consisting only of zeroes and ones.</p> <p>A substring of <code>s</code> is considered balanced if<strong> all zeroes are before ones</strong> and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring.</p> <p>Return <em>the length of the longest balanced substring of </em><code>s</code>.</p> <p>A <b>substring</b> is a contiguous sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;01000111&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The longest balanced substring is &quot;000111&quot;, which has length 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;00111&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest balanced substring is &quot;0011&quot;, which has length 4.&nbsp; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;111&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no balanced substring except the empty substring, so the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>&#39;0&#39; &lt;= s[i] &lt;= &#39;1&#39;</code></li> </ul>
String
Rust
impl Solution { pub fn find_the_longest_balanced_substring(s: String) -> i32 { let check = |i: usize, j: usize| -> bool { let mut cnt = 0; for k in i..=j { if s.as_bytes()[k] == b'1' { cnt += 1; } else if cnt > 0 { return false; } } cnt * 2 == j - i + 1 }; let mut ans = 0; let n = s.len(); for i in 0..n - 1 { for j in (i + 1..n).rev() { if j - i + 1 < ans { break; } if check(i, j) { ans = std::cmp::max(ans, j - i + 1); break; } } } ans as i32 } }
2,609
Find the Longest Balanced Substring of a Binary String
Easy
<p>You are given a binary string <code>s</code> consisting only of zeroes and ones.</p> <p>A substring of <code>s</code> is considered balanced if<strong> all zeroes are before ones</strong> and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring.</p> <p>Return <em>the length of the longest balanced substring of </em><code>s</code>.</p> <p>A <b>substring</b> is a contiguous sequence of characters within a string.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;01000111&quot; <strong>Output:</strong> 6 <strong>Explanation:</strong> The longest balanced substring is &quot;000111&quot;, which has length 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;00111&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest balanced substring is &quot;0011&quot;, which has length 4.&nbsp; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;111&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> There is no balanced substring except the empty substring, so the answer is 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>&#39;0&#39; &lt;= s[i] &lt;= &#39;1&#39;</code></li> </ul>
String
TypeScript
function findTheLongestBalancedSubstring(s: string): number { const n = s.length; let ans = 0; const check = (i: number, j: number): boolean => { let cnt = 0; for (let k = i; k <= j; ++k) { if (s[k] === '1') { ++cnt; } else if (cnt > 0) { return false; } } return cnt * 2 === j - i + 1; }; for (let i = 0; i < n; ++i) { for (let j = i + 1; j < n; j += 2) { if (check(i, j)) { ans = Math.max(ans, j - i + 1); } } } return ans; }
2,610
Convert an Array Into a 2D Array With Conditions
Medium
<p>You are given an integer array <code>nums</code>. You need to create a 2D array from <code>nums</code> satisfying the following conditions:</p> <ul> <li>The 2D array should contain <strong>only</strong> the elements of the array <code>nums</code>.</li> <li>Each row in the 2D array contains <strong>distinct</strong> integers.</li> <li>The number of rows in the 2D array should be <strong>minimal</strong>.</li> </ul> <p>Return <em>the resulting array</em>. If there are multiple answers, return any of them.</p> <p><strong>Note</strong> that the 2D array can have a different number of elements on each row.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,1,2,3,1] <strong>Output:</strong> [[1,3,4,2],[1,3],[1]] <strong>Explanation:</strong> We can create a 2D array that contains the following rows: - 1,3,4,2 - 1,3 - 1 All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer. It can be shown that we cannot have less than 3 rows in a valid array.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [[4,3,2,1]] <strong>Explanation:</strong> All elements of the array are distinct, so we can keep all of them in the first row of the 2D array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> </ul>
Array; Hash Table
C++
class Solution { public: vector<vector<int>> findMatrix(vector<int>& nums) { vector<vector<int>> ans; int n = nums.size(); vector<int> cnt(n + 1); for (int& x : nums) { ++cnt[x]; } for (int x = 1; x <= n; ++x) { int v = cnt[x]; for (int j = 0; j < v; ++j) { if (ans.size() <= j) { ans.push_back({}); } ans[j].push_back(x); } } return ans; } };
2,610
Convert an Array Into a 2D Array With Conditions
Medium
<p>You are given an integer array <code>nums</code>. You need to create a 2D array from <code>nums</code> satisfying the following conditions:</p> <ul> <li>The 2D array should contain <strong>only</strong> the elements of the array <code>nums</code>.</li> <li>Each row in the 2D array contains <strong>distinct</strong> integers.</li> <li>The number of rows in the 2D array should be <strong>minimal</strong>.</li> </ul> <p>Return <em>the resulting array</em>. If there are multiple answers, return any of them.</p> <p><strong>Note</strong> that the 2D array can have a different number of elements on each row.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,1,2,3,1] <strong>Output:</strong> [[1,3,4,2],[1,3],[1]] <strong>Explanation:</strong> We can create a 2D array that contains the following rows: - 1,3,4,2 - 1,3 - 1 All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer. It can be shown that we cannot have less than 3 rows in a valid array.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [[4,3,2,1]] <strong>Explanation:</strong> All elements of the array are distinct, so we can keep all of them in the first row of the 2D array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> </ul>
Array; Hash Table
Go
func findMatrix(nums []int) (ans [][]int) { n := len(nums) cnt := make([]int, n+1) for _, x := range nums { cnt[x]++ } for x, v := range cnt { for j := 0; j < v; j++ { if len(ans) <= j { ans = append(ans, []int{}) } ans[j] = append(ans[j], x) } } return }
2,610
Convert an Array Into a 2D Array With Conditions
Medium
<p>You are given an integer array <code>nums</code>. You need to create a 2D array from <code>nums</code> satisfying the following conditions:</p> <ul> <li>The 2D array should contain <strong>only</strong> the elements of the array <code>nums</code>.</li> <li>Each row in the 2D array contains <strong>distinct</strong> integers.</li> <li>The number of rows in the 2D array should be <strong>minimal</strong>.</li> </ul> <p>Return <em>the resulting array</em>. If there are multiple answers, return any of them.</p> <p><strong>Note</strong> that the 2D array can have a different number of elements on each row.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,1,2,3,1] <strong>Output:</strong> [[1,3,4,2],[1,3],[1]] <strong>Explanation:</strong> We can create a 2D array that contains the following rows: - 1,3,4,2 - 1,3 - 1 All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer. It can be shown that we cannot have less than 3 rows in a valid array.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [[4,3,2,1]] <strong>Explanation:</strong> All elements of the array are distinct, so we can keep all of them in the first row of the 2D array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> </ul>
Array; Hash Table
Java
class Solution { public List<List<Integer>> findMatrix(int[] nums) { List<List<Integer>> ans = new ArrayList<>(); int n = nums.length; int[] cnt = new int[n + 1]; for (int x : nums) { ++cnt[x]; } for (int x = 1; x <= n; ++x) { int v = cnt[x]; for (int j = 0; j < v; ++j) { if (ans.size() <= j) { ans.add(new ArrayList<>()); } ans.get(j).add(x); } } return ans; } }
2,610
Convert an Array Into a 2D Array With Conditions
Medium
<p>You are given an integer array <code>nums</code>. You need to create a 2D array from <code>nums</code> satisfying the following conditions:</p> <ul> <li>The 2D array should contain <strong>only</strong> the elements of the array <code>nums</code>.</li> <li>Each row in the 2D array contains <strong>distinct</strong> integers.</li> <li>The number of rows in the 2D array should be <strong>minimal</strong>.</li> </ul> <p>Return <em>the resulting array</em>. If there are multiple answers, return any of them.</p> <p><strong>Note</strong> that the 2D array can have a different number of elements on each row.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,1,2,3,1] <strong>Output:</strong> [[1,3,4,2],[1,3],[1]] <strong>Explanation:</strong> We can create a 2D array that contains the following rows: - 1,3,4,2 - 1,3 - 1 All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer. It can be shown that we cannot have less than 3 rows in a valid array.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [[4,3,2,1]] <strong>Explanation:</strong> All elements of the array are distinct, so we can keep all of them in the first row of the 2D array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> </ul>
Array; Hash Table
Python
class Solution: def findMatrix(self, nums: List[int]) -> List[List[int]]: cnt = Counter(nums) ans = [] for x, v in cnt.items(): for i in range(v): if len(ans) <= i: ans.append([]) ans[i].append(x) return ans
2,610
Convert an Array Into a 2D Array With Conditions
Medium
<p>You are given an integer array <code>nums</code>. You need to create a 2D array from <code>nums</code> satisfying the following conditions:</p> <ul> <li>The 2D array should contain <strong>only</strong> the elements of the array <code>nums</code>.</li> <li>Each row in the 2D array contains <strong>distinct</strong> integers.</li> <li>The number of rows in the 2D array should be <strong>minimal</strong>.</li> </ul> <p>Return <em>the resulting array</em>. If there are multiple answers, return any of them.</p> <p><strong>Note</strong> that the 2D array can have a different number of elements on each row.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,1,2,3,1] <strong>Output:</strong> [[1,3,4,2],[1,3],[1]] <strong>Explanation:</strong> We can create a 2D array that contains the following rows: - 1,3,4,2 - 1,3 - 1 All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer. It can be shown that we cannot have less than 3 rows in a valid array.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [[4,3,2,1]] <strong>Explanation:</strong> All elements of the array are distinct, so we can keep all of them in the first row of the 2D array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> </ul>
Array; Hash Table
Rust
impl Solution { pub fn find_matrix(nums: Vec<i32>) -> Vec<Vec<i32>> { let n = nums.len(); let mut cnt = vec![0; n + 1]; let mut ans: Vec<Vec<i32>> = Vec::new(); for &x in &nums { cnt[x as usize] += 1; } for x in 1..=n as i32 { for j in 0..cnt[x as usize] { if ans.len() <= j { ans.push(Vec::new()); } ans[j].push(x); } } ans } }
2,610
Convert an Array Into a 2D Array With Conditions
Medium
<p>You are given an integer array <code>nums</code>. You need to create a 2D array from <code>nums</code> satisfying the following conditions:</p> <ul> <li>The 2D array should contain <strong>only</strong> the elements of the array <code>nums</code>.</li> <li>Each row in the 2D array contains <strong>distinct</strong> integers.</li> <li>The number of rows in the 2D array should be <strong>minimal</strong>.</li> </ul> <p>Return <em>the resulting array</em>. If there are multiple answers, return any of them.</p> <p><strong>Note</strong> that the 2D array can have a different number of elements on each row.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,1,2,3,1] <strong>Output:</strong> [[1,3,4,2],[1,3],[1]] <strong>Explanation:</strong> We can create a 2D array that contains the following rows: - 1,3,4,2 - 1,3 - 1 All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer. It can be shown that we cannot have less than 3 rows in a valid array.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> [[4,3,2,1]] <strong>Explanation:</strong> All elements of the array are distinct, so we can keep all of them in the first row of the 2D array. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>1 &lt;= nums[i] &lt;= nums.length</code></li> </ul>
Array; Hash Table
TypeScript
function findMatrix(nums: number[]): number[][] { const ans: number[][] = []; const n = nums.length; const cnt: number[] = Array(n + 1).fill(0); for (const x of nums) { ++cnt[x]; } for (let x = 1; x <= n; ++x) { for (let j = 0; j < cnt[x]; ++j) { if (ans.length <= j) { ans.push([]); } ans[j].push(x); } } return ans; }
2,611
Mice and Cheese
Medium
<p>There are two mice and <code>n</code> different types of cheese, each type of cheese should be eaten by exactly one mouse.</p> <p>A point of the cheese with index <code>i</code> (<strong>0-indexed</strong>) is:</p> <ul> <li><code>reward1[i]</code> if the first mouse eats it.</li> <li><code>reward2[i]</code> if the second mouse eats it.</li> </ul> <p>You are given a positive integer array <code>reward1</code>, a positive integer array <code>reward2</code>, and a non-negative integer <code>k</code>.</p> <p>Return <em><strong>the maximum</strong> points the mice can achieve if the first mouse eats exactly </em><code>k</code><em> types of cheese.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2 <strong>Output:</strong> 15 <strong>Explanation:</strong> In this example, the first mouse eats the 2<sup>nd</sup>&nbsp;(0-indexed) and the 3<sup>rd</sup>&nbsp;types of cheese, and the second mouse eats the 0<sup>th</sup>&nbsp;and the 1<sup>st</sup> types of cheese. The total points are 4 + 4 + 3 + 4 = 15. It can be proven that 15 is the maximum total points that the mice can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> reward1 = [1,1], reward2 = [1,1], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the first mouse eats the 0<sup>th</sup>&nbsp;(0-indexed) and 1<sup>st</sup>&nbsp;types of cheese, and the second mouse does not eat any cheese. The total points are 1 + 1 = 2. It can be proven that 2 is the maximum total points that the mice can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == reward1.length == reward2.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= reward1[i],&nbsp;reward2[i] &lt;= 1000</code></li> <li><code>0 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
C++
class Solution { public: int miceAndCheese(vector<int>& reward1, vector<int>& reward2, int k) { int n = reward1.size(); vector<int> idx(n); iota(idx.begin(), idx.end(), 0); sort(idx.begin(), idx.end(), [&](int i, int j) { return reward1[j] - reward2[j] < reward1[i] - reward2[i]; }); int ans = 0; for (int i = 0; i < k; ++i) { ans += reward1[idx[i]]; } for (int i = k; i < n; ++i) { ans += reward2[idx[i]]; } return ans; } };
2,611
Mice and Cheese
Medium
<p>There are two mice and <code>n</code> different types of cheese, each type of cheese should be eaten by exactly one mouse.</p> <p>A point of the cheese with index <code>i</code> (<strong>0-indexed</strong>) is:</p> <ul> <li><code>reward1[i]</code> if the first mouse eats it.</li> <li><code>reward2[i]</code> if the second mouse eats it.</li> </ul> <p>You are given a positive integer array <code>reward1</code>, a positive integer array <code>reward2</code>, and a non-negative integer <code>k</code>.</p> <p>Return <em><strong>the maximum</strong> points the mice can achieve if the first mouse eats exactly </em><code>k</code><em> types of cheese.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2 <strong>Output:</strong> 15 <strong>Explanation:</strong> In this example, the first mouse eats the 2<sup>nd</sup>&nbsp;(0-indexed) and the 3<sup>rd</sup>&nbsp;types of cheese, and the second mouse eats the 0<sup>th</sup>&nbsp;and the 1<sup>st</sup> types of cheese. The total points are 4 + 4 + 3 + 4 = 15. It can be proven that 15 is the maximum total points that the mice can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> reward1 = [1,1], reward2 = [1,1], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the first mouse eats the 0<sup>th</sup>&nbsp;(0-indexed) and 1<sup>st</sup>&nbsp;types of cheese, and the second mouse does not eat any cheese. The total points are 1 + 1 = 2. It can be proven that 2 is the maximum total points that the mice can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == reward1.length == reward2.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= reward1[i],&nbsp;reward2[i] &lt;= 1000</code></li> <li><code>0 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Go
func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) { n := len(reward1) idx := make([]int, n) for i := range idx { idx[i] = i } sort.Slice(idx, func(i, j int) bool { i, j = idx[i], idx[j] return reward1[j]-reward2[j] < reward1[i]-reward2[i] }) for i := 0; i < k; i++ { ans += reward1[idx[i]] } for i := k; i < n; i++ { ans += reward2[idx[i]] } return }
2,611
Mice and Cheese
Medium
<p>There are two mice and <code>n</code> different types of cheese, each type of cheese should be eaten by exactly one mouse.</p> <p>A point of the cheese with index <code>i</code> (<strong>0-indexed</strong>) is:</p> <ul> <li><code>reward1[i]</code> if the first mouse eats it.</li> <li><code>reward2[i]</code> if the second mouse eats it.</li> </ul> <p>You are given a positive integer array <code>reward1</code>, a positive integer array <code>reward2</code>, and a non-negative integer <code>k</code>.</p> <p>Return <em><strong>the maximum</strong> points the mice can achieve if the first mouse eats exactly </em><code>k</code><em> types of cheese.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2 <strong>Output:</strong> 15 <strong>Explanation:</strong> In this example, the first mouse eats the 2<sup>nd</sup>&nbsp;(0-indexed) and the 3<sup>rd</sup>&nbsp;types of cheese, and the second mouse eats the 0<sup>th</sup>&nbsp;and the 1<sup>st</sup> types of cheese. The total points are 4 + 4 + 3 + 4 = 15. It can be proven that 15 is the maximum total points that the mice can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> reward1 = [1,1], reward2 = [1,1], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the first mouse eats the 0<sup>th</sup>&nbsp;(0-indexed) and 1<sup>st</sup>&nbsp;types of cheese, and the second mouse does not eat any cheese. The total points are 1 + 1 = 2. It can be proven that 2 is the maximum total points that the mice can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == reward1.length == reward2.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= reward1[i],&nbsp;reward2[i] &lt;= 1000</code></li> <li><code>0 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Java
class Solution { public int miceAndCheese(int[] reward1, int[] reward2, int k) { int n = reward1.length; Integer[] idx = new Integer[n]; Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> reward1[j] - reward2[j] - (reward1[i] - reward2[i])); int ans = 0; for (int i = 0; i < k; ++i) { ans += reward1[idx[i]]; } for (int i = k; i < n; ++i) { ans += reward2[idx[i]]; } return ans; } }
2,611
Mice and Cheese
Medium
<p>There are two mice and <code>n</code> different types of cheese, each type of cheese should be eaten by exactly one mouse.</p> <p>A point of the cheese with index <code>i</code> (<strong>0-indexed</strong>) is:</p> <ul> <li><code>reward1[i]</code> if the first mouse eats it.</li> <li><code>reward2[i]</code> if the second mouse eats it.</li> </ul> <p>You are given a positive integer array <code>reward1</code>, a positive integer array <code>reward2</code>, and a non-negative integer <code>k</code>.</p> <p>Return <em><strong>the maximum</strong> points the mice can achieve if the first mouse eats exactly </em><code>k</code><em> types of cheese.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2 <strong>Output:</strong> 15 <strong>Explanation:</strong> In this example, the first mouse eats the 2<sup>nd</sup>&nbsp;(0-indexed) and the 3<sup>rd</sup>&nbsp;types of cheese, and the second mouse eats the 0<sup>th</sup>&nbsp;and the 1<sup>st</sup> types of cheese. The total points are 4 + 4 + 3 + 4 = 15. It can be proven that 15 is the maximum total points that the mice can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> reward1 = [1,1], reward2 = [1,1], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the first mouse eats the 0<sup>th</sup>&nbsp;(0-indexed) and 1<sup>st</sup>&nbsp;types of cheese, and the second mouse does not eat any cheese. The total points are 1 + 1 = 2. It can be proven that 2 is the maximum total points that the mice can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == reward1.length == reward2.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= reward1[i],&nbsp;reward2[i] &lt;= 1000</code></li> <li><code>0 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
Python
class Solution: def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: n = len(reward1) idx = sorted(range(n), key=lambda i: reward1[i] - reward2[i], reverse=True) return sum(reward1[i] for i in idx[:k]) + sum(reward2[i] for i in idx[k:])
2,611
Mice and Cheese
Medium
<p>There are two mice and <code>n</code> different types of cheese, each type of cheese should be eaten by exactly one mouse.</p> <p>A point of the cheese with index <code>i</code> (<strong>0-indexed</strong>) is:</p> <ul> <li><code>reward1[i]</code> if the first mouse eats it.</li> <li><code>reward2[i]</code> if the second mouse eats it.</li> </ul> <p>You are given a positive integer array <code>reward1</code>, a positive integer array <code>reward2</code>, and a non-negative integer <code>k</code>.</p> <p>Return <em><strong>the maximum</strong> points the mice can achieve if the first mouse eats exactly </em><code>k</code><em> types of cheese.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2 <strong>Output:</strong> 15 <strong>Explanation:</strong> In this example, the first mouse eats the 2<sup>nd</sup>&nbsp;(0-indexed) and the 3<sup>rd</sup>&nbsp;types of cheese, and the second mouse eats the 0<sup>th</sup>&nbsp;and the 1<sup>st</sup> types of cheese. The total points are 4 + 4 + 3 + 4 = 15. It can be proven that 15 is the maximum total points that the mice can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> reward1 = [1,1], reward2 = [1,1], k = 2 <strong>Output:</strong> 2 <strong>Explanation:</strong> In this example, the first mouse eats the 0<sup>th</sup>&nbsp;(0-indexed) and 1<sup>st</sup>&nbsp;types of cheese, and the second mouse does not eat any cheese. The total points are 1 + 1 = 2. It can be proven that 2 is the maximum total points that the mice can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == reward1.length == reward2.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= reward1[i],&nbsp;reward2[i] &lt;= 1000</code></li> <li><code>0 &lt;= k &lt;= n</code></li> </ul>
Greedy; Array; Sorting; Heap (Priority Queue)
TypeScript
function miceAndCheese(reward1: number[], reward2: number[], k: number): number { const n = reward1.length; const idx = Array.from({ length: n }, (_, i) => i); idx.sort((i, j) => reward1[j] - reward2[j] - (reward1[i] - reward2[i])); let ans = 0; for (let i = 0; i < k; ++i) { ans += reward1[idx[i]]; } for (let i = k; i < n; ++i) { ans += reward2[idx[i]]; } return ans; }
2,612
Minimum Reverse Operations
Hard
<p>You are given an integer <code>n</code> and an integer <code>p</code> representing an array <code>arr</code> of length <code>n</code> where all elements are set to 0&#39;s, except position <code>p</code> which is set to 1. You are also given an integer array <code>banned</code> containing restricted positions. Perform the following operation on <code>arr</code>:</p> <ul> <li>Reverse a <span data-keyword="subarray-nonempty"><strong>subarray</strong></span> with size <code>k</code> if the single 1 is not set to a position in <code>banned</code>.</li> </ul> <p>Return an integer array <code>answer</code> with <code>n</code> results where the <code>i<sup>th</sup></code> result is<em> </em>the <strong>minimum</strong> number of operations needed to bring the single 1 to position <code>i</code> in <code>arr</code>, or -1 if it is impossible.</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 = 4, p = 0, banned = [1,2], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[0,-1,-1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially 1 is placed at position 0 so the number of operations we need for position 0 is 0.</li> <li>We can never place 1 on the banned positions, so the answer for positions 1 and 2 is -1.</li> <li>Perform the operation of size 4 to reverse the whole array.</li> <li>After a single operation 1 is at position 3 so the answer for position 3 is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, p = 0, banned = [2,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[0,-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially 1 is placed at position 0 so the number of operations we need for position 0 is 0.</li> <li>We cannot perform the operation on the subarray positions <code>[0, 2]</code> because position 2 is in banned.</li> <li>Because 1 cannot be set at position 2, it is impossible to set 1 at other positions in more operations.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, p = 2, banned = [0,1,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,0,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Perform operations of size 1 and 1 never changes its position.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= p &lt;= n - 1</code></li> <li><code>0 &lt;= banned.length &lt;= n - 1</code></li> <li><code>0 &lt;= banned[i] &lt;= n - 1</code></li> <li><code>1 &lt;= k &lt;= n&nbsp;</code></li> <li><code>banned[i] != p</code></li> <li>all values in <code>banned</code>&nbsp;are <strong>unique</strong>&nbsp;</li> </ul>
Breadth-First Search; Array; Ordered Set
C++
class Solution { public: vector<int> minReverseOperations(int n, int p, vector<int>& banned, int k) { vector<int> ans(n, -1); ans[p] = 0; set<int> ts[2]; for (int i = 0; i < n; ++i) { ts[i % 2].insert(i); } ts[p % 2].erase(p); for (int i : banned) { ts[i % 2].erase(i); } ts[0].insert(n); ts[1].insert(n); queue<int> q{{p}}; while (!q.empty()) { int i = q.front(); q.pop(); int mi = max(i - k + 1, k - i - 1); int mx = min(i + k - 1, n * 2 - k - i - 1); auto& s = ts[mi % 2]; auto it = s.lower_bound(mi); while (*it <= mx) { int j = *it; ans[j] = ans[i] + 1; q.push(j); it = s.erase(it); } } return ans; } };
2,612
Minimum Reverse Operations
Hard
<p>You are given an integer <code>n</code> and an integer <code>p</code> representing an array <code>arr</code> of length <code>n</code> where all elements are set to 0&#39;s, except position <code>p</code> which is set to 1. You are also given an integer array <code>banned</code> containing restricted positions. Perform the following operation on <code>arr</code>:</p> <ul> <li>Reverse a <span data-keyword="subarray-nonempty"><strong>subarray</strong></span> with size <code>k</code> if the single 1 is not set to a position in <code>banned</code>.</li> </ul> <p>Return an integer array <code>answer</code> with <code>n</code> results where the <code>i<sup>th</sup></code> result is<em> </em>the <strong>minimum</strong> number of operations needed to bring the single 1 to position <code>i</code> in <code>arr</code>, or -1 if it is impossible.</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 = 4, p = 0, banned = [1,2], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[0,-1,-1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially 1 is placed at position 0 so the number of operations we need for position 0 is 0.</li> <li>We can never place 1 on the banned positions, so the answer for positions 1 and 2 is -1.</li> <li>Perform the operation of size 4 to reverse the whole array.</li> <li>After a single operation 1 is at position 3 so the answer for position 3 is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, p = 0, banned = [2,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[0,-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially 1 is placed at position 0 so the number of operations we need for position 0 is 0.</li> <li>We cannot perform the operation on the subarray positions <code>[0, 2]</code> because position 2 is in banned.</li> <li>Because 1 cannot be set at position 2, it is impossible to set 1 at other positions in more operations.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, p = 2, banned = [0,1,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,0,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Perform operations of size 1 and 1 never changes its position.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= p &lt;= n - 1</code></li> <li><code>0 &lt;= banned.length &lt;= n - 1</code></li> <li><code>0 &lt;= banned[i] &lt;= n - 1</code></li> <li><code>1 &lt;= k &lt;= n&nbsp;</code></li> <li><code>banned[i] != p</code></li> <li>all values in <code>banned</code>&nbsp;are <strong>unique</strong>&nbsp;</li> </ul>
Breadth-First Search; Array; Ordered Set
Go
func minReverseOperations(n int, p int, banned []int, k int) []int { ans := make([]int, n) ts := [2]*redblacktree.Tree{redblacktree.NewWithIntComparator(), redblacktree.NewWithIntComparator()} for i := 0; i < n; i++ { ts[i%2].Put(i, struct{}{}) ans[i] = -1 } ans[p] = 0 ts[p%2].Remove(p) for _, i := range banned { ts[i%2].Remove(i) } ts[0].Put(n, struct{}{}) ts[1].Put(n, struct{}{}) q := []int{p} for len(q) > 0 { i := q[0] q = q[1:] mi := max(i-k+1, k-i-1) mx := min(i+k-1, n*2-k-i-1) s := ts[mi%2] for x, _ := s.Ceiling(mi); x.Key.(int) <= mx; x, _ = s.Ceiling(mi) { j := x.Key.(int) s.Remove(j) ans[j] = ans[i] + 1 q = append(q, j) } } return ans }
2,612
Minimum Reverse Operations
Hard
<p>You are given an integer <code>n</code> and an integer <code>p</code> representing an array <code>arr</code> of length <code>n</code> where all elements are set to 0&#39;s, except position <code>p</code> which is set to 1. You are also given an integer array <code>banned</code> containing restricted positions. Perform the following operation on <code>arr</code>:</p> <ul> <li>Reverse a <span data-keyword="subarray-nonempty"><strong>subarray</strong></span> with size <code>k</code> if the single 1 is not set to a position in <code>banned</code>.</li> </ul> <p>Return an integer array <code>answer</code> with <code>n</code> results where the <code>i<sup>th</sup></code> result is<em> </em>the <strong>minimum</strong> number of operations needed to bring the single 1 to position <code>i</code> in <code>arr</code>, or -1 if it is impossible.</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 = 4, p = 0, banned = [1,2], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[0,-1,-1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially 1 is placed at position 0 so the number of operations we need for position 0 is 0.</li> <li>We can never place 1 on the banned positions, so the answer for positions 1 and 2 is -1.</li> <li>Perform the operation of size 4 to reverse the whole array.</li> <li>After a single operation 1 is at position 3 so the answer for position 3 is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, p = 0, banned = [2,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[0,-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially 1 is placed at position 0 so the number of operations we need for position 0 is 0.</li> <li>We cannot perform the operation on the subarray positions <code>[0, 2]</code> because position 2 is in banned.</li> <li>Because 1 cannot be set at position 2, it is impossible to set 1 at other positions in more operations.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, p = 2, banned = [0,1,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,0,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Perform operations of size 1 and 1 never changes its position.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= p &lt;= n - 1</code></li> <li><code>0 &lt;= banned.length &lt;= n - 1</code></li> <li><code>0 &lt;= banned[i] &lt;= n - 1</code></li> <li><code>1 &lt;= k &lt;= n&nbsp;</code></li> <li><code>banned[i] != p</code></li> <li>all values in <code>banned</code>&nbsp;are <strong>unique</strong>&nbsp;</li> </ul>
Breadth-First Search; Array; Ordered Set
Java
class Solution { public int[] minReverseOperations(int n, int p, int[] banned, int k) { int[] ans = new int[n]; TreeSet<Integer>[] ts = new TreeSet[] {new TreeSet<>(), new TreeSet<>()}; for (int i = 0; i < n; ++i) { ts[i % 2].add(i); ans[i] = i == p ? 0 : -1; } ts[p % 2].remove(p); for (int i : banned) { ts[i % 2].remove(i); } ts[0].add(n); ts[1].add(n); Deque<Integer> q = new ArrayDeque<>(); q.offer(p); while (!q.isEmpty()) { int i = q.poll(); int mi = Math.max(i - k + 1, k - i - 1); int mx = Math.min(i + k - 1, n * 2 - k - i - 1); var s = ts[mi % 2]; for (int j = s.ceiling(mi); j <= mx; j = s.ceiling(mi)) { q.offer(j); ans[j] = ans[i] + 1; s.remove(j); } } return ans; } }
2,612
Minimum Reverse Operations
Hard
<p>You are given an integer <code>n</code> and an integer <code>p</code> representing an array <code>arr</code> of length <code>n</code> where all elements are set to 0&#39;s, except position <code>p</code> which is set to 1. You are also given an integer array <code>banned</code> containing restricted positions. Perform the following operation on <code>arr</code>:</p> <ul> <li>Reverse a <span data-keyword="subarray-nonempty"><strong>subarray</strong></span> with size <code>k</code> if the single 1 is not set to a position in <code>banned</code>.</li> </ul> <p>Return an integer array <code>answer</code> with <code>n</code> results where the <code>i<sup>th</sup></code> result is<em> </em>the <strong>minimum</strong> number of operations needed to bring the single 1 to position <code>i</code> in <code>arr</code>, or -1 if it is impossible.</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 = 4, p = 0, banned = [1,2], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[0,-1,-1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially 1 is placed at position 0 so the number of operations we need for position 0 is 0.</li> <li>We can never place 1 on the banned positions, so the answer for positions 1 and 2 is -1.</li> <li>Perform the operation of size 4 to reverse the whole array.</li> <li>After a single operation 1 is at position 3 so the answer for position 3 is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, p = 0, banned = [2,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[0,-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially 1 is placed at position 0 so the number of operations we need for position 0 is 0.</li> <li>We cannot perform the operation on the subarray positions <code>[0, 2]</code> because position 2 is in banned.</li> <li>Because 1 cannot be set at position 2, it is impossible to set 1 at other positions in more operations.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, p = 2, banned = [0,1,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,0,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Perform operations of size 1 and 1 never changes its position.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= p &lt;= n - 1</code></li> <li><code>0 &lt;= banned.length &lt;= n - 1</code></li> <li><code>0 &lt;= banned[i] &lt;= n - 1</code></li> <li><code>1 &lt;= k &lt;= n&nbsp;</code></li> <li><code>banned[i] != p</code></li> <li>all values in <code>banned</code>&nbsp;are <strong>unique</strong>&nbsp;</li> </ul>
Breadth-First Search; Array; Ordered Set
Python
class Solution: def minReverseOperations( self, n: int, p: int, banned: List[int], k: int ) -> List[int]: ans = [-1] * n ans[p] = 0 ts = [SortedSet() for _ in range(2)] for i in range(n): ts[i % 2].add(i) ts[p % 2].remove(p) for i in banned: ts[i % 2].remove(i) ts[0].add(n) ts[1].add(n) q = deque([p]) while q: i = q.popleft() mi = max(i - k + 1, k - i - 1) mx = min(i + k - 1, n * 2 - k - i - 1) s = ts[mi % 2] j = s.bisect_left(mi) while s[j] <= mx: q.append(s[j]) ans[s[j]] = ans[i] + 1 s.remove(s[j]) j = s.bisect_left(mi) return ans
2,612
Minimum Reverse Operations
Hard
<p>You are given an integer <code>n</code> and an integer <code>p</code> representing an array <code>arr</code> of length <code>n</code> where all elements are set to 0&#39;s, except position <code>p</code> which is set to 1. You are also given an integer array <code>banned</code> containing restricted positions. Perform the following operation on <code>arr</code>:</p> <ul> <li>Reverse a <span data-keyword="subarray-nonempty"><strong>subarray</strong></span> with size <code>k</code> if the single 1 is not set to a position in <code>banned</code>.</li> </ul> <p>Return an integer array <code>answer</code> with <code>n</code> results where the <code>i<sup>th</sup></code> result is<em> </em>the <strong>minimum</strong> number of operations needed to bring the single 1 to position <code>i</code> in <code>arr</code>, or -1 if it is impossible.</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 = 4, p = 0, banned = [1,2], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[0,-1,-1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially 1 is placed at position 0 so the number of operations we need for position 0 is 0.</li> <li>We can never place 1 on the banned positions, so the answer for positions 1 and 2 is -1.</li> <li>Perform the operation of size 4 to reverse the whole array.</li> <li>After a single operation 1 is at position 3 so the answer for position 3 is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, p = 0, banned = [2,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[0,-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially 1 is placed at position 0 so the number of operations we need for position 0 is 0.</li> <li>We cannot perform the operation on the subarray positions <code>[0, 2]</code> because position 2 is in banned.</li> <li>Because 1 cannot be set at position 2, it is impossible to set 1 at other positions in more operations.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, p = 2, banned = [0,1,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,0,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Perform operations of size 1 and 1 never changes its position.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= p &lt;= n - 1</code></li> <li><code>0 &lt;= banned.length &lt;= n - 1</code></li> <li><code>0 &lt;= banned[i] &lt;= n - 1</code></li> <li><code>1 &lt;= k &lt;= n&nbsp;</code></li> <li><code>banned[i] != p</code></li> <li>all values in <code>banned</code>&nbsp;are <strong>unique</strong>&nbsp;</li> </ul>
Breadth-First Search; Array; Ordered Set
Rust
use std::collections::{BTreeSet, VecDeque}; impl Solution { pub fn min_reverse_operations(n: i32, p: i32, banned: Vec<i32>, k: i32) -> Vec<i32> { let mut ans = vec![-1; n as usize]; let mut ts = [BTreeSet::new(), BTreeSet::new()]; for i in 0..n { ts[(i % 2) as usize].insert(i); } ans[p as usize] = 0; ts[(p % 2) as usize].remove(&p); for &b in &banned { ts[(b % 2) as usize].remove(&b); } ts[0].insert(n); ts[1].insert(n); let mut q = VecDeque::new(); q.push_back(p); while let Some(i) = q.pop_front() { let mi = (i - k + 1).max(k - i - 1); let mx = (i + k - 1).min(2 * n - k - i - 1); let s = &mut ts[(mi % 2) as usize]; while let Some(&j) = s.range(mi..=mx).next() { q.push_back(j); ans[j as usize] = ans[i as usize] + 1; s.remove(&j); } } ans } }
2,612
Minimum Reverse Operations
Hard
<p>You are given an integer <code>n</code> and an integer <code>p</code> representing an array <code>arr</code> of length <code>n</code> where all elements are set to 0&#39;s, except position <code>p</code> which is set to 1. You are also given an integer array <code>banned</code> containing restricted positions. Perform the following operation on <code>arr</code>:</p> <ul> <li>Reverse a <span data-keyword="subarray-nonempty"><strong>subarray</strong></span> with size <code>k</code> if the single 1 is not set to a position in <code>banned</code>.</li> </ul> <p>Return an integer array <code>answer</code> with <code>n</code> results where the <code>i<sup>th</sup></code> result is<em> </em>the <strong>minimum</strong> number of operations needed to bring the single 1 to position <code>i</code> in <code>arr</code>, or -1 if it is impossible.</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 = 4, p = 0, banned = [1,2], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">[0,-1,-1,1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially 1 is placed at position 0 so the number of operations we need for position 0 is 0.</li> <li>We can never place 1 on the banned positions, so the answer for positions 1 and 2 is -1.</li> <li>Perform the operation of size 4 to reverse the whole array.</li> <li>After a single operation 1 is at position 3 so the answer for position 3 is 1.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, p = 0, banned = [2,4], k = 3</span></p> <p><strong>Output:</strong> <span class="example-io">[0,-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially 1 is placed at position 0 so the number of operations we need for position 0 is 0.</li> <li>We cannot perform the operation on the subarray positions <code>[0, 2]</code> because position 2 is in banned.</li> <li>Because 1 cannot be set at position 2, it is impossible to set 1 at other positions in more operations.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, p = 2, banned = [0,1,3], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,0,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Perform operations of size 1 and 1 never changes its position.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= p &lt;= n - 1</code></li> <li><code>0 &lt;= banned.length &lt;= n - 1</code></li> <li><code>0 &lt;= banned[i] &lt;= n - 1</code></li> <li><code>1 &lt;= k &lt;= n&nbsp;</code></li> <li><code>banned[i] != p</code></li> <li>all values in <code>banned</code>&nbsp;are <strong>unique</strong>&nbsp;</li> </ul>
Breadth-First Search; Array; Ordered Set
TypeScript
function minReverseOperations(n: number, p: number, banned: number[], k: number): number[] { const ans: number[] = Array(n).fill(-1); const ts = [new TreeSet<number>(), new TreeSet<number>()]; for (let i = 0; i < n; ++i) { ts[i % 2].add(i); } ans[p] = 0; ts[p % 2].delete(p); for (const i of banned) { ts[i % 2].delete(i); } ts[0].add(n); ts[1].add(n); let q = [p]; while (q.length) { const t: number[] = []; for (const i of q) { const mi = Math.max(i - k + 1, k - i - 1); const mx = Math.min(i + k - 1, n * 2 - k - i - 1); const s = ts[mi % 2]; for (let j = s.ceil(mi)!; j <= mx; j = s.ceil(j)!) { t.push(j); ans[j] = ans[i] + 1; s.delete(j); } } q = t; } return ans; } type Compare<T> = (lhs: T, rhs: T) => number; class RBTreeNode<T = number> { data: T; count: number; left: RBTreeNode<T> | null; right: RBTreeNode<T> | null; parent: RBTreeNode<T> | null; color: number; constructor(data: T) { this.data = data; this.left = this.right = this.parent = null; this.color = 0; this.count = 1; } sibling(): RBTreeNode<T> | null { if (!this.parent) return null; // sibling null if no parent return this.isOnLeft() ? this.parent.right : this.parent.left; } isOnLeft(): boolean { return this === this.parent!.left; } hasRedChild(): boolean { return ( Boolean(this.left && this.left.color === 0) || Boolean(this.right && this.right.color === 0) ); } } class RBTree<T> { root: RBTreeNode<T> | null; lt: (l: T, r: T) => boolean; constructor(compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0)) { this.root = null; this.lt = (l: T, r: T) => compare(l, r) < 0; } rotateLeft(pt: RBTreeNode<T>): void { const right = pt.right!; pt.right = right.left; if (pt.right) pt.right.parent = pt; right.parent = pt.parent; if (!pt.parent) this.root = right; else if (pt === pt.parent.left) pt.parent.left = right; else pt.parent.right = right; right.left = pt; pt.parent = right; } rotateRight(pt: RBTreeNode<T>): void { const left = pt.left!; pt.left = left.right; if (pt.left) pt.left.parent = pt; left.parent = pt.parent; if (!pt.parent) this.root = left; else if (pt === pt.parent.left) pt.parent.left = left; else pt.parent.right = left; left.right = pt; pt.parent = left; } swapColor(p1: RBTreeNode<T>, p2: RBTreeNode<T>): void { const tmp = p1.color; p1.color = p2.color; p2.color = tmp; } swapData(p1: RBTreeNode<T>, p2: RBTreeNode<T>): void { const tmp = p1.data; p1.data = p2.data; p2.data = tmp; } fixAfterInsert(pt: RBTreeNode<T>): void { let parent = null; let grandParent = null; while (pt !== this.root && pt.color !== 1 && pt.parent?.color === 0) { parent = pt.parent; grandParent = pt.parent.parent; /* Case : A Parent of pt is left child of Grand-parent of pt */ if (parent === grandParent?.left) { const uncle = grandParent.right; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if (uncle && uncle.color === 0) { grandParent.color = 0; parent.color = 1; uncle.color = 1; pt = grandParent; } else { /* Case : 2 pt is right child of its parent Left-rotation required */ if (pt === parent.right) { this.rotateLeft(parent); pt = parent; parent = pt.parent; } /* Case : 3 pt is left child of its parent Right-rotation required */ this.rotateRight(grandParent); this.swapColor(parent!, grandParent); pt = parent!; } } else { /* Case : B Parent of pt is right child of Grand-parent of pt */ const uncle = grandParent!.left; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if (uncle != null && uncle.color === 0) { grandParent!.color = 0; parent.color = 1; uncle.color = 1; pt = grandParent!; } else { /* Case : 2 pt is left child of its parent Right-rotation required */ if (pt === parent.left) { this.rotateRight(parent); pt = parent; parent = pt.parent; } /* Case : 3 pt is right child of its parent Left-rotation required */ this.rotateLeft(grandParent!); this.swapColor(parent!, grandParent!); pt = parent!; } } } this.root!.color = 1; } delete(val: T): boolean { const node = this.find(val); if (!node) return false; node.count--; if (!node.count) this.deleteNode(node); return true; } deleteAll(val: T): boolean { const node = this.find(val); if (!node) return false; this.deleteNode(node); return true; } deleteNode(v: RBTreeNode<T>): void { const u = BSTreplace(v); // True when u and v are both black const uvBlack = (u === null || u.color === 1) && v.color === 1; const parent = v.parent!; if (!u) { // u is null therefore v is leaf if (v === this.root) this.root = null; // v is root, making root null else { if (uvBlack) { // u and v both black // v is leaf, fix double black at v this.fixDoubleBlack(v); } else { // u or v is red if (v.sibling()) { // sibling is not null, make it red" v.sibling()!.color = 0; } } // delete v from the tree if (v.isOnLeft()) parent.left = null; else parent.right = null; } return; } if (!v.left || !v.right) { // v has 1 child if (v === this.root) { // v is root, assign the value of u to v, and delete u v.data = u.data; v.left = v.right = null; } else { // Detach v from tree and move u up if (v.isOnLeft()) parent.left = u; else parent.right = u; u.parent = parent; if (uvBlack) this.fixDoubleBlack(u); // u and v both black, fix double black at u else u.color = 1; // u or v red, color u black } return; } // v has 2 children, swap data with successor and recurse this.swapData(u, v); this.deleteNode(u); // find node that replaces a deleted node in BST function BSTreplace(x: RBTreeNode<T>): RBTreeNode<T> | null { // when node have 2 children if (x.left && x.right) return successor(x.right); // when leaf if (!x.left && !x.right) return null; // when single child return x.left ?? x.right; } // find node that do not have a left child // in the subtree of the given node function successor(x: RBTreeNode<T>): RBTreeNode<T> { let temp = x; while (temp.left) temp = temp.left; return temp; } } fixDoubleBlack(x: RBTreeNode<T>): void { if (x === this.root) return; // Reached root const sibling = x.sibling(); const parent = x.parent!; if (!sibling) { // No sibiling, double black pushed up this.fixDoubleBlack(parent); } else { if (sibling.color === 0) { // Sibling red parent.color = 0; sibling.color = 1; if (sibling.isOnLeft()) this.rotateRight(parent); // left case else this.rotateLeft(parent); // right case this.fixDoubleBlack(x); } else { // Sibling black if (sibling.hasRedChild()) { // at least 1 red children if (sibling.left && sibling.left.color === 0) { if (sibling.isOnLeft()) { // left left sibling.left.color = sibling.color; sibling.color = parent.color; this.rotateRight(parent); } else { // right left sibling.left.color = parent.color; this.rotateRight(sibling); this.rotateLeft(parent); } } else { if (sibling.isOnLeft()) { // left right sibling.right!.color = parent.color; this.rotateLeft(sibling); this.rotateRight(parent); } else { // right right sibling.right!.color = sibling.color; sibling.color = parent.color; this.rotateLeft(parent); } } parent.color = 1; } else { // 2 black children sibling.color = 0; if (parent.color === 1) this.fixDoubleBlack(parent); else parent.color = 1; } } } } insert(data: T): boolean { // search for a position to insert let parent = this.root; while (parent) { if (this.lt(data, parent.data)) { if (!parent.left) break; else parent = parent.left; } else if (this.lt(parent.data, data)) { if (!parent.right) break; else parent = parent.right; } else break; } // insert node into parent const node = new RBTreeNode(data); if (!parent) this.root = node; else if (this.lt(node.data, parent.data)) parent.left = node; else if (this.lt(parent.data, node.data)) parent.right = node; else { parent.count++; return false; } node.parent = parent; this.fixAfterInsert(node); return true; } find(data: T): RBTreeNode<T> | null { let p = this.root; while (p) { if (this.lt(data, p.data)) { p = p.left; } else if (this.lt(p.data, data)) { p = p.right; } else break; } return p ?? null; } *inOrder(root: RBTreeNode<T> = this.root!): Generator<T, undefined, void> { if (!root) return; for (const v of this.inOrder(root.left!)) yield v; yield root.data; for (const v of this.inOrder(root.right!)) yield v; } *reverseInOrder(root: RBTreeNode<T> = this.root!): Generator<T, undefined, void> { if (!root) return; for (const v of this.reverseInOrder(root.right!)) yield v; yield root.data; for (const v of this.reverseInOrder(root.left!)) yield v; } } class TreeSet<T = number> { _size: number; tree: RBTree<T>; compare: Compare<T>; constructor( collection: T[] | Compare<T> = [], compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0), ) { if (typeof collection === 'function') { compare = collection; collection = []; } this._size = 0; this.compare = compare; this.tree = new RBTree(compare); for (const val of collection) this.add(val); } size(): number { return this._size; } has(val: T): boolean { return !!this.tree.find(val); } add(val: T): boolean { const successful = this.tree.insert(val); this._size += successful ? 1 : 0; return successful; } delete(val: T): boolean { const deleted = this.tree.deleteAll(val); this._size -= deleted ? 1 : 0; return deleted; } ceil(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(p.data, val) >= 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } floor(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(val, p.data) >= 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } higher(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(val, p.data) < 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } lower(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(p.data, val) < 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } first(): T | undefined { return this.tree.inOrder().next().value; } last(): T | undefined { return this.tree.reverseInOrder().next().value; } shift(): T | undefined { const first = this.first(); if (first === undefined) return undefined; this.delete(first); return first; } pop(): T | undefined { const last = this.last(); if (last === undefined) return undefined; this.delete(last); return last; } *[Symbol.iterator](): Generator<T, void, void> { for (const val of this.values()) yield val; } *keys(): Generator<T, void, void> { for (const val of this.values()) yield val; } *values(): Generator<T, undefined, void> { for (const val of this.tree.inOrder()) yield val; return undefined; } /** * Return a generator for reverse order traversing the set */ *rvalues(): Generator<T, undefined, void> { for (const val of this.tree.reverseInOrder()) yield val; return undefined; } } class TreeMultiSet<T = number> { _size: number; tree: RBTree<T>; compare: Compare<T>; constructor( collection: T[] | Compare<T> = [], compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0), ) { if (typeof collection === 'function') { compare = collection; collection = []; } this._size = 0; this.compare = compare; this.tree = new RBTree(compare); for (const val of collection) this.add(val); } size(): number { return this._size; } has(val: T): boolean { return !!this.tree.find(val); } add(val: T): boolean { const successful = this.tree.insert(val); this._size++; return successful; } delete(val: T): boolean { const successful = this.tree.delete(val); if (!successful) return false; this._size--; return true; } count(val: T): number { const node = this.tree.find(val); return node ? node.count : 0; } ceil(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(p.data, val) >= 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } floor(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(val, p.data) >= 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } higher(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(val, p.data) < 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } lower(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(p.data, val) < 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } first(): T | undefined { return this.tree.inOrder().next().value; } last(): T | undefined { return this.tree.reverseInOrder().next().value; } shift(): T | undefined { const first = this.first(); if (first === undefined) return undefined; this.delete(first); return first; } pop(): T | undefined { const last = this.last(); if (last === undefined) return undefined; this.delete(last); return last; } *[Symbol.iterator](): Generator<T, void, void> { yield* this.values(); } *keys(): Generator<T, void, void> { for (const val of this.values()) yield val; } *values(): Generator<T, undefined, void> { for (const val of this.tree.inOrder()) { let count = this.count(val); while (count--) yield val; } return undefined; } /** * Return a generator for reverse order traversing the multi-set */ *rvalues(): Generator<T, undefined, void> { for (const val of this.tree.reverseInOrder()) { let count = this.count(val); while (count--) yield val; } return undefined; } }
2,613
Beautiful Pairs
Hard
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of the same length. A pair of indices <code>(i,j)</code> is called <strong>beautiful</strong> if<code>|nums1[i] - nums1[j]| + |nums2[i] - nums2[j]|</code> is the smallest amongst all possible indices pairs where <code>i &lt; j</code>.</p> <p>Return <em>the beautiful pair. In the case that there are multiple beautiful pairs, return the lexicographically smallest pair.</em></p> <p>Note that</p> <ul> <li><code>|x|</code> denotes the absolute value of <code>x</code>.</li> <li>A pair of indices <code>(i<sub>1</sub>, j<sub>1</sub>)</code> is lexicographically smaller than <code>(i<sub>2</sub>, j<sub>2</sub>)</code> if <code>i<sub>1</sub> &lt; i<sub>2</sub></code> or <code>i<sub>1</sub> == i<sub>2</sub></code> and <code>j<sub>1</sub> &lt; j<sub>2</sub></code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,3,2,4], nums2 = [2,3,1,2,3] <strong>Output:</strong> [0,3] <strong>Explanation:</strong> Consider index 0 and index 3. The value of |nums1[i]-nums1[j]| + |nums2[i]-nums2[j]| is 1, which is the smallest value we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,4,3,2,5], nums2 = [1,4,2,3,5,1] <strong>Output:</strong> [1,4] <strong>Explanation:</strong> Consider index 1 and index 4. The value of |nums1[i]-nums1[j]| + |nums2[i]-nums2[j]| is 1, which is the smallest value we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums1.length, nums2.length &lt;= 10<sup>5</sup></code></li> <li><code>nums1.length == nums2.length</code></li> <li><code>0 &lt;= nums1<sub>i</sub><sub>&nbsp;</sub>&lt;= nums1.length</code></li> <li><code>0 &lt;= nums2<sub>i</sub>&nbsp;&lt;= nums2.length</code></li> </ul>
Geometry; Array; Math; Divide and Conquer; Ordered Set; Sorting
C++
class Solution { public: vector<int> beautifulPair(vector<int>& nums1, vector<int>& nums2) { int n = nums1.size(); unordered_map<long long, vector<int>> pl; for (int i = 0; i < n; ++i) { pl[f(nums1[i], nums2[i])].push_back(i); } vector<tuple<int, int, int>> points; for (int i = 0; i < n; ++i) { long long z = f(nums1[i], nums2[i]); if (pl[z].size() > 1) { return {i, pl[z][1]}; } points.emplace_back(nums1[i], nums2[i], i); } function<tuple<int, int, int>(int, int)> dfs = [&](int l, int r) -> tuple<int, int, int> { if (l >= r) { return {1 << 30, -1, -1}; } int m = (l + r) >> 1; int x = get<0>(points[m]); auto t1 = dfs(l, m); auto t2 = dfs(m + 1, r); if (get<0>(t1) > get<0>(t2) || (get<0>(t1) == get<0>(t2) && (get<1>(t1) > get<1>(t2) || (get<1>(t1) == get<1>(t2) && get<2>(t1) > get<2>(t2))))) { swap(t1, t2); } vector<tuple<int, int, int>> t; for (int i = l; i <= r; ++i) { if (abs(get<0>(points[i]) - x) <= get<0>(t1)) { t.emplace_back(points[i]); } } sort(t.begin(), t.end(), [](const tuple<int, int, int>& a, const tuple<int, int, int>& b) { return get<1>(a) < get<1>(b); }); for (int i = 0; i < t.size(); ++i) { for (int j = i + 1; j < t.size(); ++j) { if (get<1>(t[j]) - get<1>(t[i]) > get<0>(t1)) { break; } int pi = min(get<2>(t[i]), get<2>(t[j])); int pj = max(get<2>(t[i]), get<2>(t[j])); int d = dist(get<0>(t[i]), get<1>(t[i]), get<0>(t[j]), get<1>(t[j])); if (d < get<0>(t1) || (d == get<0>(t1) && (pi < get<1>(t1) || (pi == get<1>(t1) && pj < get<2>(t1))))) { t1 = {d, pi, pj}; } } } return t1; }; sort(points.begin(), points.end()); auto [_, pi, pj] = dfs(0, points.size() - 1); return {pi, pj}; } long long f(int x, int y) { return x * 100000LL + y; } int dist(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); } };
2,613
Beautiful Pairs
Hard
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of the same length. A pair of indices <code>(i,j)</code> is called <strong>beautiful</strong> if<code>|nums1[i] - nums1[j]| + |nums2[i] - nums2[j]|</code> is the smallest amongst all possible indices pairs where <code>i &lt; j</code>.</p> <p>Return <em>the beautiful pair. In the case that there are multiple beautiful pairs, return the lexicographically smallest pair.</em></p> <p>Note that</p> <ul> <li><code>|x|</code> denotes the absolute value of <code>x</code>.</li> <li>A pair of indices <code>(i<sub>1</sub>, j<sub>1</sub>)</code> is lexicographically smaller than <code>(i<sub>2</sub>, j<sub>2</sub>)</code> if <code>i<sub>1</sub> &lt; i<sub>2</sub></code> or <code>i<sub>1</sub> == i<sub>2</sub></code> and <code>j<sub>1</sub> &lt; j<sub>2</sub></code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,3,2,4], nums2 = [2,3,1,2,3] <strong>Output:</strong> [0,3] <strong>Explanation:</strong> Consider index 0 and index 3. The value of |nums1[i]-nums1[j]| + |nums2[i]-nums2[j]| is 1, which is the smallest value we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,4,3,2,5], nums2 = [1,4,2,3,5,1] <strong>Output:</strong> [1,4] <strong>Explanation:</strong> Consider index 1 and index 4. The value of |nums1[i]-nums1[j]| + |nums2[i]-nums2[j]| is 1, which is the smallest value we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums1.length, nums2.length &lt;= 10<sup>5</sup></code></li> <li><code>nums1.length == nums2.length</code></li> <li><code>0 &lt;= nums1<sub>i</sub><sub>&nbsp;</sub>&lt;= nums1.length</code></li> <li><code>0 &lt;= nums2<sub>i</sub>&nbsp;&lt;= nums2.length</code></li> </ul>
Geometry; Array; Math; Divide and Conquer; Ordered Set; Sorting
Go
func beautifulPair(nums1 []int, nums2 []int) []int { n := len(nums1) pl := map[[2]int][]int{} for i := 0; i < n; i++ { k := [2]int{nums1[i], nums2[i]} pl[k] = append(pl[k], i) } points := [][3]int{} for i := 0; i < n; i++ { k := [2]int{nums2[i], nums1[i]} if len(pl[k]) > 1 { return []int{pl[k][0], pl[k][1]} } points = append(points, [3]int{nums1[i], nums2[i], i}) } sort.Slice(points, func(i, j int) bool { return points[i][0] < points[j][0] }) var dfs func(l, r int) [3]int dfs = func(l, r int) [3]int { if l >= r { return [3]int{1 << 30, -1, -1} } m := (l + r) >> 1 x := points[m][0] t1 := dfs(l, m) t2 := dfs(m+1, r) if t1[0] > t2[0] || (t1[0] == t2[0] && (t1[1] > t2[1] || (t1[1] == t2[1] && t1[2] > t2[2]))) { t1 = t2 } t := [][3]int{} for i := l; i <= r; i++ { if abs(points[i][0]-x) <= t1[0] { t = append(t, points[i]) } } sort.Slice(t, func(i, j int) bool { return t[i][1] < t[j][1] }) for i := 0; i < len(t); i++ { for j := i + 1; j < len(t); j++ { if t[j][1]-t[i][1] > t1[0] { break } pi := min(t[i][2], t[j][2]) pj := max(t[i][2], t[j][2]) d := dist(t[i][0], t[i][1], t[j][0], t[j][1]) if d < t1[0] || (d == t1[0] && (pi < t1[1] || (pi == t1[1] && pj < t1[2]))) { t1 = [3]int{d, pi, pj} } } } return t1 } ans := dfs(0, n-1) return []int{ans[1], ans[2]} } func dist(x1, y1, x2, y2 int) int { return abs(x1-x2) + abs(y1-y2) } func abs(x int) int { if x < 0 { return -x } return x }
2,613
Beautiful Pairs
Hard
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of the same length. A pair of indices <code>(i,j)</code> is called <strong>beautiful</strong> if<code>|nums1[i] - nums1[j]| + |nums2[i] - nums2[j]|</code> is the smallest amongst all possible indices pairs where <code>i &lt; j</code>.</p> <p>Return <em>the beautiful pair. In the case that there are multiple beautiful pairs, return the lexicographically smallest pair.</em></p> <p>Note that</p> <ul> <li><code>|x|</code> denotes the absolute value of <code>x</code>.</li> <li>A pair of indices <code>(i<sub>1</sub>, j<sub>1</sub>)</code> is lexicographically smaller than <code>(i<sub>2</sub>, j<sub>2</sub>)</code> if <code>i<sub>1</sub> &lt; i<sub>2</sub></code> or <code>i<sub>1</sub> == i<sub>2</sub></code> and <code>j<sub>1</sub> &lt; j<sub>2</sub></code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,3,2,4], nums2 = [2,3,1,2,3] <strong>Output:</strong> [0,3] <strong>Explanation:</strong> Consider index 0 and index 3. The value of |nums1[i]-nums1[j]| + |nums2[i]-nums2[j]| is 1, which is the smallest value we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,4,3,2,5], nums2 = [1,4,2,3,5,1] <strong>Output:</strong> [1,4] <strong>Explanation:</strong> Consider index 1 and index 4. The value of |nums1[i]-nums1[j]| + |nums2[i]-nums2[j]| is 1, which is the smallest value we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums1.length, nums2.length &lt;= 10<sup>5</sup></code></li> <li><code>nums1.length == nums2.length</code></li> <li><code>0 &lt;= nums1<sub>i</sub><sub>&nbsp;</sub>&lt;= nums1.length</code></li> <li><code>0 &lt;= nums2<sub>i</sub>&nbsp;&lt;= nums2.length</code></li> </ul>
Geometry; Array; Math; Divide and Conquer; Ordered Set; Sorting
Java
class Solution { private List<int[]> points = new ArrayList<>(); public int[] beautifulPair(int[] nums1, int[] nums2) { int n = nums1.length; Map<Long, List<Integer>> pl = new HashMap<>(); for (int i = 0; i < n; ++i) { long z = f(nums1[i], nums2[i]); pl.computeIfAbsent(z, k -> new ArrayList<>()).add(i); } for (int i = 0; i < n; ++i) { long z = f(nums1[i], nums2[i]); if (pl.get(z).size() > 1) { return new int[] {i, pl.get(z).get(1)}; } points.add(new int[] {nums1[i], nums2[i], i}); } points.sort((a, b) -> a[0] - b[0]); int[] ans = dfs(0, points.size() - 1); return new int[] {ans[1], ans[2]}; } private long f(int x, int y) { return x * 100000L + y; } private int dist(int x1, int y1, int x2, int y2) { return Math.abs(x1 - x2) + Math.abs(y1 - y2); } private int[] dfs(int l, int r) { if (l >= r) { return new int[] {1 << 30, -1, -1}; } int m = (l + r) >> 1; int x = points.get(m)[0]; int[] t1 = dfs(l, m); int[] t2 = dfs(m + 1, r); if (t1[0] > t2[0] || (t1[0] == t2[0] && (t1[1] > t2[1] || (t1[1] == t2[1] && t1[2] > t2[2])))) { t1 = t2; } List<int[]> t = new ArrayList<>(); for (int i = l; i <= r; ++i) { if (Math.abs(points.get(i)[0] - x) <= t1[0]) { t.add(points.get(i)); } } t.sort((a, b) -> a[1] - b[1]); for (int i = 0; i < t.size(); ++i) { for (int j = i + 1; j < t.size(); ++j) { if (t.get(j)[1] - t.get(i)[1] > t1[0]) { break; } int pi = Math.min(t.get(i)[2], t.get(j)[2]); int pj = Math.max(t.get(i)[2], t.get(j)[2]); int d = dist(t.get(i)[0], t.get(i)[1], t.get(j)[0], t.get(j)[1]); if (d < t1[0] || (d == t1[0] && (pi < t1[1] || (pi == t1[1] && pj < t1[2])))) { t1 = new int[] {d, pi, pj}; } } } return t1; } }
2,613
Beautiful Pairs
Hard
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of the same length. A pair of indices <code>(i,j)</code> is called <strong>beautiful</strong> if<code>|nums1[i] - nums1[j]| + |nums2[i] - nums2[j]|</code> is the smallest amongst all possible indices pairs where <code>i &lt; j</code>.</p> <p>Return <em>the beautiful pair. In the case that there are multiple beautiful pairs, return the lexicographically smallest pair.</em></p> <p>Note that</p> <ul> <li><code>|x|</code> denotes the absolute value of <code>x</code>.</li> <li>A pair of indices <code>(i<sub>1</sub>, j<sub>1</sub>)</code> is lexicographically smaller than <code>(i<sub>2</sub>, j<sub>2</sub>)</code> if <code>i<sub>1</sub> &lt; i<sub>2</sub></code> or <code>i<sub>1</sub> == i<sub>2</sub></code> and <code>j<sub>1</sub> &lt; j<sub>2</sub></code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,3,2,4], nums2 = [2,3,1,2,3] <strong>Output:</strong> [0,3] <strong>Explanation:</strong> Consider index 0 and index 3. The value of |nums1[i]-nums1[j]| + |nums2[i]-nums2[j]| is 1, which is the smallest value we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,4,3,2,5], nums2 = [1,4,2,3,5,1] <strong>Output:</strong> [1,4] <strong>Explanation:</strong> Consider index 1 and index 4. The value of |nums1[i]-nums1[j]| + |nums2[i]-nums2[j]| is 1, which is the smallest value we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums1.length, nums2.length &lt;= 10<sup>5</sup></code></li> <li><code>nums1.length == nums2.length</code></li> <li><code>0 &lt;= nums1<sub>i</sub><sub>&nbsp;</sub>&lt;= nums1.length</code></li> <li><code>0 &lt;= nums2<sub>i</sub>&nbsp;&lt;= nums2.length</code></li> </ul>
Geometry; Array; Math; Divide and Conquer; Ordered Set; Sorting
Python
class Solution: def beautifulPair(self, nums1: List[int], nums2: List[int]) -> List[int]: def dist(x1: int, y1: int, x2: int, y2: int) -> int: return abs(x1 - x2) + abs(y1 - y2) def dfs(l: int, r: int): if l >= r: return inf, -1, -1 m = (l + r) >> 1 x = points[m][0] d1, pi1, pj1 = dfs(l, m) d2, pi2, pj2 = dfs(m + 1, r) if d1 > d2 or (d1 == d2 and (pi1 > pi2 or (pi1 == pi2 and pj1 > pj2))): d1, pi1, pj1 = d2, pi2, pj2 t = [p for p in points[l : r + 1] if abs(p[0] - x) <= d1] t.sort(key=lambda x: x[1]) for i in range(len(t)): for j in range(i + 1, len(t)): if t[j][1] - t[i][1] > d1: break pi, pj = sorted([t[i][2], t[j][2]]) d = dist(t[i][0], t[i][1], t[j][0], t[j][1]) if d < d1 or (d == d1 and (pi < pi1 or (pi == pi1 and pj < pj1))): d1, pi1, pj1 = d, pi, pj return d1, pi1, pj1 pl = defaultdict(list) for i, (x, y) in enumerate(zip(nums1, nums2)): pl[(x, y)].append(i) points = [] for i, (x, y) in enumerate(zip(nums1, nums2)): if len(pl[(x, y)]) > 1: return [i, pl[(x, y)][1]] points.append((x, y, i)) points.sort() _, pi, pj = dfs(0, len(points) - 1) return [pi, pj]
2,613
Beautiful Pairs
Hard
<p>You are given two <strong>0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code> of the same length. A pair of indices <code>(i,j)</code> is called <strong>beautiful</strong> if<code>|nums1[i] - nums1[j]| + |nums2[i] - nums2[j]|</code> is the smallest amongst all possible indices pairs where <code>i &lt; j</code>.</p> <p>Return <em>the beautiful pair. In the case that there are multiple beautiful pairs, return the lexicographically smallest pair.</em></p> <p>Note that</p> <ul> <li><code>|x|</code> denotes the absolute value of <code>x</code>.</li> <li>A pair of indices <code>(i<sub>1</sub>, j<sub>1</sub>)</code> is lexicographically smaller than <code>(i<sub>2</sub>, j<sub>2</sub>)</code> if <code>i<sub>1</sub> &lt; i<sub>2</sub></code> or <code>i<sub>1</sub> == i<sub>2</sub></code> and <code>j<sub>1</sub> &lt; j<sub>2</sub></code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,3,2,4], nums2 = [2,3,1,2,3] <strong>Output:</strong> [0,3] <strong>Explanation:</strong> Consider index 0 and index 3. The value of |nums1[i]-nums1[j]| + |nums2[i]-nums2[j]| is 1, which is the smallest value we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,4,3,2,5], nums2 = [1,4,2,3,5,1] <strong>Output:</strong> [1,4] <strong>Explanation:</strong> Consider index 1 and index 4. The value of |nums1[i]-nums1[j]| + |nums2[i]-nums2[j]| is 1, which is the smallest value we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums1.length, nums2.length &lt;= 10<sup>5</sup></code></li> <li><code>nums1.length == nums2.length</code></li> <li><code>0 &lt;= nums1<sub>i</sub><sub>&nbsp;</sub>&lt;= nums1.length</code></li> <li><code>0 &lt;= nums2<sub>i</sub>&nbsp;&lt;= nums2.length</code></li> </ul>
Geometry; Array; Math; Divide and Conquer; Ordered Set; Sorting
TypeScript
function beautifulPair(nums1: number[], nums2: number[]): number[] { const pl: Map<number, number[]> = new Map(); const n = nums1.length; for (let i = 0; i < n; ++i) { const z = f(nums1[i], nums2[i]); if (!pl.has(z)) { pl.set(z, []); } pl.get(z)!.push(i); } const points: number[][] = []; for (let i = 0; i < n; ++i) { const z = f(nums1[i], nums2[i]); if (pl.get(z)!.length > 1) { return [i, pl.get(z)![1]]; } points.push([nums1[i], nums2[i], i]); } points.sort((a, b) => a[0] - b[0]); const dfs = (l: number, r: number): number[] => { if (l >= r) { return [1 << 30, -1, -1]; } const m = (l + r) >> 1; const x = points[m][0]; let t1 = dfs(l, m); let t2 = dfs(m + 1, r); if ( t1[0] > t2[0] || (t1[0] == t2[0] && (t1[1] > t2[1] || (t1[1] == t2[1] && t1[2] > t2[2]))) ) { t1 = t2; } const t: number[][] = []; for (let i = l; i <= r; ++i) { if (Math.abs(points[i][0] - x) <= t1[0]) { t.push(points[i]); } } t.sort((a, b) => a[1] - b[1]); for (let i = 0; i < t.length; ++i) { for (let j = i + 1; j < t.length; ++j) { if (t[j][1] - t[i][1] > t1[0]) { break; } const pi = Math.min(t[i][2], t[j][2]); const pj = Math.max(t[i][2], t[j][2]); const d = dist(t[i][0], t[i][1], t[j][0], t[j][1]); if (d < t1[0] || (d == t1[0] && (pi < t1[1] || (pi == t1[1] && pj < t1[2])))) { t1 = [d, pi, pj]; } } } return t1; }; return dfs(0, n - 1).slice(1); } function dist(x1: number, y1: number, x2: number, y2: number): number { return Math.abs(x1 - x2) + Math.abs(y1 - y2); } function f(x: number, y: number): number { return x * 100000 + y; }
2,614
Prime In Diagonal
Easy
<p>You are given a 0-indexed two-dimensional integer array <code>nums</code>.</p> <p>Return <em>the largest <strong>prime</strong> number that lies on at least one of the <b>diagonals</b> of </em><code>nums</code>. In case, no prime is present on any of the diagonals, return<em> 0.</em></p> <p>Note that:</p> <ul> <li>An integer is <strong>prime</strong> if it is greater than <code>1</code> and has no positive integer divisors other than <code>1</code> and itself.</li> <li>An integer <code>val</code> is on one of the <strong>diagonals</strong> of <code>nums</code> if there exists an integer <code>i</code> for which <code>nums[i][i] = val</code> or an <code>i</code> for which <code>nums[i][nums.length - i - 1] = val</code>.</li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2614.Prime%20In%20Diagonal/images/screenshot-2023-03-06-at-45648-pm.png" style="width: 181px; height: 121px;" /></p> <p>In the above diagram, one diagonal is <strong>[1,5,9]</strong> and another diagonal is<strong> [3,5,7]</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,6,7],[9,10,11]] <strong>Output:</strong> 11 <strong>Explanation:</strong> The numbers 1, 3, 6, 9, and 11 are the only numbers present on at least one of the diagonals. Since 11 is the largest prime, we return 11. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,17,7],[9,11,10]] <strong>Output:</strong> 17 <strong>Explanation:</strong> The numbers 1, 3, 9, 10, and 17 are all present on at least one of the diagonals. 17 is the largest prime, so we return 17. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 300</code></li> <li><code>nums.length == nums<sub>i</sub>.length</code></li> <li><code>1 &lt;= nums<span style="font-size: 10.8333px;">[i][j]</span>&nbsp;&lt;= 4*10<sup>6</sup></code></li> </ul>
Array; Math; Matrix; Number Theory
C++
class Solution { public: int diagonalPrime(vector<vector<int>>& nums) { int n = nums.size(); int ans = 0; for (int i = 0; i < n; ++i) { if (isPrime(nums[i][i])) { ans = max(ans, nums[i][i]); } if (isPrime(nums[i][n - i - 1])) { ans = max(ans, nums[i][n - i - 1]); } } return ans; } bool isPrime(int x) { if (x < 2) { return false; } for (int i = 2; i <= x / i; ++i) { if (x % i == 0) { return false; } } return true; } };
2,614
Prime In Diagonal
Easy
<p>You are given a 0-indexed two-dimensional integer array <code>nums</code>.</p> <p>Return <em>the largest <strong>prime</strong> number that lies on at least one of the <b>diagonals</b> of </em><code>nums</code>. In case, no prime is present on any of the diagonals, return<em> 0.</em></p> <p>Note that:</p> <ul> <li>An integer is <strong>prime</strong> if it is greater than <code>1</code> and has no positive integer divisors other than <code>1</code> and itself.</li> <li>An integer <code>val</code> is on one of the <strong>diagonals</strong> of <code>nums</code> if there exists an integer <code>i</code> for which <code>nums[i][i] = val</code> or an <code>i</code> for which <code>nums[i][nums.length - i - 1] = val</code>.</li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2614.Prime%20In%20Diagonal/images/screenshot-2023-03-06-at-45648-pm.png" style="width: 181px; height: 121px;" /></p> <p>In the above diagram, one diagonal is <strong>[1,5,9]</strong> and another diagonal is<strong> [3,5,7]</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,6,7],[9,10,11]] <strong>Output:</strong> 11 <strong>Explanation:</strong> The numbers 1, 3, 6, 9, and 11 are the only numbers present on at least one of the diagonals. Since 11 is the largest prime, we return 11. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,17,7],[9,11,10]] <strong>Output:</strong> 17 <strong>Explanation:</strong> The numbers 1, 3, 9, 10, and 17 are all present on at least one of the diagonals. 17 is the largest prime, so we return 17. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 300</code></li> <li><code>nums.length == nums<sub>i</sub>.length</code></li> <li><code>1 &lt;= nums<span style="font-size: 10.8333px;">[i][j]</span>&nbsp;&lt;= 4*10<sup>6</sup></code></li> </ul>
Array; Math; Matrix; Number Theory
Go
func diagonalPrime(nums [][]int) (ans int) { n := len(nums) for i, row := range nums { if isPrime(row[i]) { ans = max(ans, row[i]) } if isPrime(row[n-i-1]) { ans = max(ans, row[n-i-1]) } } return } func isPrime(x int) bool { if x < 2 { return false } for i := 2; i <= x/i; i++ { if x%i == 0 { return false } } return true }
2,614
Prime In Diagonal
Easy
<p>You are given a 0-indexed two-dimensional integer array <code>nums</code>.</p> <p>Return <em>the largest <strong>prime</strong> number that lies on at least one of the <b>diagonals</b> of </em><code>nums</code>. In case, no prime is present on any of the diagonals, return<em> 0.</em></p> <p>Note that:</p> <ul> <li>An integer is <strong>prime</strong> if it is greater than <code>1</code> and has no positive integer divisors other than <code>1</code> and itself.</li> <li>An integer <code>val</code> is on one of the <strong>diagonals</strong> of <code>nums</code> if there exists an integer <code>i</code> for which <code>nums[i][i] = val</code> or an <code>i</code> for which <code>nums[i][nums.length - i - 1] = val</code>.</li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2614.Prime%20In%20Diagonal/images/screenshot-2023-03-06-at-45648-pm.png" style="width: 181px; height: 121px;" /></p> <p>In the above diagram, one diagonal is <strong>[1,5,9]</strong> and another diagonal is<strong> [3,5,7]</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,6,7],[9,10,11]] <strong>Output:</strong> 11 <strong>Explanation:</strong> The numbers 1, 3, 6, 9, and 11 are the only numbers present on at least one of the diagonals. Since 11 is the largest prime, we return 11. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,17,7],[9,11,10]] <strong>Output:</strong> 17 <strong>Explanation:</strong> The numbers 1, 3, 9, 10, and 17 are all present on at least one of the diagonals. 17 is the largest prime, so we return 17. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 300</code></li> <li><code>nums.length == nums<sub>i</sub>.length</code></li> <li><code>1 &lt;= nums<span style="font-size: 10.8333px;">[i][j]</span>&nbsp;&lt;= 4*10<sup>6</sup></code></li> </ul>
Array; Math; Matrix; Number Theory
Java
class Solution { public int diagonalPrime(int[][] nums) { int n = nums.length; int ans = 0; for (int i = 0; i < n; ++i) { if (isPrime(nums[i][i])) { ans = Math.max(ans, nums[i][i]); } if (isPrime(nums[i][n - i - 1])) { ans = Math.max(ans, nums[i][n - i - 1]); } } return ans; } private boolean isPrime(int x) { if (x < 2) { return false; } for (int i = 2; i <= x / i; ++i) { if (x % i == 0) { return false; } } return true; } }
2,614
Prime In Diagonal
Easy
<p>You are given a 0-indexed two-dimensional integer array <code>nums</code>.</p> <p>Return <em>the largest <strong>prime</strong> number that lies on at least one of the <b>diagonals</b> of </em><code>nums</code>. In case, no prime is present on any of the diagonals, return<em> 0.</em></p> <p>Note that:</p> <ul> <li>An integer is <strong>prime</strong> if it is greater than <code>1</code> and has no positive integer divisors other than <code>1</code> and itself.</li> <li>An integer <code>val</code> is on one of the <strong>diagonals</strong> of <code>nums</code> if there exists an integer <code>i</code> for which <code>nums[i][i] = val</code> or an <code>i</code> for which <code>nums[i][nums.length - i - 1] = val</code>.</li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2614.Prime%20In%20Diagonal/images/screenshot-2023-03-06-at-45648-pm.png" style="width: 181px; height: 121px;" /></p> <p>In the above diagram, one diagonal is <strong>[1,5,9]</strong> and another diagonal is<strong> [3,5,7]</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,6,7],[9,10,11]] <strong>Output:</strong> 11 <strong>Explanation:</strong> The numbers 1, 3, 6, 9, and 11 are the only numbers present on at least one of the diagonals. Since 11 is the largest prime, we return 11. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,17,7],[9,11,10]] <strong>Output:</strong> 17 <strong>Explanation:</strong> The numbers 1, 3, 9, 10, and 17 are all present on at least one of the diagonals. 17 is the largest prime, so we return 17. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 300</code></li> <li><code>nums.length == nums<sub>i</sub>.length</code></li> <li><code>1 &lt;= nums<span style="font-size: 10.8333px;">[i][j]</span>&nbsp;&lt;= 4*10<sup>6</sup></code></li> </ul>
Array; Math; Matrix; Number Theory
JavaScript
/** * @param {number[][]} nums * @return {number} */ var diagonalPrime = function (nums) { let ans = 0; const n = nums.length; for (let i = 0; i < n; i++) { if (isPrime(nums[i][i])) { ans = Math.max(ans, nums[i][i]); } if (isPrime(nums[i][n - i - 1])) { ans = Math.max(ans, nums[i][n - i - 1]); } } return ans; }; function isPrime(x) { if (x < 2) { return false; } for (let i = 2; i * i <= x; i++) { if (x % i === 0) { return false; } } return true; }
2,614
Prime In Diagonal
Easy
<p>You are given a 0-indexed two-dimensional integer array <code>nums</code>.</p> <p>Return <em>the largest <strong>prime</strong> number that lies on at least one of the <b>diagonals</b> of </em><code>nums</code>. In case, no prime is present on any of the diagonals, return<em> 0.</em></p> <p>Note that:</p> <ul> <li>An integer is <strong>prime</strong> if it is greater than <code>1</code> and has no positive integer divisors other than <code>1</code> and itself.</li> <li>An integer <code>val</code> is on one of the <strong>diagonals</strong> of <code>nums</code> if there exists an integer <code>i</code> for which <code>nums[i][i] = val</code> or an <code>i</code> for which <code>nums[i][nums.length - i - 1] = val</code>.</li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2614.Prime%20In%20Diagonal/images/screenshot-2023-03-06-at-45648-pm.png" style="width: 181px; height: 121px;" /></p> <p>In the above diagram, one diagonal is <strong>[1,5,9]</strong> and another diagonal is<strong> [3,5,7]</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,6,7],[9,10,11]] <strong>Output:</strong> 11 <strong>Explanation:</strong> The numbers 1, 3, 6, 9, and 11 are the only numbers present on at least one of the diagonals. Since 11 is the largest prime, we return 11. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,17,7],[9,11,10]] <strong>Output:</strong> 17 <strong>Explanation:</strong> The numbers 1, 3, 9, 10, and 17 are all present on at least one of the diagonals. 17 is the largest prime, so we return 17. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 300</code></li> <li><code>nums.length == nums<sub>i</sub>.length</code></li> <li><code>1 &lt;= nums<span style="font-size: 10.8333px;">[i][j]</span>&nbsp;&lt;= 4*10<sup>6</sup></code></li> </ul>
Array; Math; Matrix; Number Theory
Python
class Solution: def diagonalPrime(self, nums: List[List[int]]) -> int: def is_prime(x: int) -> bool: if x < 2: return False return all(x % i for i in range(2, int(sqrt(x)) + 1)) n = len(nums) ans = 0 for i, row in enumerate(nums): if is_prime(row[i]): ans = max(ans, row[i]) if is_prime(row[n - i - 1]): ans = max(ans, row[n - i - 1]) return ans
2,614
Prime In Diagonal
Easy
<p>You are given a 0-indexed two-dimensional integer array <code>nums</code>.</p> <p>Return <em>the largest <strong>prime</strong> number that lies on at least one of the <b>diagonals</b> of </em><code>nums</code>. In case, no prime is present on any of the diagonals, return<em> 0.</em></p> <p>Note that:</p> <ul> <li>An integer is <strong>prime</strong> if it is greater than <code>1</code> and has no positive integer divisors other than <code>1</code> and itself.</li> <li>An integer <code>val</code> is on one of the <strong>diagonals</strong> of <code>nums</code> if there exists an integer <code>i</code> for which <code>nums[i][i] = val</code> or an <code>i</code> for which <code>nums[i][nums.length - i - 1] = val</code>.</li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2614.Prime%20In%20Diagonal/images/screenshot-2023-03-06-at-45648-pm.png" style="width: 181px; height: 121px;" /></p> <p>In the above diagram, one diagonal is <strong>[1,5,9]</strong> and another diagonal is<strong> [3,5,7]</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,6,7],[9,10,11]] <strong>Output:</strong> 11 <strong>Explanation:</strong> The numbers 1, 3, 6, 9, and 11 are the only numbers present on at least one of the diagonals. Since 11 is the largest prime, we return 11. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,17,7],[9,11,10]] <strong>Output:</strong> 17 <strong>Explanation:</strong> The numbers 1, 3, 9, 10, and 17 are all present on at least one of the diagonals. 17 is the largest prime, so we return 17. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 300</code></li> <li><code>nums.length == nums<sub>i</sub>.length</code></li> <li><code>1 &lt;= nums<span style="font-size: 10.8333px;">[i][j]</span>&nbsp;&lt;= 4*10<sup>6</sup></code></li> </ul>
Array; Math; Matrix; Number Theory
Rust
impl Solution { pub fn diagonal_prime(nums: Vec<Vec<i32>>) -> i32 { let mut ans = 0; let n = nums.len(); for (i, row) in nums.iter().enumerate() { if Self::is_prime(row[i]) && row[i] > ans { ans = row[i]; } if Self::is_prime(row[n - i - 1]) && row[n - i - 1] > ans { ans = row[n - i - 1]; } } ans } fn is_prime(n: i32) -> bool { if n < 2 { return false; } let upper = (n as f64).sqrt() as i32; for i in 2..=upper { if n % i == 0 { return false; } } true } }
2,614
Prime In Diagonal
Easy
<p>You are given a 0-indexed two-dimensional integer array <code>nums</code>.</p> <p>Return <em>the largest <strong>prime</strong> number that lies on at least one of the <b>diagonals</b> of </em><code>nums</code>. In case, no prime is present on any of the diagonals, return<em> 0.</em></p> <p>Note that:</p> <ul> <li>An integer is <strong>prime</strong> if it is greater than <code>1</code> and has no positive integer divisors other than <code>1</code> and itself.</li> <li>An integer <code>val</code> is on one of the <strong>diagonals</strong> of <code>nums</code> if there exists an integer <code>i</code> for which <code>nums[i][i] = val</code> or an <code>i</code> for which <code>nums[i][nums.length - i - 1] = val</code>.</li> </ul> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2614.Prime%20In%20Diagonal/images/screenshot-2023-03-06-at-45648-pm.png" style="width: 181px; height: 121px;" /></p> <p>In the above diagram, one diagonal is <strong>[1,5,9]</strong> and another diagonal is<strong> [3,5,7]</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,6,7],[9,10,11]] <strong>Output:</strong> 11 <strong>Explanation:</strong> The numbers 1, 3, 6, 9, and 11 are the only numbers present on at least one of the diagonals. Since 11 is the largest prime, we return 11. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2,3],[5,17,7],[9,11,10]] <strong>Output:</strong> 17 <strong>Explanation:</strong> The numbers 1, 3, 9, 10, and 17 are all present on at least one of the diagonals. 17 is the largest prime, so we return 17. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 300</code></li> <li><code>nums.length == nums<sub>i</sub>.length</code></li> <li><code>1 &lt;= nums<span style="font-size: 10.8333px;">[i][j]</span>&nbsp;&lt;= 4*10<sup>6</sup></code></li> </ul>
Array; Math; Matrix; Number Theory
TypeScript
function diagonalPrime(nums: number[][]): number { const n = nums.length; let ans = 0; for (let i = 0; i < n; ++i) { if (isPrime(nums[i][i])) { ans = Math.max(ans, nums[i][i]); } if (isPrime(nums[i][n - i - 1])) { ans = Math.max(ans, nums[i][n - i - 1]); } } return ans; } function isPrime(x: number): boolean { if (x < 2) { return false; } for (let i = 2; i <= Math.floor(x / i); ++i) { if (x % i === 0) { return false; } } return true; }
2,615
Sum of Distances
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. There exists an array <code>arr</code> of length <code>nums.length</code>, where <code>arr[i]</code> is the sum of <code>|i - j|</code> over all <code>j</code> such that <code>nums[j] == nums[i]</code> and <code>j != i</code>. If there is no such <code>j</code>, set <code>arr[i]</code> to be <code>0</code>.</p> <p>Return <em>the array </em><code>arr</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,1,2] <strong>Output:</strong> [5,0,3,4,0] <strong>Explanation:</strong> When i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = |0 - 2| + |0 - 3| = 5. When i = 1, arr[1] = 0 because there is no other index with value 3. When i = 2, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = |2 - 0| + |2 - 3| = 3. When i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = |3 - 0| + |3 - 2| = 4. When i = 4, arr[4] = 0 because there is no other index with value 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,5,3] <strong>Output:</strong> [0,0,0] <strong>Explanation:</strong> Since each element in nums is distinct, arr[i] = 0 for all i. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/intervals-between-identical-elements/description/" target="_blank"> 2121: Intervals Between Identical Elements.</a></p>
Array; Hash Table; Prefix Sum
C++
class Solution { public: vector<long long> distance(vector<int>& nums) { int n = nums.size(); vector<long long> ans(n); unordered_map<int, vector<int>> d; for (int i = 0; i < n; ++i) { d[nums[i]].push_back(i); } for (auto& [_, idx] : d) { int m = idx.size(); long long left = 0; long long right = -1LL * m * idx[0]; for (int i : idx) { right += i; } for (int i = 0; i < m; ++i) { ans[idx[i]] = left + right; if (i + 1 < m) { left += (idx[i + 1] - idx[i]) * (i + 1); right -= (idx[i + 1] - idx[i]) * (m - i - 1); } } } return ans; } };
2,615
Sum of Distances
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. There exists an array <code>arr</code> of length <code>nums.length</code>, where <code>arr[i]</code> is the sum of <code>|i - j|</code> over all <code>j</code> such that <code>nums[j] == nums[i]</code> and <code>j != i</code>. If there is no such <code>j</code>, set <code>arr[i]</code> to be <code>0</code>.</p> <p>Return <em>the array </em><code>arr</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,1,2] <strong>Output:</strong> [5,0,3,4,0] <strong>Explanation:</strong> When i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = |0 - 2| + |0 - 3| = 5. When i = 1, arr[1] = 0 because there is no other index with value 3. When i = 2, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = |2 - 0| + |2 - 3| = 3. When i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = |3 - 0| + |3 - 2| = 4. When i = 4, arr[4] = 0 because there is no other index with value 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,5,3] <strong>Output:</strong> [0,0,0] <strong>Explanation:</strong> Since each element in nums is distinct, arr[i] = 0 for all i. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/intervals-between-identical-elements/description/" target="_blank"> 2121: Intervals Between Identical Elements.</a></p>
Array; Hash Table; Prefix Sum
Go
func distance(nums []int) []int64 { n := len(nums) ans := make([]int64, n) d := map[int][]int{} for i, x := range nums { d[x] = append(d[x], i) } for _, idx := range d { m := len(idx) left, right := 0, -m*idx[0] for _, i := range idx { right += i } for i := range idx { ans[idx[i]] = int64(left + right) if i+1 < m { left += (idx[i+1] - idx[i]) * (i + 1) right -= (idx[i+1] - idx[i]) * (m - i - 1) } } } return ans }
2,615
Sum of Distances
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. There exists an array <code>arr</code> of length <code>nums.length</code>, where <code>arr[i]</code> is the sum of <code>|i - j|</code> over all <code>j</code> such that <code>nums[j] == nums[i]</code> and <code>j != i</code>. If there is no such <code>j</code>, set <code>arr[i]</code> to be <code>0</code>.</p> <p>Return <em>the array </em><code>arr</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,1,2] <strong>Output:</strong> [5,0,3,4,0] <strong>Explanation:</strong> When i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = |0 - 2| + |0 - 3| = 5. When i = 1, arr[1] = 0 because there is no other index with value 3. When i = 2, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = |2 - 0| + |2 - 3| = 3. When i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = |3 - 0| + |3 - 2| = 4. When i = 4, arr[4] = 0 because there is no other index with value 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,5,3] <strong>Output:</strong> [0,0,0] <strong>Explanation:</strong> Since each element in nums is distinct, arr[i] = 0 for all i. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/intervals-between-identical-elements/description/" target="_blank"> 2121: Intervals Between Identical Elements.</a></p>
Array; Hash Table; Prefix Sum
Java
class Solution { public long[] distance(int[] nums) { int n = nums.length; long[] ans = new long[n]; Map<Integer, List<Integer>> d = new HashMap<>(); for (int i = 0; i < n; ++i) { d.computeIfAbsent(nums[i], k -> new ArrayList<>()).add(i); } for (var idx : d.values()) { int m = idx.size(); long left = 0; long right = -1L * m * idx.get(0); for (int i : idx) { right += i; } for (int i = 0; i < m; ++i) { ans[idx.get(i)] = left + right; if (i + 1 < m) { left += (idx.get(i + 1) - idx.get(i)) * (i + 1L); right -= (idx.get(i + 1) - idx.get(i)) * (m - i - 1L); } } } return ans; } }
2,615
Sum of Distances
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. There exists an array <code>arr</code> of length <code>nums.length</code>, where <code>arr[i]</code> is the sum of <code>|i - j|</code> over all <code>j</code> such that <code>nums[j] == nums[i]</code> and <code>j != i</code>. If there is no such <code>j</code>, set <code>arr[i]</code> to be <code>0</code>.</p> <p>Return <em>the array </em><code>arr</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,1,1,2] <strong>Output:</strong> [5,0,3,4,0] <strong>Explanation:</strong> When i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = |0 - 2| + |0 - 3| = 5. When i = 1, arr[1] = 0 because there is no other index with value 3. When i = 2, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = |2 - 0| + |2 - 3| = 3. When i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = |3 - 0| + |3 - 2| = 4. When i = 4, arr[4] = 0 because there is no other index with value 2. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,5,3] <strong>Output:</strong> [0,0,0] <strong>Explanation:</strong> Since each element in nums is distinct, arr[i] = 0 for all i. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/intervals-between-identical-elements/description/" target="_blank"> 2121: Intervals Between Identical Elements.</a></p>
Array; Hash Table; Prefix Sum
Python
class Solution: def distance(self, nums: List[int]) -> List[int]: d = defaultdict(list) for i, x in enumerate(nums): d[x].append(i) ans = [0] * len(nums) for idx in d.values(): left, right = 0, sum(idx) - len(idx) * idx[0] for i in range(len(idx)): ans[idx[i]] = left + right if i + 1 < len(idx): left += (idx[i + 1] - idx[i]) * (i + 1) right -= (idx[i + 1] - idx[i]) * (len(idx) - i - 1) return ans
2,616
Minimize the Maximum Difference of Pairs
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>p</code>. Find <code>p</code> pairs of indices of <code>nums</code> such that the <strong>maximum</strong> difference amongst all the pairs is <strong>minimized</strong>. Also, ensure no index appears more than once amongst the <code>p</code> pairs.</p> <p>Note that for a pair of elements at the index <code>i</code> and <code>j</code>, the difference of this pair is <code>|nums[i] - nums[j]|</code>, where <code>|x|</code> represents the <strong>absolute</strong> <strong>value</strong> of <code>x</code>.</p> <p>Return <em>the <strong>minimum</strong> <strong>maximum</strong> difference among all </em><code>p</code> <em>pairs.</em> We define the maximum of an empty set to be zero.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,7,1,3], p = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,1,2], p = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= p &lt;= (nums.length)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Sorting
C++
class Solution { public: int minimizeMax(vector<int>& nums, int p) { sort(nums.begin(), nums.end()); int n = nums.size(); int l = 0, r = nums[n - 1] - nums[0] + 1; auto check = [&](int diff) -> bool { int cnt = 0; for (int i = 0; i < n - 1; ++i) { if (nums[i + 1] - nums[i] <= diff) { ++cnt; ++i; } } return cnt >= p; }; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } };
2,616
Minimize the Maximum Difference of Pairs
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>p</code>. Find <code>p</code> pairs of indices of <code>nums</code> such that the <strong>maximum</strong> difference amongst all the pairs is <strong>minimized</strong>. Also, ensure no index appears more than once amongst the <code>p</code> pairs.</p> <p>Note that for a pair of elements at the index <code>i</code> and <code>j</code>, the difference of this pair is <code>|nums[i] - nums[j]|</code>, where <code>|x|</code> represents the <strong>absolute</strong> <strong>value</strong> of <code>x</code>.</p> <p>Return <em>the <strong>minimum</strong> <strong>maximum</strong> difference among all </em><code>p</code> <em>pairs.</em> We define the maximum of an empty set to be zero.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,7,1,3], p = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,1,2], p = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= p &lt;= (nums.length)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Sorting
C#
public class Solution { public int MinimizeMax(int[] nums, int p) { Array.Sort(nums); int n = nums.Length; int l = 0, r = nums[n - 1] - nums[0] + 1; bool check(int diff) { int cnt = 0; for (int i = 0; i < n - 1; ++i) { if (nums[i + 1] - nums[i] <= diff) { ++cnt; ++i; } } return cnt >= p; } while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } }
2,616
Minimize the Maximum Difference of Pairs
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>p</code>. Find <code>p</code> pairs of indices of <code>nums</code> such that the <strong>maximum</strong> difference amongst all the pairs is <strong>minimized</strong>. Also, ensure no index appears more than once amongst the <code>p</code> pairs.</p> <p>Note that for a pair of elements at the index <code>i</code> and <code>j</code>, the difference of this pair is <code>|nums[i] - nums[j]|</code>, where <code>|x|</code> represents the <strong>absolute</strong> <strong>value</strong> of <code>x</code>.</p> <p>Return <em>the <strong>minimum</strong> <strong>maximum</strong> difference among all </em><code>p</code> <em>pairs.</em> We define the maximum of an empty set to be zero.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,7,1,3], p = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,1,2], p = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= p &lt;= (nums.length)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Sorting
Go
func minimizeMax(nums []int, p int) int { sort.Ints(nums) n := len(nums) r := nums[n-1] - nums[0] + 1 return sort.Search(r, func(diff int) bool { cnt := 0 for i := 0; i < n-1; i++ { if nums[i+1]-nums[i] <= diff { cnt++ i++ } } return cnt >= p }) }
2,616
Minimize the Maximum Difference of Pairs
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>p</code>. Find <code>p</code> pairs of indices of <code>nums</code> such that the <strong>maximum</strong> difference amongst all the pairs is <strong>minimized</strong>. Also, ensure no index appears more than once amongst the <code>p</code> pairs.</p> <p>Note that for a pair of elements at the index <code>i</code> and <code>j</code>, the difference of this pair is <code>|nums[i] - nums[j]|</code>, where <code>|x|</code> represents the <strong>absolute</strong> <strong>value</strong> of <code>x</code>.</p> <p>Return <em>the <strong>minimum</strong> <strong>maximum</strong> difference among all </em><code>p</code> <em>pairs.</em> We define the maximum of an empty set to be zero.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,7,1,3], p = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,1,2], p = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= p &lt;= (nums.length)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Sorting
Java
class Solution { public int minimizeMax(int[] nums, int p) { Arrays.sort(nums); int n = nums.length; int l = 0, r = nums[n - 1] - nums[0] + 1; while (l < r) { int mid = (l + r) >>> 1; if (count(nums, mid) >= p) { r = mid; } else { l = mid + 1; } } return l; } private int count(int[] nums, int diff) { int cnt = 0; for (int i = 0; i < nums.length - 1; ++i) { if (nums[i + 1] - nums[i] <= diff) { ++cnt; ++i; } } return cnt; } }
2,616
Minimize the Maximum Difference of Pairs
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>p</code>. Find <code>p</code> pairs of indices of <code>nums</code> such that the <strong>maximum</strong> difference amongst all the pairs is <strong>minimized</strong>. Also, ensure no index appears more than once amongst the <code>p</code> pairs.</p> <p>Note that for a pair of elements at the index <code>i</code> and <code>j</code>, the difference of this pair is <code>|nums[i] - nums[j]|</code>, where <code>|x|</code> represents the <strong>absolute</strong> <strong>value</strong> of <code>x</code>.</p> <p>Return <em>the <strong>minimum</strong> <strong>maximum</strong> difference among all </em><code>p</code> <em>pairs.</em> We define the maximum of an empty set to be zero.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,7,1,3], p = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,1,2], p = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= p &lt;= (nums.length)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Sorting
PHP
class Solution { /** * @param Integer[] $nums * @param Integer $p * @return Integer */ function minimizeMax($nums, $p) { sort($nums); $n = count($nums); $l = 0; $r = $nums[$n - 1] - $nums[0] + 1; $check = function ($diff) use ($nums, $n, $p) { $cnt = 0; for ($i = 0; $i < $n - 1; ++$i) { if ($nums[$i + 1] - $nums[$i] <= $diff) { ++$cnt; ++$i; } } return $cnt >= $p; }; while ($l < $r) { $mid = intdiv($l + $r, 2); if ($check($mid)) { $r = $mid; } else { $l = $mid + 1; } } return $l; } }
2,616
Minimize the Maximum Difference of Pairs
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>p</code>. Find <code>p</code> pairs of indices of <code>nums</code> such that the <strong>maximum</strong> difference amongst all the pairs is <strong>minimized</strong>. Also, ensure no index appears more than once amongst the <code>p</code> pairs.</p> <p>Note that for a pair of elements at the index <code>i</code> and <code>j</code>, the difference of this pair is <code>|nums[i] - nums[j]|</code>, where <code>|x|</code> represents the <strong>absolute</strong> <strong>value</strong> of <code>x</code>.</p> <p>Return <em>the <strong>minimum</strong> <strong>maximum</strong> difference among all </em><code>p</code> <em>pairs.</em> We define the maximum of an empty set to be zero.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,7,1,3], p = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,1,2], p = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= p &lt;= (nums.length)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Sorting
Python
class Solution: def minimizeMax(self, nums: List[int], p: int) -> int: def check(diff: int) -> bool: cnt = i = 0 while i < len(nums) - 1: if nums[i + 1] - nums[i] <= diff: cnt += 1 i += 2 else: i += 1 return cnt >= p nums.sort() return bisect_left(range(nums[-1] - nums[0] + 1), True, key=check)
2,616
Minimize the Maximum Difference of Pairs
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>p</code>. Find <code>p</code> pairs of indices of <code>nums</code> such that the <strong>maximum</strong> difference amongst all the pairs is <strong>minimized</strong>. Also, ensure no index appears more than once amongst the <code>p</code> pairs.</p> <p>Note that for a pair of elements at the index <code>i</code> and <code>j</code>, the difference of this pair is <code>|nums[i] - nums[j]|</code>, where <code>|x|</code> represents the <strong>absolute</strong> <strong>value</strong> of <code>x</code>.</p> <p>Return <em>the <strong>minimum</strong> <strong>maximum</strong> difference among all </em><code>p</code> <em>pairs.</em> We define the maximum of an empty set to be zero.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,7,1,3], p = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,1,2], p = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= p &lt;= (nums.length)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Sorting
Rust
impl Solution { pub fn minimize_max(mut nums: Vec<i32>, p: i32) -> i32 { nums.sort(); let n = nums.len(); let (mut l, mut r) = (0, nums[n - 1] - nums[0] + 1); let check = |diff: i32| -> bool { let mut cnt = 0; let mut i = 0; while i < n - 1 { if nums[i + 1] - nums[i] <= diff { cnt += 1; i += 2; } else { i += 1; } } cnt >= p }; while l < r { let mid = (l + r) / 2; if check(mid) { r = mid; } else { l = mid + 1; } } l } }
2,616
Minimize the Maximum Difference of Pairs
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>p</code>. Find <code>p</code> pairs of indices of <code>nums</code> such that the <strong>maximum</strong> difference amongst all the pairs is <strong>minimized</strong>. Also, ensure no index appears more than once amongst the <code>p</code> pairs.</p> <p>Note that for a pair of elements at the index <code>i</code> and <code>j</code>, the difference of this pair is <code>|nums[i] - nums[j]|</code>, where <code>|x|</code> represents the <strong>absolute</strong> <strong>value</strong> of <code>x</code>.</p> <p>Return <em>the <strong>minimum</strong> <strong>maximum</strong> difference among all </em><code>p</code> <em>pairs.</em> We define the maximum of an empty set to be zero.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,7,1,3], p = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,1,2], p = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= p &lt;= (nums.length)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Sorting
Swift
class Solution { func minimizeMax(_ nums: [Int], _ p: Int) -> Int { var nums = nums.sorted() let n = nums.count var l = 0 var r = nums[n - 1] - nums[0] + 1 func check(_ diff: Int) -> Bool { var cnt = 0 var i = 0 while i < n - 1 { if nums[i + 1] - nums[i] <= diff { cnt += 1 i += 2 } else { i += 1 } } return cnt >= p } while l < r { let mid = (l + r) >> 1 if check(mid) { r = mid } else { l = mid + 1 } } return l } }
2,616
Minimize the Maximum Difference of Pairs
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>p</code>. Find <code>p</code> pairs of indices of <code>nums</code> such that the <strong>maximum</strong> difference amongst all the pairs is <strong>minimized</strong>. Also, ensure no index appears more than once amongst the <code>p</code> pairs.</p> <p>Note that for a pair of elements at the index <code>i</code> and <code>j</code>, the difference of this pair is <code>|nums[i] - nums[j]|</code>, where <code>|x|</code> represents the <strong>absolute</strong> <strong>value</strong> of <code>x</code>.</p> <p>Return <em>the <strong>minimum</strong> <strong>maximum</strong> difference among all </em><code>p</code> <em>pairs.</em> We define the maximum of an empty set to be zero.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [10,1,2,7,1,3], p = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [4,2,1,2], p = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= p &lt;= (nums.length)/2</code></li> </ul>
Greedy; Array; Binary Search; Dynamic Programming; Sorting
TypeScript
function minimizeMax(nums: number[], p: number): number { nums.sort((a, b) => a - b); const n = nums.length; let l = 0, r = nums[n - 1] - nums[0] + 1; const check = (diff: number): boolean => { let cnt = 0; for (let i = 0; i < n - 1; ++i) { if (nums[i + 1] - nums[i] <= diff) { ++cnt; ++i; } } return cnt >= p; }; while (l < r) { const mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; }
2,617
Minimum Number of Visited Cells in a Grid
Hard
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>grid</code>. Your initial position is at the <strong>top-left</strong> cell <code>(0, 0)</code>.</p> <p>Starting from the cell <code>(i, j)</code>, you can move to one of the following cells:</p> <ul> <li>Cells <code>(i, k)</code> with <code>j &lt; k &lt;= grid[i][j] + j</code> (rightward movement), or</li> <li>Cells <code>(k, j)</code> with <code>i &lt; k &lt;= grid[i][j] + i</code> (downward movement).</li> </ul> <p>Return <em>the minimum number of cells you need to visit to reach the <strong>bottom-right</strong> cell</em> <code>(m - 1, n - 1)</code>. If there is no valid path, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2617.Minimum%20Number%20of%20Visited%20Cells%20in%20a%20Grid/images/ex1.png" style="width: 271px; height: 171px;" /> <pre> <strong>Input:</strong> grid = [[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The image above shows one of the paths that visits exactly 4 cells. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2617.Minimum%20Number%20of%20Visited%20Cells%20in%20a%20Grid/images/ex2.png" style="width: 271px; height: 171px;" /> <pre> <strong>Input:</strong> grid = [[3,4,2,1],[4,2,1,1],[2,1,1,0],[3,4,1,0]] <strong>Output:</strong> 3 <strong>Explanation: </strong>The image above shows one of the paths that visits exactly 3 cells. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2617.Minimum%20Number%20of%20Visited%20Cells%20in%20a%20Grid/images/ex3.png" style="width: 181px; height: 81px;" /> <pre> <strong>Input:</strong> grid = [[2,1,0],[1,0,0]] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proven that no path exists. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= grid[i][j] &lt; m * n</code></li> <li><code>grid[m - 1][n - 1] == 0</code></li> </ul>
Stack; Breadth-First Search; Union Find; Array; Dynamic Programming; Matrix; Monotonic Stack; Heap (Priority Queue)
C++
class Solution { public: int minimumVisitedCells(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); vector<vector<int>> dist(m, vector<int>(n, -1)); using pii = pair<int, int>; priority_queue<pii, vector<pii>, greater<pii>> row[m]; priority_queue<pii, vector<pii>, greater<pii>> col[n]; dist[0][0] = 1; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { while (!row[i].empty() && grid[i][row[i].top().second] + row[i].top().second < j) { row[i].pop(); } if (!row[i].empty() && (dist[i][j] == -1 || row[i].top().first + 1 < dist[i][j])) { dist[i][j] = row[i].top().first + 1; } while (!col[j].empty() && grid[col[j].top().second][j] + col[j].top().second < i) { col[j].pop(); } if (!col[j].empty() && (dist[i][j] == -1 || col[j].top().first + 1 < dist[i][j])) { dist[i][j] = col[j].top().first + 1; } if (dist[i][j] != -1) { row[i].emplace(dist[i][j], j); col[j].emplace(dist[i][j], i); } } } return dist[m - 1][n - 1]; } };
2,617
Minimum Number of Visited Cells in a Grid
Hard
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>grid</code>. Your initial position is at the <strong>top-left</strong> cell <code>(0, 0)</code>.</p> <p>Starting from the cell <code>(i, j)</code>, you can move to one of the following cells:</p> <ul> <li>Cells <code>(i, k)</code> with <code>j &lt; k &lt;= grid[i][j] + j</code> (rightward movement), or</li> <li>Cells <code>(k, j)</code> with <code>i &lt; k &lt;= grid[i][j] + i</code> (downward movement).</li> </ul> <p>Return <em>the minimum number of cells you need to visit to reach the <strong>bottom-right</strong> cell</em> <code>(m - 1, n - 1)</code>. If there is no valid path, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2617.Minimum%20Number%20of%20Visited%20Cells%20in%20a%20Grid/images/ex1.png" style="width: 271px; height: 171px;" /> <pre> <strong>Input:</strong> grid = [[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The image above shows one of the paths that visits exactly 4 cells. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2617.Minimum%20Number%20of%20Visited%20Cells%20in%20a%20Grid/images/ex2.png" style="width: 271px; height: 171px;" /> <pre> <strong>Input:</strong> grid = [[3,4,2,1],[4,2,1,1],[2,1,1,0],[3,4,1,0]] <strong>Output:</strong> 3 <strong>Explanation: </strong>The image above shows one of the paths that visits exactly 3 cells. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2617.Minimum%20Number%20of%20Visited%20Cells%20in%20a%20Grid/images/ex3.png" style="width: 181px; height: 81px;" /> <pre> <strong>Input:</strong> grid = [[2,1,0],[1,0,0]] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proven that no path exists. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= grid[i][j] &lt; m * n</code></li> <li><code>grid[m - 1][n - 1] == 0</code></li> </ul>
Stack; Breadth-First Search; Union Find; Array; Dynamic Programming; Matrix; Monotonic Stack; Heap (Priority Queue)
Go
func minimumVisitedCells(grid [][]int) int { m, n := len(grid), len(grid[0]) dist := make([][]int, m) row := make([]hp, m) col := make([]hp, n) for i := range dist { dist[i] = make([]int, n) for j := range dist[i] { dist[i][j] = -1 } } dist[0][0] = 1 for i := 0; i < m; i++ { for j := 0; j < n; j++ { for len(row[i]) > 0 && grid[i][row[i][0].second]+row[i][0].second < j { heap.Pop(&row[i]) } if len(row[i]) > 0 && (dist[i][j] == -1 || row[i][0].first+1 < dist[i][j]) { dist[i][j] = row[i][0].first + 1 } for len(col[j]) > 0 && grid[col[j][0].second][j]+col[j][0].second < i { heap.Pop(&col[j]) } if len(col[j]) > 0 && (dist[i][j] == -1 || col[j][0].first+1 < dist[i][j]) { dist[i][j] = col[j][0].first + 1 } if dist[i][j] != -1 { heap.Push(&row[i], pair{dist[i][j], j}) heap.Push(&col[j], pair{dist[i][j], i}) } } } return dist[m-1][n-1] } type pair struct { first int second int } type hp []pair func (a hp) Len() int { return len(a) } func (a hp) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a hp) Less(i, j int) bool { return a[i].first < a[j].first || (a[i].first == a[j].first && a[i].second < a[j].second) } func (a *hp) Push(x any) { *a = append(*a, x.(pair)) } func (a *hp) Pop() any { l := len(*a); t := (*a)[l-1]; *a = (*a)[:l-1]; return t }
2,617
Minimum Number of Visited Cells in a Grid
Hard
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>grid</code>. Your initial position is at the <strong>top-left</strong> cell <code>(0, 0)</code>.</p> <p>Starting from the cell <code>(i, j)</code>, you can move to one of the following cells:</p> <ul> <li>Cells <code>(i, k)</code> with <code>j &lt; k &lt;= grid[i][j] + j</code> (rightward movement), or</li> <li>Cells <code>(k, j)</code> with <code>i &lt; k &lt;= grid[i][j] + i</code> (downward movement).</li> </ul> <p>Return <em>the minimum number of cells you need to visit to reach the <strong>bottom-right</strong> cell</em> <code>(m - 1, n - 1)</code>. If there is no valid path, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2617.Minimum%20Number%20of%20Visited%20Cells%20in%20a%20Grid/images/ex1.png" style="width: 271px; height: 171px;" /> <pre> <strong>Input:</strong> grid = [[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The image above shows one of the paths that visits exactly 4 cells. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2617.Minimum%20Number%20of%20Visited%20Cells%20in%20a%20Grid/images/ex2.png" style="width: 271px; height: 171px;" /> <pre> <strong>Input:</strong> grid = [[3,4,2,1],[4,2,1,1],[2,1,1,0],[3,4,1,0]] <strong>Output:</strong> 3 <strong>Explanation: </strong>The image above shows one of the paths that visits exactly 3 cells. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2617.Minimum%20Number%20of%20Visited%20Cells%20in%20a%20Grid/images/ex3.png" style="width: 181px; height: 81px;" /> <pre> <strong>Input:</strong> grid = [[2,1,0],[1,0,0]] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proven that no path exists. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= grid[i][j] &lt; m * n</code></li> <li><code>grid[m - 1][n - 1] == 0</code></li> </ul>
Stack; Breadth-First Search; Union Find; Array; Dynamic Programming; Matrix; Monotonic Stack; Heap (Priority Queue)
Java
class Solution { public int minimumVisitedCells(int[][] grid) { int m = grid.length, n = grid[0].length; int[][] dist = new int[m][n]; PriorityQueue<int[]>[] row = new PriorityQueue[m]; PriorityQueue<int[]>[] col = new PriorityQueue[n]; for (int i = 0; i < m; ++i) { Arrays.fill(dist[i], -1); row[i] = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); } for (int i = 0; i < n; ++i) { col[i] = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); } dist[0][0] = 1; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { while (!row[i].isEmpty() && grid[i][row[i].peek()[1]] + row[i].peek()[1] < j) { row[i].poll(); } if (!row[i].isEmpty() && (dist[i][j] == -1 || row[i].peek()[0] + 1 < dist[i][j])) { dist[i][j] = row[i].peek()[0] + 1; } while (!col[j].isEmpty() && grid[col[j].peek()[1]][j] + col[j].peek()[1] < i) { col[j].poll(); } if (!col[j].isEmpty() && (dist[i][j] == -1 || col[j].peek()[0] + 1 < dist[i][j])) { dist[i][j] = col[j].peek()[0] + 1; } if (dist[i][j] != -1) { row[i].offer(new int[] {dist[i][j], j}); col[j].offer(new int[] {dist[i][j], i}); } } } return dist[m - 1][n - 1]; } }
2,617
Minimum Number of Visited Cells in a Grid
Hard
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> integer matrix <code>grid</code>. Your initial position is at the <strong>top-left</strong> cell <code>(0, 0)</code>.</p> <p>Starting from the cell <code>(i, j)</code>, you can move to one of the following cells:</p> <ul> <li>Cells <code>(i, k)</code> with <code>j &lt; k &lt;= grid[i][j] + j</code> (rightward movement), or</li> <li>Cells <code>(k, j)</code> with <code>i &lt; k &lt;= grid[i][j] + i</code> (downward movement).</li> </ul> <p>Return <em>the minimum number of cells you need to visit to reach the <strong>bottom-right</strong> cell</em> <code>(m - 1, n - 1)</code>. If there is no valid path, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2617.Minimum%20Number%20of%20Visited%20Cells%20in%20a%20Grid/images/ex1.png" style="width: 271px; height: 171px;" /> <pre> <strong>Input:</strong> grid = [[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]] <strong>Output:</strong> 4 <strong>Explanation:</strong> The image above shows one of the paths that visits exactly 4 cells. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2617.Minimum%20Number%20of%20Visited%20Cells%20in%20a%20Grid/images/ex2.png" style="width: 271px; height: 171px;" /> <pre> <strong>Input:</strong> grid = [[3,4,2,1],[4,2,1,1],[2,1,1,0],[3,4,1,0]] <strong>Output:</strong> 3 <strong>Explanation: </strong>The image above shows one of the paths that visits exactly 3 cells. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2617.Minimum%20Number%20of%20Visited%20Cells%20in%20a%20Grid/images/ex3.png" style="width: 181px; height: 81px;" /> <pre> <strong>Input:</strong> grid = [[2,1,0],[1,0,0]] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be proven that no path exists. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= grid[i][j] &lt; m * n</code></li> <li><code>grid[m - 1][n - 1] == 0</code></li> </ul>
Stack; Breadth-First Search; Union Find; Array; Dynamic Programming; Matrix; Monotonic Stack; Heap (Priority Queue)
Python
class Solution: def minimumVisitedCells(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dist = [[-1] * n for _ in range(m)] dist[0][0] = 1 row = [[] for _ in range(m)] col = [[] for _ in range(n)] for i in range(m): for j in range(n): while row[i] and grid[i][row[i][0][1]] + row[i][0][1] < j: heappop(row[i]) if row[i] and (dist[i][j] == -1 or dist[i][j] > row[i][0][0] + 1): dist[i][j] = row[i][0][0] + 1 while col[j] and grid[col[j][0][1]][j] + col[j][0][1] < i: heappop(col[j]) if col[j] and (dist[i][j] == -1 or dist[i][j] > col[j][0][0] + 1): dist[i][j] = col[j][0][0] + 1 if dist[i][j] != -1: heappush(row[i], (dist[i][j], j)) heappush(col[j], (dist[i][j], i)) return dist[-1][-1]