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,679
Sum in a Matrix
Medium
<p>You are given a <strong>0-indexed</strong> 2D integer array <code>nums</code>. Initially, your score is <code>0</code>. Perform the following operations until the matrix becomes empty:</p> <ol> <li>From each row in the matrix, select the largest number and remove it. In the case of a tie, it does not matter which number is chosen.</li> <li>Identify the highest number amongst all those removed in step 1. Add that number to your <strong>score</strong>.</li> </ol> <p>Return <em>the final <strong>score</strong>.</em></p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[7,2,1],[6,4,2],[6,5,3],[3,2,1]] <strong>Output:</strong> 15 <strong>Explanation:</strong> In the first operation, we remove 7, 6, 6, and 3. We then add 7 to our score. Next, we remove 2, 4, 5, and 2. We add 5 to our score. Lastly, we remove 1, 2, 3, and 1. We add 3 to our score. Thus, our final score is 7 + 5 + 3 = 15. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> We remove 1 and add it to the answer. We return 1.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 300</code></li> <li><code>1 &lt;= nums[i].length &lt;= 500</code></li> <li><code>0 &lt;= nums[i][j] &lt;= 10<sup>3</sup></code></li> </ul>
Array; Matrix; Sorting; Simulation; Heap (Priority Queue)
Python
class Solution: def matrixSum(self, nums: List[List[int]]) -> int: for row in nums: row.sort() return sum(map(max, zip(*nums)))
2,679
Sum in a Matrix
Medium
<p>You are given a <strong>0-indexed</strong> 2D integer array <code>nums</code>. Initially, your score is <code>0</code>. Perform the following operations until the matrix becomes empty:</p> <ol> <li>From each row in the matrix, select the largest number and remove it. In the case of a tie, it does not matter which number is chosen.</li> <li>Identify the highest number amongst all those removed in step 1. Add that number to your <strong>score</strong>.</li> </ol> <p>Return <em>the final <strong>score</strong>.</em></p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[7,2,1],[6,4,2],[6,5,3],[3,2,1]] <strong>Output:</strong> 15 <strong>Explanation:</strong> In the first operation, we remove 7, 6, 6, and 3. We then add 7 to our score. Next, we remove 2, 4, 5, and 2. We add 5 to our score. Lastly, we remove 1, 2, 3, and 1. We add 3 to our score. Thus, our final score is 7 + 5 + 3 = 15. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> We remove 1 and add it to the answer. We return 1.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 300</code></li> <li><code>1 &lt;= nums[i].length &lt;= 500</code></li> <li><code>0 &lt;= nums[i][j] &lt;= 10<sup>3</sup></code></li> </ul>
Array; Matrix; Sorting; Simulation; Heap (Priority Queue)
Rust
impl Solution { pub fn matrix_sum(mut nums: Vec<Vec<i32>>) -> i32 { for row in &mut nums { row.sort(); } (0..nums[0].len()) .map(|col| nums.iter().map(|row| row[col]).max().unwrap()) .sum() } }
2,679
Sum in a Matrix
Medium
<p>You are given a <strong>0-indexed</strong> 2D integer array <code>nums</code>. Initially, your score is <code>0</code>. Perform the following operations until the matrix becomes empty:</p> <ol> <li>From each row in the matrix, select the largest number and remove it. In the case of a tie, it does not matter which number is chosen.</li> <li>Identify the highest number amongst all those removed in step 1. Add that number to your <strong>score</strong>.</li> </ol> <p>Return <em>the final <strong>score</strong>.</em></p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[7,2,1],[6,4,2],[6,5,3],[3,2,1]] <strong>Output:</strong> 15 <strong>Explanation:</strong> In the first operation, we remove 7, 6, 6, and 3. We then add 7 to our score. Next, we remove 2, 4, 5, and 2. We add 5 to our score. Lastly, we remove 1, 2, 3, and 1. We add 3 to our score. Thus, our final score is 7 + 5 + 3 = 15. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> We remove 1 and add it to the answer. We return 1.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 300</code></li> <li><code>1 &lt;= nums[i].length &lt;= 500</code></li> <li><code>0 &lt;= nums[i][j] &lt;= 10<sup>3</sup></code></li> </ul>
Array; Matrix; Sorting; Simulation; Heap (Priority Queue)
TypeScript
function matrixSum(nums: number[][]): number { for (const row of nums) { row.sort((a, b) => a - b); } let ans = 0; for (let j = 0; j < nums[0].length; ++j) { let mx = 0; for (const row of nums) { mx = Math.max(mx, row[j]); } ans += mx; } return ans; }
2,680
Maximum OR
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> and an integer <code>k</code>. In an operation, you can choose an element and multiply it by <code>2</code>.</p> <p>Return <em>the maximum possible value of </em><code>nums[0] | nums[1] | ... | nums[n - 1]</code> <em>that can be obtained after applying the operation on nums at most </em><code>k</code><em> times</em>.</p> <p>Note that <code>a | b</code> denotes the <strong>bitwise or</strong> between two integers <code>a</code> and <code>b</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,9], k = 1 <strong>Output:</strong> 30 <strong>Explanation:</strong> If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [8,1,2], k = 2 <strong>Output:</strong> 35 <strong>Explanation:</strong> If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32|1|2 = 35. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 15</code></li> </ul>
Greedy; Bit Manipulation; Array; Prefix Sum
C++
class Solution { public: long long maximumOr(vector<int>& nums, int k) { int n = nums.size(); long long suf[n + 1]; memset(suf, 0, sizeof(suf)); for (int i = n - 1; i >= 0; --i) { suf[i] = suf[i + 1] | nums[i]; } long long ans = 0, pre = 0; for (int i = 0; i < n; ++i) { ans = max(ans, pre | (1LL * nums[i] << k) | suf[i + 1]); pre |= nums[i]; } return ans; } };
2,680
Maximum OR
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> and an integer <code>k</code>. In an operation, you can choose an element and multiply it by <code>2</code>.</p> <p>Return <em>the maximum possible value of </em><code>nums[0] | nums[1] | ... | nums[n - 1]</code> <em>that can be obtained after applying the operation on nums at most </em><code>k</code><em> times</em>.</p> <p>Note that <code>a | b</code> denotes the <strong>bitwise or</strong> between two integers <code>a</code> and <code>b</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,9], k = 1 <strong>Output:</strong> 30 <strong>Explanation:</strong> If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [8,1,2], k = 2 <strong>Output:</strong> 35 <strong>Explanation:</strong> If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32|1|2 = 35. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 15</code></li> </ul>
Greedy; Bit Manipulation; Array; Prefix Sum
Go
func maximumOr(nums []int, k int) int64 { n := len(nums) suf := make([]int, n+1) for i := n - 1; i >= 0; i-- { suf[i] = suf[i+1] | nums[i] } ans, pre := 0, 0 for i, x := range nums { ans = max(ans, pre|(nums[i]<<k)|suf[i+1]) pre |= x } return int64(ans) }
2,680
Maximum OR
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> and an integer <code>k</code>. In an operation, you can choose an element and multiply it by <code>2</code>.</p> <p>Return <em>the maximum possible value of </em><code>nums[0] | nums[1] | ... | nums[n - 1]</code> <em>that can be obtained after applying the operation on nums at most </em><code>k</code><em> times</em>.</p> <p>Note that <code>a | b</code> denotes the <strong>bitwise or</strong> between two integers <code>a</code> and <code>b</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,9], k = 1 <strong>Output:</strong> 30 <strong>Explanation:</strong> If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [8,1,2], k = 2 <strong>Output:</strong> 35 <strong>Explanation:</strong> If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32|1|2 = 35. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 15</code></li> </ul>
Greedy; Bit Manipulation; Array; Prefix Sum
Java
class Solution { public long maximumOr(int[] nums, int k) { int n = nums.length; long[] suf = new long[n + 1]; for (int i = n - 1; i >= 0; --i) { suf[i] = suf[i + 1] | nums[i]; } long ans = 0, pre = 0; for (int i = 0; i < n; ++i) { ans = Math.max(ans, pre | (1L * nums[i] << k) | suf[i + 1]); pre |= nums[i]; } return ans; } }
2,680
Maximum OR
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> and an integer <code>k</code>. In an operation, you can choose an element and multiply it by <code>2</code>.</p> <p>Return <em>the maximum possible value of </em><code>nums[0] | nums[1] | ... | nums[n - 1]</code> <em>that can be obtained after applying the operation on nums at most </em><code>k</code><em> times</em>.</p> <p>Note that <code>a | b</code> denotes the <strong>bitwise or</strong> between two integers <code>a</code> and <code>b</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,9], k = 1 <strong>Output:</strong> 30 <strong>Explanation:</strong> If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [8,1,2], k = 2 <strong>Output:</strong> 35 <strong>Explanation:</strong> If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32|1|2 = 35. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 15</code></li> </ul>
Greedy; Bit Manipulation; Array; Prefix Sum
Python
class Solution: def maximumOr(self, nums: List[int], k: int) -> int: n = len(nums) suf = [0] * (n + 1) for i in range(n - 1, -1, -1): suf[i] = suf[i + 1] | nums[i] ans = pre = 0 for i, x in enumerate(nums): ans = max(ans, pre | (x << k) | suf[i + 1]) pre |= x return ans
2,680
Maximum OR
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> and an integer <code>k</code>. In an operation, you can choose an element and multiply it by <code>2</code>.</p> <p>Return <em>the maximum possible value of </em><code>nums[0] | nums[1] | ... | nums[n - 1]</code> <em>that can be obtained after applying the operation on nums at most </em><code>k</code><em> times</em>.</p> <p>Note that <code>a | b</code> denotes the <strong>bitwise or</strong> between two integers <code>a</code> and <code>b</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,9], k = 1 <strong>Output:</strong> 30 <strong>Explanation:</strong> If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [8,1,2], k = 2 <strong>Output:</strong> 35 <strong>Explanation:</strong> If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32|1|2 = 35. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 15</code></li> </ul>
Greedy; Bit Manipulation; Array; Prefix Sum
Rust
impl Solution { pub fn maximum_or(nums: Vec<i32>, k: i32) -> i64 { let n = nums.len(); let mut suf = vec![0; n + 1]; for i in (0..n).rev() { suf[i] = suf[i + 1] | (nums[i] as i64); } let mut ans = 0i64; let mut pre = 0i64; let k64 = k as i64; for i in 0..n { ans = ans.max(pre | ((nums[i] as i64) << k64) | suf[i + 1]); pre |= nums[i] as i64; } ans } }
2,680
Maximum OR
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> of length <code>n</code> and an integer <code>k</code>. In an operation, you can choose an element and multiply it by <code>2</code>.</p> <p>Return <em>the maximum possible value of </em><code>nums[0] | nums[1] | ... | nums[n - 1]</code> <em>that can be obtained after applying the operation on nums at most </em><code>k</code><em> times</em>.</p> <p>Note that <code>a | b</code> denotes the <strong>bitwise or</strong> between two integers <code>a</code> and <code>b</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [12,9], k = 1 <strong>Output:</strong> 30 <strong>Explanation:</strong> If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [8,1,2], k = 2 <strong>Output:</strong> 35 <strong>Explanation:</strong> If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32|1|2 = 35. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= k &lt;= 15</code></li> </ul>
Greedy; Bit Manipulation; Array; Prefix Sum
TypeScript
function maximumOr(nums: number[], k: number): number { const n = nums.length; const suf: bigint[] = Array(n + 1).fill(0n); for (let i = n - 1; i >= 0; i--) { suf[i] = suf[i + 1] | BigInt(nums[i]); } let [ans, pre] = [0, 0n]; for (let i = 0; i < n; i++) { ans = Math.max(Number(ans), Number(pre | (BigInt(nums[i]) << BigInt(k)) | suf[i + 1])); pre |= BigInt(nums[i]); } return ans; }
2,681
Power of Heroes
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the strength of some heroes. The<b> power</b> of a group of heroes is defined as follows:</p> <ul> <li>Let <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, ... ,<code>i<sub>k</sub></code> be the indices of the heroes in a group. Then, the power of this group is <code>max(nums[i<sub>0</sub>], nums[i<sub>1</sub>], ... ,nums[i<sub>k</sub>])<sup>2</sup> * min(nums[i<sub>0</sub>], nums[i<sub>1</sub>], ... ,nums[i<sub>k</sub>])</code>.</li> </ul> <p>Return <em>the sum of the <strong>power</strong> of all <strong>non-empty</strong> groups of heroes possible.</em> Since the sum could be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4] <strong>Output:</strong> 141 <strong>Explanation:</strong> 1<sup>st</sup>&nbsp;group: [2] has power = 2<sup>2</sup>&nbsp;* 2 = 8. 2<sup>nd</sup>&nbsp;group: [1] has power = 1<sup>2</sup> * 1 = 1. 3<sup>rd</sup>&nbsp;group: [4] has power = 4<sup>2</sup> * 4 = 64. 4<sup>th</sup>&nbsp;group: [2,1] has power = 2<sup>2</sup> * 1 = 4. 5<sup>th</sup>&nbsp;group: [2,4] has power = 4<sup>2</sup> * 2 = 32. 6<sup>th</sup>&nbsp;group: [1,4] has power = 4<sup>2</sup> * 1 = 16. ​​​​​​​7<sup>th</sup>&nbsp;group: [2,1,4] has power = 4<sup>2</sup>​​​​​​​ * 1 = 16. The sum of powers of all groups is 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1] <strong>Output:</strong> 7 <strong>Explanation:</strong> A total of 7 groups are possible, and the power of each group will be 1. Therefore, the sum of the powers of all groups is 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Math; Dynamic Programming; Prefix Sum; Sorting
C++
class Solution { public: int sumOfPower(vector<int>& nums) { const int mod = 1e9 + 7; sort(nums.rbegin(), nums.rend()); long long ans = 0, p = 0; for (long long x : nums) { ans = (ans + (x * x % mod) * x) % mod; ans = (ans + x * p % mod) % mod; p = (p * 2 + x * x % mod) % mod; } return ans; } };
2,681
Power of Heroes
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the strength of some heroes. The<b> power</b> of a group of heroes is defined as follows:</p> <ul> <li>Let <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, ... ,<code>i<sub>k</sub></code> be the indices of the heroes in a group. Then, the power of this group is <code>max(nums[i<sub>0</sub>], nums[i<sub>1</sub>], ... ,nums[i<sub>k</sub>])<sup>2</sup> * min(nums[i<sub>0</sub>], nums[i<sub>1</sub>], ... ,nums[i<sub>k</sub>])</code>.</li> </ul> <p>Return <em>the sum of the <strong>power</strong> of all <strong>non-empty</strong> groups of heroes possible.</em> Since the sum could be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4] <strong>Output:</strong> 141 <strong>Explanation:</strong> 1<sup>st</sup>&nbsp;group: [2] has power = 2<sup>2</sup>&nbsp;* 2 = 8. 2<sup>nd</sup>&nbsp;group: [1] has power = 1<sup>2</sup> * 1 = 1. 3<sup>rd</sup>&nbsp;group: [4] has power = 4<sup>2</sup> * 4 = 64. 4<sup>th</sup>&nbsp;group: [2,1] has power = 2<sup>2</sup> * 1 = 4. 5<sup>th</sup>&nbsp;group: [2,4] has power = 4<sup>2</sup> * 2 = 32. 6<sup>th</sup>&nbsp;group: [1,4] has power = 4<sup>2</sup> * 1 = 16. ​​​​​​​7<sup>th</sup>&nbsp;group: [2,1,4] has power = 4<sup>2</sup>​​​​​​​ * 1 = 16. The sum of powers of all groups is 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1] <strong>Output:</strong> 7 <strong>Explanation:</strong> A total of 7 groups are possible, and the power of each group will be 1. Therefore, the sum of the powers of all groups is 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Math; Dynamic Programming; Prefix Sum; Sorting
Go
func sumOfPower(nums []int) (ans int) { const mod = 1e9 + 7 sort.Ints(nums) p := 0 for i := len(nums) - 1; i >= 0; i-- { x := nums[i] ans = (ans + (x*x%mod)*x) % mod ans = (ans + x*p%mod) % mod p = (p*2 + x*x%mod) % mod } return }
2,681
Power of Heroes
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the strength of some heroes. The<b> power</b> of a group of heroes is defined as follows:</p> <ul> <li>Let <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, ... ,<code>i<sub>k</sub></code> be the indices of the heroes in a group. Then, the power of this group is <code>max(nums[i<sub>0</sub>], nums[i<sub>1</sub>], ... ,nums[i<sub>k</sub>])<sup>2</sup> * min(nums[i<sub>0</sub>], nums[i<sub>1</sub>], ... ,nums[i<sub>k</sub>])</code>.</li> </ul> <p>Return <em>the sum of the <strong>power</strong> of all <strong>non-empty</strong> groups of heroes possible.</em> Since the sum could be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4] <strong>Output:</strong> 141 <strong>Explanation:</strong> 1<sup>st</sup>&nbsp;group: [2] has power = 2<sup>2</sup>&nbsp;* 2 = 8. 2<sup>nd</sup>&nbsp;group: [1] has power = 1<sup>2</sup> * 1 = 1. 3<sup>rd</sup>&nbsp;group: [4] has power = 4<sup>2</sup> * 4 = 64. 4<sup>th</sup>&nbsp;group: [2,1] has power = 2<sup>2</sup> * 1 = 4. 5<sup>th</sup>&nbsp;group: [2,4] has power = 4<sup>2</sup> * 2 = 32. 6<sup>th</sup>&nbsp;group: [1,4] has power = 4<sup>2</sup> * 1 = 16. ​​​​​​​7<sup>th</sup>&nbsp;group: [2,1,4] has power = 4<sup>2</sup>​​​​​​​ * 1 = 16. The sum of powers of all groups is 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1] <strong>Output:</strong> 7 <strong>Explanation:</strong> A total of 7 groups are possible, and the power of each group will be 1. Therefore, the sum of the powers of all groups is 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Math; Dynamic Programming; Prefix Sum; Sorting
Java
class Solution { public int sumOfPower(int[] nums) { final int mod = (int) 1e9 + 7; Arrays.sort(nums); long ans = 0, p = 0; for (int i = nums.length - 1; i >= 0; --i) { long x = nums[i]; ans = (ans + (x * x % mod) * x) % mod; ans = (ans + x * p % mod) % mod; p = (p * 2 + x * x % mod) % mod; } return (int) ans; } }
2,681
Power of Heroes
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the strength of some heroes. The<b> power</b> of a group of heroes is defined as follows:</p> <ul> <li>Let <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, ... ,<code>i<sub>k</sub></code> be the indices of the heroes in a group. Then, the power of this group is <code>max(nums[i<sub>0</sub>], nums[i<sub>1</sub>], ... ,nums[i<sub>k</sub>])<sup>2</sup> * min(nums[i<sub>0</sub>], nums[i<sub>1</sub>], ... ,nums[i<sub>k</sub>])</code>.</li> </ul> <p>Return <em>the sum of the <strong>power</strong> of all <strong>non-empty</strong> groups of heroes possible.</em> Since the sum could be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4] <strong>Output:</strong> 141 <strong>Explanation:</strong> 1<sup>st</sup>&nbsp;group: [2] has power = 2<sup>2</sup>&nbsp;* 2 = 8. 2<sup>nd</sup>&nbsp;group: [1] has power = 1<sup>2</sup> * 1 = 1. 3<sup>rd</sup>&nbsp;group: [4] has power = 4<sup>2</sup> * 4 = 64. 4<sup>th</sup>&nbsp;group: [2,1] has power = 2<sup>2</sup> * 1 = 4. 5<sup>th</sup>&nbsp;group: [2,4] has power = 4<sup>2</sup> * 2 = 32. 6<sup>th</sup>&nbsp;group: [1,4] has power = 4<sup>2</sup> * 1 = 16. ​​​​​​​7<sup>th</sup>&nbsp;group: [2,1,4] has power = 4<sup>2</sup>​​​​​​​ * 1 = 16. The sum of powers of all groups is 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1] <strong>Output:</strong> 7 <strong>Explanation:</strong> A total of 7 groups are possible, and the power of each group will be 1. Therefore, the sum of the powers of all groups is 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Math; Dynamic Programming; Prefix Sum; Sorting
Python
class Solution: def sumOfPower(self, nums: List[int]) -> int: mod = 10**9 + 7 nums.sort() ans = 0 p = 0 for x in nums[::-1]: ans = (ans + (x * x % mod) * x) % mod ans = (ans + x * p) % mod p = (p * 2 + x * x) % mod return ans
2,681
Power of Heroes
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the strength of some heroes. The<b> power</b> of a group of heroes is defined as follows:</p> <ul> <li>Let <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, ... ,<code>i<sub>k</sub></code> be the indices of the heroes in a group. Then, the power of this group is <code>max(nums[i<sub>0</sub>], nums[i<sub>1</sub>], ... ,nums[i<sub>k</sub>])<sup>2</sup> * min(nums[i<sub>0</sub>], nums[i<sub>1</sub>], ... ,nums[i<sub>k</sub>])</code>.</li> </ul> <p>Return <em>the sum of the <strong>power</strong> of all <strong>non-empty</strong> groups of heroes possible.</em> Since the sum could be very large, return it <strong>modulo</strong> <code>10<sup>9 </sup>+ 7</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,1,4] <strong>Output:</strong> 141 <strong>Explanation:</strong> 1<sup>st</sup>&nbsp;group: [2] has power = 2<sup>2</sup>&nbsp;* 2 = 8. 2<sup>nd</sup>&nbsp;group: [1] has power = 1<sup>2</sup> * 1 = 1. 3<sup>rd</sup>&nbsp;group: [4] has power = 4<sup>2</sup> * 4 = 64. 4<sup>th</sup>&nbsp;group: [2,1] has power = 2<sup>2</sup> * 1 = 4. 5<sup>th</sup>&nbsp;group: [2,4] has power = 4<sup>2</sup> * 2 = 32. 6<sup>th</sup>&nbsp;group: [1,4] has power = 4<sup>2</sup> * 1 = 16. ​​​​​​​7<sup>th</sup>&nbsp;group: [2,1,4] has power = 4<sup>2</sup>​​​​​​​ * 1 = 16. The sum of powers of all groups is 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1] <strong>Output:</strong> 7 <strong>Explanation:</strong> A total of 7 groups are possible, and the power of each group will be 1. Therefore, the sum of the powers of all groups is 7. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Math; Dynamic Programming; Prefix Sum; Sorting
TypeScript
function sumOfPower(nums: number[]): number { const mod = 10 ** 9 + 7; nums.sort((a, b) => a - b); let ans = 0; let p = 0; for (let i = nums.length - 1; i >= 0; --i) { const x = BigInt(nums[i]); ans = (ans + Number((x * x * x) % BigInt(mod))) % mod; ans = (ans + Number((x * BigInt(p)) % BigInt(mod))) % mod; p = Number((BigInt(p) * 2n + x * x) % BigInt(mod)); } return ans; }
2,682
Find the Losers of the Circular Game
Easy
<p>There are <code>n</code> friends that are playing a game. The friends are sitting in a circle and are numbered from <code>1</code> to <code>n</code> in <strong>clockwise order</strong>. More formally, moving clockwise from the <code>i<sup>th</sup></code> friend brings you to the <code>(i+1)<sup>th</sup></code> friend for <code>1 &lt;= i &lt; n</code>, and moving clockwise from the <code>n<sup>th</sup></code> friend brings you to the <code>1<sup>st</sup></code> friend.</p> <p>The rules of the game are as follows:</p> <p><code>1<sup>st</sup></code> friend receives the ball.</p> <ul> <li>After that, <code>1<sup>st</sup></code> friend passes it to the friend who is <code>k</code> steps away from them in the <strong>clockwise</strong> direction.</li> <li>After that, the friend who receives the ball should pass it to the friend who is <code>2 * k</code> steps away from them in the <strong>clockwise</strong> direction.</li> <li>After that, the friend who receives the ball should pass it to the friend who is <code>3 * k</code> steps away from them in the <strong>clockwise</strong> direction, and so on and so forth.</li> </ul> <p>In other words, on the <code>i<sup>th</sup></code> turn, the friend holding the ball should pass it to the friend who is <code>i * k</code> steps away from them in the <strong>clockwise</strong> direction.</p> <p>The game is finished when some friend receives the ball for the second time.</p> <p>The <strong>losers</strong> of the game are friends who did not receive the ball in the entire game.</p> <p>Given the number of friends, <code>n</code>, and an integer <code>k</code>, return <em>the array answer, which contains the losers of the game in the <strong>ascending</strong> order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, k = 2 <strong>Output:</strong> [4,5] <strong>Explanation:</strong> The game goes as follows: 1) Start at 1<sup>st</sup>&nbsp;friend and pass the ball to the friend who is 2 steps away from them - 3<sup>rd</sup>&nbsp;friend. 2) 3<sup>rd</sup>&nbsp;friend passes the ball to the friend who is 4 steps away from them - 2<sup>nd</sup>&nbsp;friend. 3) 2<sup>nd</sup>&nbsp;friend passes the ball to the friend who is 6 steps away from them - 3<sup>rd</sup>&nbsp;friend. 4) The game ends as 3<sup>rd</sup>&nbsp;friend receives the ball for the second time. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 4, k = 4 <strong>Output:</strong> [2,3,4] <strong>Explanation:</strong> The game goes as follows: 1) Start at the 1<sup>st</sup>&nbsp;friend and pass the ball to the friend who is 4 steps away from them - 1<sup>st</sup>&nbsp;friend. 2) The game ends as 1<sup>st</sup>&nbsp;friend receives the ball for the second time. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= n &lt;= 50</code></li> </ul>
Array; Hash Table; Simulation
C++
class Solution { public: vector<int> circularGameLosers(int n, int k) { bool vis[n]; memset(vis, false, sizeof(vis)); for (int i = 0, p = 1; !vis[i]; ++p) { vis[i] = true; i = (i + p * k) % n; } vector<int> ans; for (int i = 0; i < n; ++i) { if (!vis[i]) { ans.push_back(i + 1); } } return ans; } };
2,682
Find the Losers of the Circular Game
Easy
<p>There are <code>n</code> friends that are playing a game. The friends are sitting in a circle and are numbered from <code>1</code> to <code>n</code> in <strong>clockwise order</strong>. More formally, moving clockwise from the <code>i<sup>th</sup></code> friend brings you to the <code>(i+1)<sup>th</sup></code> friend for <code>1 &lt;= i &lt; n</code>, and moving clockwise from the <code>n<sup>th</sup></code> friend brings you to the <code>1<sup>st</sup></code> friend.</p> <p>The rules of the game are as follows:</p> <p><code>1<sup>st</sup></code> friend receives the ball.</p> <ul> <li>After that, <code>1<sup>st</sup></code> friend passes it to the friend who is <code>k</code> steps away from them in the <strong>clockwise</strong> direction.</li> <li>After that, the friend who receives the ball should pass it to the friend who is <code>2 * k</code> steps away from them in the <strong>clockwise</strong> direction.</li> <li>After that, the friend who receives the ball should pass it to the friend who is <code>3 * k</code> steps away from them in the <strong>clockwise</strong> direction, and so on and so forth.</li> </ul> <p>In other words, on the <code>i<sup>th</sup></code> turn, the friend holding the ball should pass it to the friend who is <code>i * k</code> steps away from them in the <strong>clockwise</strong> direction.</p> <p>The game is finished when some friend receives the ball for the second time.</p> <p>The <strong>losers</strong> of the game are friends who did not receive the ball in the entire game.</p> <p>Given the number of friends, <code>n</code>, and an integer <code>k</code>, return <em>the array answer, which contains the losers of the game in the <strong>ascending</strong> order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, k = 2 <strong>Output:</strong> [4,5] <strong>Explanation:</strong> The game goes as follows: 1) Start at 1<sup>st</sup>&nbsp;friend and pass the ball to the friend who is 2 steps away from them - 3<sup>rd</sup>&nbsp;friend. 2) 3<sup>rd</sup>&nbsp;friend passes the ball to the friend who is 4 steps away from them - 2<sup>nd</sup>&nbsp;friend. 3) 2<sup>nd</sup>&nbsp;friend passes the ball to the friend who is 6 steps away from them - 3<sup>rd</sup>&nbsp;friend. 4) The game ends as 3<sup>rd</sup>&nbsp;friend receives the ball for the second time. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 4, k = 4 <strong>Output:</strong> [2,3,4] <strong>Explanation:</strong> The game goes as follows: 1) Start at the 1<sup>st</sup>&nbsp;friend and pass the ball to the friend who is 4 steps away from them - 1<sup>st</sup>&nbsp;friend. 2) The game ends as 1<sup>st</sup>&nbsp;friend receives the ball for the second time. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= n &lt;= 50</code></li> </ul>
Array; Hash Table; Simulation
Go
func circularGameLosers(n int, k int) (ans []int) { vis := make([]bool, n) for i, p := 0, 1; !vis[i]; p++ { vis[i] = true i = (i + p*k) % n } for i, x := range vis { if !x { ans = append(ans, i+1) } } return }
2,682
Find the Losers of the Circular Game
Easy
<p>There are <code>n</code> friends that are playing a game. The friends are sitting in a circle and are numbered from <code>1</code> to <code>n</code> in <strong>clockwise order</strong>. More formally, moving clockwise from the <code>i<sup>th</sup></code> friend brings you to the <code>(i+1)<sup>th</sup></code> friend for <code>1 &lt;= i &lt; n</code>, and moving clockwise from the <code>n<sup>th</sup></code> friend brings you to the <code>1<sup>st</sup></code> friend.</p> <p>The rules of the game are as follows:</p> <p><code>1<sup>st</sup></code> friend receives the ball.</p> <ul> <li>After that, <code>1<sup>st</sup></code> friend passes it to the friend who is <code>k</code> steps away from them in the <strong>clockwise</strong> direction.</li> <li>After that, the friend who receives the ball should pass it to the friend who is <code>2 * k</code> steps away from them in the <strong>clockwise</strong> direction.</li> <li>After that, the friend who receives the ball should pass it to the friend who is <code>3 * k</code> steps away from them in the <strong>clockwise</strong> direction, and so on and so forth.</li> </ul> <p>In other words, on the <code>i<sup>th</sup></code> turn, the friend holding the ball should pass it to the friend who is <code>i * k</code> steps away from them in the <strong>clockwise</strong> direction.</p> <p>The game is finished when some friend receives the ball for the second time.</p> <p>The <strong>losers</strong> of the game are friends who did not receive the ball in the entire game.</p> <p>Given the number of friends, <code>n</code>, and an integer <code>k</code>, return <em>the array answer, which contains the losers of the game in the <strong>ascending</strong> order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, k = 2 <strong>Output:</strong> [4,5] <strong>Explanation:</strong> The game goes as follows: 1) Start at 1<sup>st</sup>&nbsp;friend and pass the ball to the friend who is 2 steps away from them - 3<sup>rd</sup>&nbsp;friend. 2) 3<sup>rd</sup>&nbsp;friend passes the ball to the friend who is 4 steps away from them - 2<sup>nd</sup>&nbsp;friend. 3) 2<sup>nd</sup>&nbsp;friend passes the ball to the friend who is 6 steps away from them - 3<sup>rd</sup>&nbsp;friend. 4) The game ends as 3<sup>rd</sup>&nbsp;friend receives the ball for the second time. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 4, k = 4 <strong>Output:</strong> [2,3,4] <strong>Explanation:</strong> The game goes as follows: 1) Start at the 1<sup>st</sup>&nbsp;friend and pass the ball to the friend who is 4 steps away from them - 1<sup>st</sup>&nbsp;friend. 2) The game ends as 1<sup>st</sup>&nbsp;friend receives the ball for the second time. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= n &lt;= 50</code></li> </ul>
Array; Hash Table; Simulation
Java
class Solution { public int[] circularGameLosers(int n, int k) { boolean[] vis = new boolean[n]; int cnt = 0; for (int i = 0, p = 1; !vis[i]; ++p) { vis[i] = true; ++cnt; i = (i + p * k) % n; } int[] ans = new int[n - cnt]; for (int i = 0, j = 0; i < n; ++i) { if (!vis[i]) { ans[j++] = i + 1; } } return ans; } }
2,682
Find the Losers of the Circular Game
Easy
<p>There are <code>n</code> friends that are playing a game. The friends are sitting in a circle and are numbered from <code>1</code> to <code>n</code> in <strong>clockwise order</strong>. More formally, moving clockwise from the <code>i<sup>th</sup></code> friend brings you to the <code>(i+1)<sup>th</sup></code> friend for <code>1 &lt;= i &lt; n</code>, and moving clockwise from the <code>n<sup>th</sup></code> friend brings you to the <code>1<sup>st</sup></code> friend.</p> <p>The rules of the game are as follows:</p> <p><code>1<sup>st</sup></code> friend receives the ball.</p> <ul> <li>After that, <code>1<sup>st</sup></code> friend passes it to the friend who is <code>k</code> steps away from them in the <strong>clockwise</strong> direction.</li> <li>After that, the friend who receives the ball should pass it to the friend who is <code>2 * k</code> steps away from them in the <strong>clockwise</strong> direction.</li> <li>After that, the friend who receives the ball should pass it to the friend who is <code>3 * k</code> steps away from them in the <strong>clockwise</strong> direction, and so on and so forth.</li> </ul> <p>In other words, on the <code>i<sup>th</sup></code> turn, the friend holding the ball should pass it to the friend who is <code>i * k</code> steps away from them in the <strong>clockwise</strong> direction.</p> <p>The game is finished when some friend receives the ball for the second time.</p> <p>The <strong>losers</strong> of the game are friends who did not receive the ball in the entire game.</p> <p>Given the number of friends, <code>n</code>, and an integer <code>k</code>, return <em>the array answer, which contains the losers of the game in the <strong>ascending</strong> order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, k = 2 <strong>Output:</strong> [4,5] <strong>Explanation:</strong> The game goes as follows: 1) Start at 1<sup>st</sup>&nbsp;friend and pass the ball to the friend who is 2 steps away from them - 3<sup>rd</sup>&nbsp;friend. 2) 3<sup>rd</sup>&nbsp;friend passes the ball to the friend who is 4 steps away from them - 2<sup>nd</sup>&nbsp;friend. 3) 2<sup>nd</sup>&nbsp;friend passes the ball to the friend who is 6 steps away from them - 3<sup>rd</sup>&nbsp;friend. 4) The game ends as 3<sup>rd</sup>&nbsp;friend receives the ball for the second time. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 4, k = 4 <strong>Output:</strong> [2,3,4] <strong>Explanation:</strong> The game goes as follows: 1) Start at the 1<sup>st</sup>&nbsp;friend and pass the ball to the friend who is 4 steps away from them - 1<sup>st</sup>&nbsp;friend. 2) The game ends as 1<sup>st</sup>&nbsp;friend receives the ball for the second time. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= n &lt;= 50</code></li> </ul>
Array; Hash Table; Simulation
Python
class Solution: def circularGameLosers(self, n: int, k: int) -> List[int]: vis = [False] * n i, p = 0, 1 while not vis[i]: vis[i] = True i = (i + p * k) % n p += 1 return [i + 1 for i in range(n) if not vis[i]]
2,682
Find the Losers of the Circular Game
Easy
<p>There are <code>n</code> friends that are playing a game. The friends are sitting in a circle and are numbered from <code>1</code> to <code>n</code> in <strong>clockwise order</strong>. More formally, moving clockwise from the <code>i<sup>th</sup></code> friend brings you to the <code>(i+1)<sup>th</sup></code> friend for <code>1 &lt;= i &lt; n</code>, and moving clockwise from the <code>n<sup>th</sup></code> friend brings you to the <code>1<sup>st</sup></code> friend.</p> <p>The rules of the game are as follows:</p> <p><code>1<sup>st</sup></code> friend receives the ball.</p> <ul> <li>After that, <code>1<sup>st</sup></code> friend passes it to the friend who is <code>k</code> steps away from them in the <strong>clockwise</strong> direction.</li> <li>After that, the friend who receives the ball should pass it to the friend who is <code>2 * k</code> steps away from them in the <strong>clockwise</strong> direction.</li> <li>After that, the friend who receives the ball should pass it to the friend who is <code>3 * k</code> steps away from them in the <strong>clockwise</strong> direction, and so on and so forth.</li> </ul> <p>In other words, on the <code>i<sup>th</sup></code> turn, the friend holding the ball should pass it to the friend who is <code>i * k</code> steps away from them in the <strong>clockwise</strong> direction.</p> <p>The game is finished when some friend receives the ball for the second time.</p> <p>The <strong>losers</strong> of the game are friends who did not receive the ball in the entire game.</p> <p>Given the number of friends, <code>n</code>, and an integer <code>k</code>, return <em>the array answer, which contains the losers of the game in the <strong>ascending</strong> order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, k = 2 <strong>Output:</strong> [4,5] <strong>Explanation:</strong> The game goes as follows: 1) Start at 1<sup>st</sup>&nbsp;friend and pass the ball to the friend who is 2 steps away from them - 3<sup>rd</sup>&nbsp;friend. 2) 3<sup>rd</sup>&nbsp;friend passes the ball to the friend who is 4 steps away from them - 2<sup>nd</sup>&nbsp;friend. 3) 2<sup>nd</sup>&nbsp;friend passes the ball to the friend who is 6 steps away from them - 3<sup>rd</sup>&nbsp;friend. 4) The game ends as 3<sup>rd</sup>&nbsp;friend receives the ball for the second time. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 4, k = 4 <strong>Output:</strong> [2,3,4] <strong>Explanation:</strong> The game goes as follows: 1) Start at the 1<sup>st</sup>&nbsp;friend and pass the ball to the friend who is 4 steps away from them - 1<sup>st</sup>&nbsp;friend. 2) The game ends as 1<sup>st</sup>&nbsp;friend receives the ball for the second time. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= n &lt;= 50</code></li> </ul>
Array; Hash Table; Simulation
Rust
impl Solution { pub fn circular_game_losers(n: i32, k: i32) -> Vec<i32> { let mut vis: Vec<bool> = vec![false; n as usize]; let mut i = 0; let mut p = 1; while !vis[i] { vis[i] = true; i = (i + p * (k as usize)) % (n as usize); p += 1; } let mut ans = Vec::new(); for i in 0..vis.len() { if !vis[i] { ans.push((i + 1) as i32); } } ans } }
2,682
Find the Losers of the Circular Game
Easy
<p>There are <code>n</code> friends that are playing a game. The friends are sitting in a circle and are numbered from <code>1</code> to <code>n</code> in <strong>clockwise order</strong>. More formally, moving clockwise from the <code>i<sup>th</sup></code> friend brings you to the <code>(i+1)<sup>th</sup></code> friend for <code>1 &lt;= i &lt; n</code>, and moving clockwise from the <code>n<sup>th</sup></code> friend brings you to the <code>1<sup>st</sup></code> friend.</p> <p>The rules of the game are as follows:</p> <p><code>1<sup>st</sup></code> friend receives the ball.</p> <ul> <li>After that, <code>1<sup>st</sup></code> friend passes it to the friend who is <code>k</code> steps away from them in the <strong>clockwise</strong> direction.</li> <li>After that, the friend who receives the ball should pass it to the friend who is <code>2 * k</code> steps away from them in the <strong>clockwise</strong> direction.</li> <li>After that, the friend who receives the ball should pass it to the friend who is <code>3 * k</code> steps away from them in the <strong>clockwise</strong> direction, and so on and so forth.</li> </ul> <p>In other words, on the <code>i<sup>th</sup></code> turn, the friend holding the ball should pass it to the friend who is <code>i * k</code> steps away from them in the <strong>clockwise</strong> direction.</p> <p>The game is finished when some friend receives the ball for the second time.</p> <p>The <strong>losers</strong> of the game are friends who did not receive the ball in the entire game.</p> <p>Given the number of friends, <code>n</code>, and an integer <code>k</code>, return <em>the array answer, which contains the losers of the game in the <strong>ascending</strong> order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, k = 2 <strong>Output:</strong> [4,5] <strong>Explanation:</strong> The game goes as follows: 1) Start at 1<sup>st</sup>&nbsp;friend and pass the ball to the friend who is 2 steps away from them - 3<sup>rd</sup>&nbsp;friend. 2) 3<sup>rd</sup>&nbsp;friend passes the ball to the friend who is 4 steps away from them - 2<sup>nd</sup>&nbsp;friend. 3) 2<sup>nd</sup>&nbsp;friend passes the ball to the friend who is 6 steps away from them - 3<sup>rd</sup>&nbsp;friend. 4) The game ends as 3<sup>rd</sup>&nbsp;friend receives the ball for the second time. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 4, k = 4 <strong>Output:</strong> [2,3,4] <strong>Explanation:</strong> The game goes as follows: 1) Start at the 1<sup>st</sup>&nbsp;friend and pass the ball to the friend who is 4 steps away from them - 1<sup>st</sup>&nbsp;friend. 2) The game ends as 1<sup>st</sup>&nbsp;friend receives the ball for the second time. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= n &lt;= 50</code></li> </ul>
Array; Hash Table; Simulation
TypeScript
function circularGameLosers(n: number, k: number): number[] { const vis = new Array(n).fill(false); const ans: number[] = []; for (let i = 0, p = 1; !vis[i]; p++) { vis[i] = true; i = (i + p * k) % n; } for (let i = 0; i < vis.length; i++) { if (!vis[i]) { ans.push(i + 1); } } return ans; }
2,683
Neighboring Bitwise XOR
Medium
<p>A <strong>0-indexed</strong> array <code>derived</code> with length <code>n</code> is derived by computing the <strong>bitwise XOR</strong>&nbsp;(&oplus;) of adjacent values in a <strong>binary array</strong> <code>original</code> of length <code>n</code>.</p> <p>Specifically, for each index <code>i</code> in the range <code>[0, n - 1]</code>:</p> <ul> <li>If <code>i = n - 1</code>, then <code>derived[i] = original[i] &oplus; original[0]</code>.</li> <li>Otherwise, <code>derived[i] = original[i] &oplus; original[i + 1]</code>.</li> </ul> <p>Given an array <code>derived</code>, your task is to determine whether there exists a <strong>valid binary array</strong> <code>original</code> that could have formed <code>derived</code>.</p> <p>Return <em><strong>true</strong> if such an array exists or <strong>false</strong> otherwise.</em></p> <ul> <li>A binary array is an array containing only <strong>0&#39;s</strong> and <strong>1&#39;s</strong></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> derived = [1,1,0] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1,0]. derived[0] = original[0] &oplus; original[1] = 0 &oplus; 1 = 1 derived[1] = original[1] &oplus; original[2] = 1 &oplus; 0 = 1 derived[2] = original[2] &oplus; original[0] = 0 &oplus; 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> derived = [1,1] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1]. derived[0] = original[0] &oplus; original[1] = 1 derived[1] = original[1] &oplus; original[0] = 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> derived = [1,0] <strong>Output:</strong> false <strong>Explanation:</strong> There is no valid original array that gives derived. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == derived.length</code></li> <li><code>1 &lt;= n&nbsp;&lt;= 10<sup>5</sup></code></li> <li>The values in <code>derived</code>&nbsp;are either <strong>0&#39;s</strong> or <strong>1&#39;s</strong></li> </ul>
Bit Manipulation; Array
C++
class Solution { public: bool doesValidArrayExist(vector<int>& derived) { int s = 0; for (int x : derived) { s ^= x; } return s == 0; } };
2,683
Neighboring Bitwise XOR
Medium
<p>A <strong>0-indexed</strong> array <code>derived</code> with length <code>n</code> is derived by computing the <strong>bitwise XOR</strong>&nbsp;(&oplus;) of adjacent values in a <strong>binary array</strong> <code>original</code> of length <code>n</code>.</p> <p>Specifically, for each index <code>i</code> in the range <code>[0, n - 1]</code>:</p> <ul> <li>If <code>i = n - 1</code>, then <code>derived[i] = original[i] &oplus; original[0]</code>.</li> <li>Otherwise, <code>derived[i] = original[i] &oplus; original[i + 1]</code>.</li> </ul> <p>Given an array <code>derived</code>, your task is to determine whether there exists a <strong>valid binary array</strong> <code>original</code> that could have formed <code>derived</code>.</p> <p>Return <em><strong>true</strong> if such an array exists or <strong>false</strong> otherwise.</em></p> <ul> <li>A binary array is an array containing only <strong>0&#39;s</strong> and <strong>1&#39;s</strong></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> derived = [1,1,0] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1,0]. derived[0] = original[0] &oplus; original[1] = 0 &oplus; 1 = 1 derived[1] = original[1] &oplus; original[2] = 1 &oplus; 0 = 1 derived[2] = original[2] &oplus; original[0] = 0 &oplus; 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> derived = [1,1] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1]. derived[0] = original[0] &oplus; original[1] = 1 derived[1] = original[1] &oplus; original[0] = 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> derived = [1,0] <strong>Output:</strong> false <strong>Explanation:</strong> There is no valid original array that gives derived. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == derived.length</code></li> <li><code>1 &lt;= n&nbsp;&lt;= 10<sup>5</sup></code></li> <li>The values in <code>derived</code>&nbsp;are either <strong>0&#39;s</strong> or <strong>1&#39;s</strong></li> </ul>
Bit Manipulation; Array
C#
public class Solution { public bool DoesValidArrayExist(int[] derived) { return derived.Aggregate(0, (acc, x) => acc ^ x) == 0; } }
2,683
Neighboring Bitwise XOR
Medium
<p>A <strong>0-indexed</strong> array <code>derived</code> with length <code>n</code> is derived by computing the <strong>bitwise XOR</strong>&nbsp;(&oplus;) of adjacent values in a <strong>binary array</strong> <code>original</code> of length <code>n</code>.</p> <p>Specifically, for each index <code>i</code> in the range <code>[0, n - 1]</code>:</p> <ul> <li>If <code>i = n - 1</code>, then <code>derived[i] = original[i] &oplus; original[0]</code>.</li> <li>Otherwise, <code>derived[i] = original[i] &oplus; original[i + 1]</code>.</li> </ul> <p>Given an array <code>derived</code>, your task is to determine whether there exists a <strong>valid binary array</strong> <code>original</code> that could have formed <code>derived</code>.</p> <p>Return <em><strong>true</strong> if such an array exists or <strong>false</strong> otherwise.</em></p> <ul> <li>A binary array is an array containing only <strong>0&#39;s</strong> and <strong>1&#39;s</strong></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> derived = [1,1,0] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1,0]. derived[0] = original[0] &oplus; original[1] = 0 &oplus; 1 = 1 derived[1] = original[1] &oplus; original[2] = 1 &oplus; 0 = 1 derived[2] = original[2] &oplus; original[0] = 0 &oplus; 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> derived = [1,1] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1]. derived[0] = original[0] &oplus; original[1] = 1 derived[1] = original[1] &oplus; original[0] = 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> derived = [1,0] <strong>Output:</strong> false <strong>Explanation:</strong> There is no valid original array that gives derived. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == derived.length</code></li> <li><code>1 &lt;= n&nbsp;&lt;= 10<sup>5</sup></code></li> <li>The values in <code>derived</code>&nbsp;are either <strong>0&#39;s</strong> or <strong>1&#39;s</strong></li> </ul>
Bit Manipulation; Array
Go
func doesValidArrayExist(derived []int) bool { s := 0 for _, x := range derived { s ^= x } return s == 0 }
2,683
Neighboring Bitwise XOR
Medium
<p>A <strong>0-indexed</strong> array <code>derived</code> with length <code>n</code> is derived by computing the <strong>bitwise XOR</strong>&nbsp;(&oplus;) of adjacent values in a <strong>binary array</strong> <code>original</code> of length <code>n</code>.</p> <p>Specifically, for each index <code>i</code> in the range <code>[0, n - 1]</code>:</p> <ul> <li>If <code>i = n - 1</code>, then <code>derived[i] = original[i] &oplus; original[0]</code>.</li> <li>Otherwise, <code>derived[i] = original[i] &oplus; original[i + 1]</code>.</li> </ul> <p>Given an array <code>derived</code>, your task is to determine whether there exists a <strong>valid binary array</strong> <code>original</code> that could have formed <code>derived</code>.</p> <p>Return <em><strong>true</strong> if such an array exists or <strong>false</strong> otherwise.</em></p> <ul> <li>A binary array is an array containing only <strong>0&#39;s</strong> and <strong>1&#39;s</strong></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> derived = [1,1,0] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1,0]. derived[0] = original[0] &oplus; original[1] = 0 &oplus; 1 = 1 derived[1] = original[1] &oplus; original[2] = 1 &oplus; 0 = 1 derived[2] = original[2] &oplus; original[0] = 0 &oplus; 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> derived = [1,1] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1]. derived[0] = original[0] &oplus; original[1] = 1 derived[1] = original[1] &oplus; original[0] = 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> derived = [1,0] <strong>Output:</strong> false <strong>Explanation:</strong> There is no valid original array that gives derived. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == derived.length</code></li> <li><code>1 &lt;= n&nbsp;&lt;= 10<sup>5</sup></code></li> <li>The values in <code>derived</code>&nbsp;are either <strong>0&#39;s</strong> or <strong>1&#39;s</strong></li> </ul>
Bit Manipulation; Array
Java
class Solution { public boolean doesValidArrayExist(int[] derived) { int s = 0; for (int x : derived) { s ^= x; } return s == 0; } }
2,683
Neighboring Bitwise XOR
Medium
<p>A <strong>0-indexed</strong> array <code>derived</code> with length <code>n</code> is derived by computing the <strong>bitwise XOR</strong>&nbsp;(&oplus;) of adjacent values in a <strong>binary array</strong> <code>original</code> of length <code>n</code>.</p> <p>Specifically, for each index <code>i</code> in the range <code>[0, n - 1]</code>:</p> <ul> <li>If <code>i = n - 1</code>, then <code>derived[i] = original[i] &oplus; original[0]</code>.</li> <li>Otherwise, <code>derived[i] = original[i] &oplus; original[i + 1]</code>.</li> </ul> <p>Given an array <code>derived</code>, your task is to determine whether there exists a <strong>valid binary array</strong> <code>original</code> that could have formed <code>derived</code>.</p> <p>Return <em><strong>true</strong> if such an array exists or <strong>false</strong> otherwise.</em></p> <ul> <li>A binary array is an array containing only <strong>0&#39;s</strong> and <strong>1&#39;s</strong></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> derived = [1,1,0] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1,0]. derived[0] = original[0] &oplus; original[1] = 0 &oplus; 1 = 1 derived[1] = original[1] &oplus; original[2] = 1 &oplus; 0 = 1 derived[2] = original[2] &oplus; original[0] = 0 &oplus; 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> derived = [1,1] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1]. derived[0] = original[0] &oplus; original[1] = 1 derived[1] = original[1] &oplus; original[0] = 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> derived = [1,0] <strong>Output:</strong> false <strong>Explanation:</strong> There is no valid original array that gives derived. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == derived.length</code></li> <li><code>1 &lt;= n&nbsp;&lt;= 10<sup>5</sup></code></li> <li>The values in <code>derived</code>&nbsp;are either <strong>0&#39;s</strong> or <strong>1&#39;s</strong></li> </ul>
Bit Manipulation; Array
JavaScript
/** * @param {number[]} derived * @return {boolean} */ var doesValidArrayExist = function (derived) { return derived.reduce((acc, x) => acc ^ x) === 0; };
2,683
Neighboring Bitwise XOR
Medium
<p>A <strong>0-indexed</strong> array <code>derived</code> with length <code>n</code> is derived by computing the <strong>bitwise XOR</strong>&nbsp;(&oplus;) of adjacent values in a <strong>binary array</strong> <code>original</code> of length <code>n</code>.</p> <p>Specifically, for each index <code>i</code> in the range <code>[0, n - 1]</code>:</p> <ul> <li>If <code>i = n - 1</code>, then <code>derived[i] = original[i] &oplus; original[0]</code>.</li> <li>Otherwise, <code>derived[i] = original[i] &oplus; original[i + 1]</code>.</li> </ul> <p>Given an array <code>derived</code>, your task is to determine whether there exists a <strong>valid binary array</strong> <code>original</code> that could have formed <code>derived</code>.</p> <p>Return <em><strong>true</strong> if such an array exists or <strong>false</strong> otherwise.</em></p> <ul> <li>A binary array is an array containing only <strong>0&#39;s</strong> and <strong>1&#39;s</strong></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> derived = [1,1,0] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1,0]. derived[0] = original[0] &oplus; original[1] = 0 &oplus; 1 = 1 derived[1] = original[1] &oplus; original[2] = 1 &oplus; 0 = 1 derived[2] = original[2] &oplus; original[0] = 0 &oplus; 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> derived = [1,1] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1]. derived[0] = original[0] &oplus; original[1] = 1 derived[1] = original[1] &oplus; original[0] = 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> derived = [1,0] <strong>Output:</strong> false <strong>Explanation:</strong> There is no valid original array that gives derived. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == derived.length</code></li> <li><code>1 &lt;= n&nbsp;&lt;= 10<sup>5</sup></code></li> <li>The values in <code>derived</code>&nbsp;are either <strong>0&#39;s</strong> or <strong>1&#39;s</strong></li> </ul>
Bit Manipulation; Array
Python
class Solution: def doesValidArrayExist(self, derived: List[int]) -> bool: return reduce(xor, derived) == 0
2,683
Neighboring Bitwise XOR
Medium
<p>A <strong>0-indexed</strong> array <code>derived</code> with length <code>n</code> is derived by computing the <strong>bitwise XOR</strong>&nbsp;(&oplus;) of adjacent values in a <strong>binary array</strong> <code>original</code> of length <code>n</code>.</p> <p>Specifically, for each index <code>i</code> in the range <code>[0, n - 1]</code>:</p> <ul> <li>If <code>i = n - 1</code>, then <code>derived[i] = original[i] &oplus; original[0]</code>.</li> <li>Otherwise, <code>derived[i] = original[i] &oplus; original[i + 1]</code>.</li> </ul> <p>Given an array <code>derived</code>, your task is to determine whether there exists a <strong>valid binary array</strong> <code>original</code> that could have formed <code>derived</code>.</p> <p>Return <em><strong>true</strong> if such an array exists or <strong>false</strong> otherwise.</em></p> <ul> <li>A binary array is an array containing only <strong>0&#39;s</strong> and <strong>1&#39;s</strong></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> derived = [1,1,0] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1,0]. derived[0] = original[0] &oplus; original[1] = 0 &oplus; 1 = 1 derived[1] = original[1] &oplus; original[2] = 1 &oplus; 0 = 1 derived[2] = original[2] &oplus; original[0] = 0 &oplus; 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> derived = [1,1] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1]. derived[0] = original[0] &oplus; original[1] = 1 derived[1] = original[1] &oplus; original[0] = 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> derived = [1,0] <strong>Output:</strong> false <strong>Explanation:</strong> There is no valid original array that gives derived. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == derived.length</code></li> <li><code>1 &lt;= n&nbsp;&lt;= 10<sup>5</sup></code></li> <li>The values in <code>derived</code>&nbsp;are either <strong>0&#39;s</strong> or <strong>1&#39;s</strong></li> </ul>
Bit Manipulation; Array
Rust
impl Solution { pub fn does_valid_array_exist(derived: Vec<i32>) -> bool { derived.iter().fold(0, |acc, &x| acc ^ x) == 0 } }
2,683
Neighboring Bitwise XOR
Medium
<p>A <strong>0-indexed</strong> array <code>derived</code> with length <code>n</code> is derived by computing the <strong>bitwise XOR</strong>&nbsp;(&oplus;) of adjacent values in a <strong>binary array</strong> <code>original</code> of length <code>n</code>.</p> <p>Specifically, for each index <code>i</code> in the range <code>[0, n - 1]</code>:</p> <ul> <li>If <code>i = n - 1</code>, then <code>derived[i] = original[i] &oplus; original[0]</code>.</li> <li>Otherwise, <code>derived[i] = original[i] &oplus; original[i + 1]</code>.</li> </ul> <p>Given an array <code>derived</code>, your task is to determine whether there exists a <strong>valid binary array</strong> <code>original</code> that could have formed <code>derived</code>.</p> <p>Return <em><strong>true</strong> if such an array exists or <strong>false</strong> otherwise.</em></p> <ul> <li>A binary array is an array containing only <strong>0&#39;s</strong> and <strong>1&#39;s</strong></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> derived = [1,1,0] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1,0]. derived[0] = original[0] &oplus; original[1] = 0 &oplus; 1 = 1 derived[1] = original[1] &oplus; original[2] = 1 &oplus; 0 = 1 derived[2] = original[2] &oplus; original[0] = 0 &oplus; 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> derived = [1,1] <strong>Output:</strong> true <strong>Explanation:</strong> A valid original array that gives derived is [0,1]. derived[0] = original[0] &oplus; original[1] = 1 derived[1] = original[1] &oplus; original[0] = 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> derived = [1,0] <strong>Output:</strong> false <strong>Explanation:</strong> There is no valid original array that gives derived. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == derived.length</code></li> <li><code>1 &lt;= n&nbsp;&lt;= 10<sup>5</sup></code></li> <li>The values in <code>derived</code>&nbsp;are either <strong>0&#39;s</strong> or <strong>1&#39;s</strong></li> </ul>
Bit Manipulation; Array
TypeScript
function doesValidArrayExist(derived: number[]): boolean { return derived.reduce((acc, x) => acc ^ x) === 0; }
2,684
Maximum Number of Moves in a Grid
Medium
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> matrix <code>grid</code> consisting of <strong>positive</strong> integers.</p> <p>You can start at <strong>any</strong> cell in the first column of the matrix, and traverse the grid in the following way:</p> <ul> <li>From a cell <code>(row, col)</code>, you can move to any of the cells: <code>(row - 1, col + 1)</code>, <code>(row, col + 1)</code> and <code>(row + 1, col + 1)</code> such that the value of the cell you move to, should be <strong>strictly</strong> bigger than the value of the current cell.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of <strong>moves</strong> that you can perform.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2684.Maximum%20Number%20of%20Moves%20in%20a%20Grid/images/yetgriddrawio-10.png" style="width: 201px; height: 201px;" /> <pre> <strong>Input:</strong> grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can start at the cell (0, 0) and make the following moves: - (0, 0) -&gt; (0, 1). - (0, 1) -&gt; (1, 2). - (1, 2) -&gt; (2, 3). It can be shown that it is the maximum number of moves that can be made.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2684.Maximum%20Number%20of%20Moves%20in%20a%20Grid/images/yetgrid4drawio.png" /> <strong>Input:</strong> grid = [[3,2,4],[2,1,9],[1,1,7]] <strong>Output:</strong> 0 <strong>Explanation:</strong> Starting from any cell in the first column we cannot perform any moves. </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>2 &lt;= m, n &lt;= 1000</code></li> <li><code>4 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Dynamic Programming; Matrix
C++
class Solution { public: int maxMoves(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); unordered_set<int> q, t; for (int i = 0; i < m; ++i) { q.insert(i); } for (int j = 0; j < n - 1; ++j) { t.clear(); for (int i : q) { for (int k = i - 1; k <= i + 1; ++k) { if (k >= 0 && k < m && grid[i][j] < grid[k][j + 1]) { t.insert(k); } } } if (t.empty()) { return j; } q.swap(t); } return n - 1; } };
2,684
Maximum Number of Moves in a Grid
Medium
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> matrix <code>grid</code> consisting of <strong>positive</strong> integers.</p> <p>You can start at <strong>any</strong> cell in the first column of the matrix, and traverse the grid in the following way:</p> <ul> <li>From a cell <code>(row, col)</code>, you can move to any of the cells: <code>(row - 1, col + 1)</code>, <code>(row, col + 1)</code> and <code>(row + 1, col + 1)</code> such that the value of the cell you move to, should be <strong>strictly</strong> bigger than the value of the current cell.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of <strong>moves</strong> that you can perform.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2684.Maximum%20Number%20of%20Moves%20in%20a%20Grid/images/yetgriddrawio-10.png" style="width: 201px; height: 201px;" /> <pre> <strong>Input:</strong> grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can start at the cell (0, 0) and make the following moves: - (0, 0) -&gt; (0, 1). - (0, 1) -&gt; (1, 2). - (1, 2) -&gt; (2, 3). It can be shown that it is the maximum number of moves that can be made.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2684.Maximum%20Number%20of%20Moves%20in%20a%20Grid/images/yetgrid4drawio.png" /> <strong>Input:</strong> grid = [[3,2,4],[2,1,9],[1,1,7]] <strong>Output:</strong> 0 <strong>Explanation:</strong> Starting from any cell in the first column we cannot perform any moves. </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>2 &lt;= m, n &lt;= 1000</code></li> <li><code>4 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Dynamic Programming; Matrix
Go
func maxMoves(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) q := map[int]bool{} for i := range grid { q[i] = true } for j := 0; j < n-1; j++ { t := map[int]bool{} for i := range q { for k := i - 1; k <= i+1; k++ { if k >= 0 && k < m && grid[i][j] < grid[k][j+1] { t[k] = true } } } if len(t) == 0 { return j } q = t } return n - 1 }
2,684
Maximum Number of Moves in a Grid
Medium
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> matrix <code>grid</code> consisting of <strong>positive</strong> integers.</p> <p>You can start at <strong>any</strong> cell in the first column of the matrix, and traverse the grid in the following way:</p> <ul> <li>From a cell <code>(row, col)</code>, you can move to any of the cells: <code>(row - 1, col + 1)</code>, <code>(row, col + 1)</code> and <code>(row + 1, col + 1)</code> such that the value of the cell you move to, should be <strong>strictly</strong> bigger than the value of the current cell.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of <strong>moves</strong> that you can perform.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2684.Maximum%20Number%20of%20Moves%20in%20a%20Grid/images/yetgriddrawio-10.png" style="width: 201px; height: 201px;" /> <pre> <strong>Input:</strong> grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can start at the cell (0, 0) and make the following moves: - (0, 0) -&gt; (0, 1). - (0, 1) -&gt; (1, 2). - (1, 2) -&gt; (2, 3). It can be shown that it is the maximum number of moves that can be made.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2684.Maximum%20Number%20of%20Moves%20in%20a%20Grid/images/yetgrid4drawio.png" /> <strong>Input:</strong> grid = [[3,2,4],[2,1,9],[1,1,7]] <strong>Output:</strong> 0 <strong>Explanation:</strong> Starting from any cell in the first column we cannot perform any moves. </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>2 &lt;= m, n &lt;= 1000</code></li> <li><code>4 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Dynamic Programming; Matrix
Java
class Solution { public int maxMoves(int[][] grid) { int m = grid.length, n = grid[0].length; Set<Integer> q = IntStream.range(0, m).boxed().collect(Collectors.toSet()); for (int j = 0; j < n - 1; ++j) { Set<Integer> t = new HashSet<>(); for (int i : q) { for (int k = i - 1; k <= i + 1; ++k) { if (k >= 0 && k < m && grid[i][j] < grid[k][j + 1]) { t.add(k); } } } if (t.isEmpty()) { return j; } q = t; } return n - 1; } }
2,684
Maximum Number of Moves in a Grid
Medium
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> matrix <code>grid</code> consisting of <strong>positive</strong> integers.</p> <p>You can start at <strong>any</strong> cell in the first column of the matrix, and traverse the grid in the following way:</p> <ul> <li>From a cell <code>(row, col)</code>, you can move to any of the cells: <code>(row - 1, col + 1)</code>, <code>(row, col + 1)</code> and <code>(row + 1, col + 1)</code> such that the value of the cell you move to, should be <strong>strictly</strong> bigger than the value of the current cell.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of <strong>moves</strong> that you can perform.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2684.Maximum%20Number%20of%20Moves%20in%20a%20Grid/images/yetgriddrawio-10.png" style="width: 201px; height: 201px;" /> <pre> <strong>Input:</strong> grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can start at the cell (0, 0) and make the following moves: - (0, 0) -&gt; (0, 1). - (0, 1) -&gt; (1, 2). - (1, 2) -&gt; (2, 3). It can be shown that it is the maximum number of moves that can be made.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2684.Maximum%20Number%20of%20Moves%20in%20a%20Grid/images/yetgrid4drawio.png" /> <strong>Input:</strong> grid = [[3,2,4],[2,1,9],[1,1,7]] <strong>Output:</strong> 0 <strong>Explanation:</strong> Starting from any cell in the first column we cannot perform any moves. </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>2 &lt;= m, n &lt;= 1000</code></li> <li><code>4 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Dynamic Programming; Matrix
Python
class Solution: def maxMoves(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) q = set(range(m)) for j in range(n - 1): t = set() for i in q: for k in range(i - 1, i + 2): if 0 <= k < m and grid[i][j] < grid[k][j + 1]: t.add(k) if not t: return j q = t return n - 1
2,684
Maximum Number of Moves in a Grid
Medium
<p>You are given a <strong>0-indexed</strong> <code>m x n</code> matrix <code>grid</code> consisting of <strong>positive</strong> integers.</p> <p>You can start at <strong>any</strong> cell in the first column of the matrix, and traverse the grid in the following way:</p> <ul> <li>From a cell <code>(row, col)</code>, you can move to any of the cells: <code>(row - 1, col + 1)</code>, <code>(row, col + 1)</code> and <code>(row + 1, col + 1)</code> such that the value of the cell you move to, should be <strong>strictly</strong> bigger than the value of the current cell.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of <strong>moves</strong> that you can perform.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2684.Maximum%20Number%20of%20Moves%20in%20a%20Grid/images/yetgriddrawio-10.png" style="width: 201px; height: 201px;" /> <pre> <strong>Input:</strong> grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can start at the cell (0, 0) and make the following moves: - (0, 0) -&gt; (0, 1). - (0, 1) -&gt; (1, 2). - (1, 2) -&gt; (2, 3). It can be shown that it is the maximum number of moves that can be made.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2684.Maximum%20Number%20of%20Moves%20in%20a%20Grid/images/yetgrid4drawio.png" /> <strong>Input:</strong> grid = [[3,2,4],[2,1,9],[1,1,7]] <strong>Output:</strong> 0 <strong>Explanation:</strong> Starting from any cell in the first column we cannot perform any moves. </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>2 &lt;= m, n &lt;= 1000</code></li> <li><code>4 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= grid[i][j] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Dynamic Programming; Matrix
TypeScript
function maxMoves(grid: number[][]): number { const m = grid.length; const n = grid[0].length; let q = new Set<number>(Array.from({ length: m }, (_, i) => i)); for (let j = 0; j < n - 1; ++j) { const t = new Set<number>(); for (const i of q) { for (let k = i - 1; k <= i + 1; ++k) { if (k >= 0 && k < m && grid[i][j] < grid[k][j + 1]) { t.add(k); } } } if (t.size === 0) { return j; } q = t; } return n - 1; }
2,685
Count the Number of Complete Components
Medium
<p>You are given an integer <code>n</code>. There is an <strong>undirected</strong> graph with <code>n</code> vertices, numbered from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> denotes that there exists an <strong>undirected</strong> edge connecting vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code>.</p> <p>Return <em>the number of <strong>complete connected components</strong> of the graph</em>.</p> <p>A <strong>connected component</strong> is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.</p> <p>A connected component is said to be <b>complete</b> if there exists an edge between every pair of its vertices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2685.Count%20the%20Number%20of%20Complete%20Components/images/screenshot-from-2023-04-11-23-31-23.png" style="width: 671px; height: 270px;" /></strong></p> <pre> <strong>Input:</strong> n = 6, edges = [[0,1],[0,2],[1,2],[3,4]] <strong>Output:</strong> 3 <strong>Explanation:</strong> From the picture above, one can see that all of the components of this graph are complete. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2685.Count%20the%20Number%20of%20Complete%20Components/images/screenshot-from-2023-04-11-23-32-00.png" style="width: 671px; height: 270px;" /></strong></p> <pre> <strong>Input:</strong> n = 6, edges = [[0,1],[0,2],[1,2],[3,4],[3,5]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The component containing vertices 0, 1, and 2 is complete since there is an edge between every pair of two vertices. On the other hand, the component containing vertices 3, 4, and 5 is not complete since there is no edge between vertices 4 and 5. Thus, the number of complete components in this graph is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>0 &lt;= edges.length &lt;= n * (n - 1) / 2</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt;= n - 1</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>There are no repeated edges.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
C++
class Solution { public: int countCompleteComponents(int n, vector<vector<int>>& edges) { vector<vector<int>> g(n); bool vis[n]; memset(vis, false, sizeof(vis)); for (auto& e : edges) { int a = e[0], b = e[1]; g[a].push_back(b); g[b].push_back(a); } function<pair<int, int>(int)> dfs = [&](int i) -> pair<int, int> { vis[i] = true; int x = 1, y = g[i].size(); for (int j : g[i]) { if (!vis[j]) { auto [a, b] = dfs(j); x += a; y += b; } } return make_pair(x, y); }; int ans = 0; for (int i = 0; i < n; ++i) { if (!vis[i]) { auto [a, b] = dfs(i); if (a * (a - 1) == b) { ++ans; } } } return ans; } };
2,685
Count the Number of Complete Components
Medium
<p>You are given an integer <code>n</code>. There is an <strong>undirected</strong> graph with <code>n</code> vertices, numbered from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> denotes that there exists an <strong>undirected</strong> edge connecting vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code>.</p> <p>Return <em>the number of <strong>complete connected components</strong> of the graph</em>.</p> <p>A <strong>connected component</strong> is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.</p> <p>A connected component is said to be <b>complete</b> if there exists an edge between every pair of its vertices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2685.Count%20the%20Number%20of%20Complete%20Components/images/screenshot-from-2023-04-11-23-31-23.png" style="width: 671px; height: 270px;" /></strong></p> <pre> <strong>Input:</strong> n = 6, edges = [[0,1],[0,2],[1,2],[3,4]] <strong>Output:</strong> 3 <strong>Explanation:</strong> From the picture above, one can see that all of the components of this graph are complete. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2685.Count%20the%20Number%20of%20Complete%20Components/images/screenshot-from-2023-04-11-23-32-00.png" style="width: 671px; height: 270px;" /></strong></p> <pre> <strong>Input:</strong> n = 6, edges = [[0,1],[0,2],[1,2],[3,4],[3,5]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The component containing vertices 0, 1, and 2 is complete since there is an edge between every pair of two vertices. On the other hand, the component containing vertices 3, 4, and 5 is not complete since there is no edge between vertices 4 and 5. Thus, the number of complete components in this graph is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>0 &lt;= edges.length &lt;= n * (n - 1) / 2</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt;= n - 1</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>There are no repeated edges.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
Go
func countCompleteComponents(n int, edges [][]int) (ans int) { g := make([][]int, n) vis := make([]bool, n) for _, e := range edges { a, b := e[0], e[1] g[a] = append(g[a], b) g[b] = append(g[b], a) } var dfs func(int) (int, int) dfs = func(i int) (int, int) { vis[i] = true x, y := 1, len(g[i]) for _, j := range g[i] { if !vis[j] { a, b := dfs(j) x += a y += b } } return x, y } for i := range vis { if !vis[i] { a, b := dfs(i) if a*(a-1) == b { ans++ } } } return }
2,685
Count the Number of Complete Components
Medium
<p>You are given an integer <code>n</code>. There is an <strong>undirected</strong> graph with <code>n</code> vertices, numbered from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> denotes that there exists an <strong>undirected</strong> edge connecting vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code>.</p> <p>Return <em>the number of <strong>complete connected components</strong> of the graph</em>.</p> <p>A <strong>connected component</strong> is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.</p> <p>A connected component is said to be <b>complete</b> if there exists an edge between every pair of its vertices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2685.Count%20the%20Number%20of%20Complete%20Components/images/screenshot-from-2023-04-11-23-31-23.png" style="width: 671px; height: 270px;" /></strong></p> <pre> <strong>Input:</strong> n = 6, edges = [[0,1],[0,2],[1,2],[3,4]] <strong>Output:</strong> 3 <strong>Explanation:</strong> From the picture above, one can see that all of the components of this graph are complete. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2685.Count%20the%20Number%20of%20Complete%20Components/images/screenshot-from-2023-04-11-23-32-00.png" style="width: 671px; height: 270px;" /></strong></p> <pre> <strong>Input:</strong> n = 6, edges = [[0,1],[0,2],[1,2],[3,4],[3,5]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The component containing vertices 0, 1, and 2 is complete since there is an edge between every pair of two vertices. On the other hand, the component containing vertices 3, 4, and 5 is not complete since there is no edge between vertices 4 and 5. Thus, the number of complete components in this graph is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>0 &lt;= edges.length &lt;= n * (n - 1) / 2</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt;= n - 1</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>There are no repeated edges.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
Java
class Solution { private List<Integer>[] g; private boolean[] vis; public int countCompleteComponents(int n, int[][] edges) { g = new List[n]; vis = new boolean[n]; Arrays.setAll(g, k -> new ArrayList<>()); for (int[] e : edges) { int a = e[0], b = e[1]; g[a].add(b); g[b].add(a); } int ans = 0; for (int i = 0; i < n; ++i) { if (!vis[i]) { int[] t = dfs(i); if (t[0] * (t[0] - 1) == t[1]) { ++ans; } } } return ans; } private int[] dfs(int i) { vis[i] = true; int x = 1, y = g[i].size(); for (int j : g[i]) { if (!vis[j]) { int[] t = dfs(j); x += t[0]; y += t[1]; } } return new int[] {x, y}; } }
2,685
Count the Number of Complete Components
Medium
<p>You are given an integer <code>n</code>. There is an <strong>undirected</strong> graph with <code>n</code> vertices, numbered from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> denotes that there exists an <strong>undirected</strong> edge connecting vertices <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code>.</p> <p>Return <em>the number of <strong>complete connected components</strong> of the graph</em>.</p> <p>A <strong>connected component</strong> is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.</p> <p>A connected component is said to be <b>complete</b> if there exists an edge between every pair of its vertices.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2685.Count%20the%20Number%20of%20Complete%20Components/images/screenshot-from-2023-04-11-23-31-23.png" style="width: 671px; height: 270px;" /></strong></p> <pre> <strong>Input:</strong> n = 6, edges = [[0,1],[0,2],[1,2],[3,4]] <strong>Output:</strong> 3 <strong>Explanation:</strong> From the picture above, one can see that all of the components of this graph are complete. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2685.Count%20the%20Number%20of%20Complete%20Components/images/screenshot-from-2023-04-11-23-32-00.png" style="width: 671px; height: 270px;" /></strong></p> <pre> <strong>Input:</strong> n = 6, edges = [[0,1],[0,2],[1,2],[3,4],[3,5]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The component containing vertices 0, 1, and 2 is complete since there is an edge between every pair of two vertices. On the other hand, the component containing vertices 3, 4, and 5 is not complete since there is no edge between vertices 4 and 5. Thus, the number of complete components in this graph is 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>0 &lt;= edges.length &lt;= n * (n - 1) / 2</code></li> <li><code>edges[i].length == 2</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt;= n - 1</code></li> <li><code>a<sub>i</sub> != b<sub>i</sub></code></li> <li>There are no repeated edges.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph
Python
class Solution: def countCompleteComponents(self, n: int, edges: List[List[int]]) -> int: def dfs(i: int) -> (int, int): vis[i] = True x, y = 1, len(g[i]) for j in g[i]: if not vis[j]: a, b = dfs(j) x += a y += b return x, y g = defaultdict(list) for a, b in edges: g[a].append(b) g[b].append(a) vis = [False] * n ans = 0 for i in range(n): if not vis[i]: a, b = dfs(i) ans += a * (a - 1) == b return ans
2,686
Immediate Food Delivery III
Medium
<p>Table: <code>Delivery</code></p> <pre> +-----------------------------+---------+ | Column Name | Type | +-----------------------------+---------+ | delivery_id | int | | customer_id | int | | order_date | date | | customer_pref_delivery_date | date | +-----------------------------+---------+ delivery_id is the column with unique values of this table. Each row contains information about food delivery to a customer that makes an order at some date and specifies a preferred delivery date (on the order date or after it). </pre> <p>If the customer&#39;s preferred delivery date is the same as the order date, then the order is called <strong>immediate,</strong>&nbsp;otherwise, it is <strong>scheduled</strong>.</p> <p>Write a solution&nbsp;to find the percentage of immediate orders on each unique&nbsp;<code>order_date</code>, <strong>rounded to 2 decimal places</strong>.&nbsp;</p> <p>Return <em>the result table ordered by</em> <code>order_date</code> <em>in <strong>ascending</strong> order.</em></p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Delivery table: +-------------+-------------+------------+-----------------------------+ | delivery_id | customer_id | order_date | customer_pref_delivery_date | +-------------+-------------+------------+-----------------------------+ | 1 | 1 | 2019-08-01 | 2019-08-02 | | 2 | 2 | 2019-08-01 | 2019-08-01 | | 3 | 1 | 2019-08-01 | 2019-08-01 | | 4 | 3 | 2019-08-02 | 2019-08-13 | | 5 | 3 | 2019-08-02 | 2019-08-02 | | 6 | 2 | 2019-08-02 | 2019-08-02 | | 7 | 4 | 2019-08-03 | 2019-08-03 | | 8 | 1 | 2019-08-03 | 2019-08-03 | | 9 | 5 | 2019-08-04 | 2019-08-08 | | 10 | 2 | 2019-08-04 | 2019-08-18 | +-------------+-------------+------------+-----------------------------+ <strong>Output:</strong> +------------+----------------------+ | order_date | immediate_percentage | +------------+----------------------+ | 2019-08-01 | 66.67 | | 2019-08-02 | 66.67 | | 2019-08-03 | 100.00 | | 2019-08-04 | 0.00 | +------------+----------------------+ <strong>Explanation:</strong> - On 2019-08-01 there were three orders, out of those, two were immediate and one was scheduled. So, immediate percentage for that date was 66.67. - On 2019-08-02 there were three orders, out of those, two were immediate and one was scheduled. So, immediate percentage for that date was 66.67. - On 2019-08-03 there were two orders, both were immediate. So, the immediate percentage for that date was 100.00. - On 2019-08-04 there were two orders, both were scheduled. So, the immediate percentage for that date was 0.00. order_date is sorted in ascending order. </pre>
Database
SQL
# Write your MySQL query statement below SELECT order_date, ROUND( 100 * SUM(IF(customer_pref_delivery_date = order_date, 1, 0)) / COUNT(*), 2 ) AS immediate_percentage FROM Delivery GROUP BY order_date ORDER BY order_date;
2,687
Bikes Last Time Used
Easy
<p>Table: <code><font face="monospace">Bikes</font></code></p> <pre> +-------------+----------+ | Column Name | Type | +-------------+----------+ | ride_id | int | | bike_number | int | | start_time | datetime | | end_time | datetime | +-------------+----------+ ride_id column contains unique values. Each row contains a ride information that includes ride_id, bike number, start and end time of the ride. It is guaranteed that start_time and end_time are valid datetime values. </pre> <p>Write a solution to find the <strong>last</strong> <strong>time</strong> when each bike was used.</p> <p>Return the result table ordered by the bikes that were <strong>most recently used</strong>.&nbsp;</p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input: </strong><code>Bikes</code> table: +---------+-------------+---------------------+---------------------+ | ride_id | bike_number | start_time | end_time | +---------+-------------+---------------------+---------------------+ | 1 | W00576 | 2012-03-25 11:30:00 | 2012-03-25 12:40:00 | | 2 | W00300 | 2012-03-25 10:30:00 | 2012-03-25 10:50:00 | | 3 | W00455 | 2012-03-26 14:30:00 | 2012-03-26 17:40:00 | | 4 | W00455 | 2012-03-25 12:30:00 | 2012-03-25 13:40:00 | | 5 | W00576 | 2012-03-25 08:10:00 | 2012-03-25 09:10:00 | | 6 | W00576 | 2012-03-28 02:30:00 | 2012-03-28 02:50:00 | +---------+-------------+---------------------+---------------------+ <strong>Output:</strong> +-------------+---------------------+ | bike_number | end_time | +-------------+---------------------+ | W00576 | 2012-03-28 02:50:00 | | W00455 | 2012-03-26 17:40:00 | | W00300 | 2012-03-25 10:50:00 | +-------------+---------------------+ <strong>Explanation:</strong> bike with number W00576 has three rides, out of that, most recent ride is with ride_id 6 which ended on 2012-03-28 02:50:00. bike with number W00300 has only 1 ride so we will include end_time in output directly. bike with number W00455 has two rides, out of that, most recent ride is with ride_id 3 which ended on 2012-03-26 17:40:00. Returning output in order by the bike that were most recently used. </pre> <p>&nbsp;</p>
Database
SQL
# Write your MySQL query statement below SELECT bike_number, MAX(end_time) AS end_time FROM Bikes GROUP BY bike_number ORDER BY end_time DESC;
2,688
Find Active Users
Medium
<p>Table:<font face="monospace">&nbsp;<code>Users</code></font></p> <pre> +-------------+----------+ | Column Name | Type | +-------------+----------+ | user_id | int | | item | varchar | | created_at | datetime | | amount | int | +-------------+----------+ This table may contain duplicate records. Each row includes the user ID, the purchased item, the date of purchase, and the purchase amount. </pre> <p>Write a solution to identify active users. An active user is a user that has made a second purchase <strong>within 7&nbsp;days&nbsp;</strong>of any other of their purchases.</p> <p>For example, if the ending date is May 31, 2023.&nbsp;So any date between May 31, 2023, and June 7, 2023 (inclusive) would be considered &quot;within 7 days&quot; of May 31, 2023.</p> <p>Return&nbsp;a list of&nbsp;<code>user_id</code>&nbsp;which denotes the list of active users&nbsp;in <strong>any order</strong>.</p> <p>The&nbsp;result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input: </strong>Users table: +---------+-------------------+------------+--------+ | user_id | item | created_at | amount | +---------+-------------------+------------+--------+ | 5 | Smart Crock Pot | 2021-09-18 | 698882 | | 6 | Smart Lock | 2021-09-14 | 11487 | | 6 | Smart Thermostat | 2021-09-10 | 674762 | | 8 | Smart Light Strip | 2021-09-29 | 630773 | | 4 | Smart Cat Feeder | 2021-09-02 | 693545 | | 4 | Smart Bed | 2021-09-13 | 170249 | +---------+-------------------+------------+--------+ <strong>Output:</strong> +---------+ | user_id | +---------+ | 6 | +---------+ <strong>Explanation:</strong> - User with user_id 5 has only one transaction, so he is not an active user. - User with user_id 6 has two transaction his first transaction was on 2021-09-10 and second transation was on 2021-09-14. The distance between the first and second transactions date is &lt;= 7 days. So he is an active user. - User with user_id 8 has only one transaction, so he is not an active user. - User with user_id 4 has two transaction his first transaction was on 2021-09-02 and second transation was on 2021-09-13. The distance between the first and second transactions date is &gt; 7 days. So he is not an active user. </pre>
Database
SQL
# Write your MySQL query statement SELECT DISTINCT user_id FROM Users WHERE user_id IN ( SELECT user_id FROM ( SELECT user_id, created_at, LAG(created_at, 1) OVER ( PARTITION BY user_id ORDER BY created_at ) AS prev_created_at FROM Users ) AS t WHERE DATEDIFF(created_at, prev_created_at) <= 7 );
2,689
Extract Kth Character From The Rope Tree
Easy
<p>You are given the <code>root</code> of a binary tree and an integer <code>k</code>. Besides the left and right children, every node of this tree has two other properties, a <strong>string</strong> <code>node.val</code> containing only lowercase English letters (possibly empty) and a non-negative integer <code>node.len</code>. There are two types of nodes in this tree:</p> <ul> <li><strong>Leaf</strong>: These nodes have no children, <code>node.len = 0</code>, and <code>node.val</code> is some <strong>non-empty</strong> string.</li> <li><strong>Internal</strong>: These nodes have at least one child (also at most two children), <code>node.len &gt; 0</code>, and <code>node.val</code> is an <strong>empty</strong> string.</li> </ul> <p>The tree described above is called a <em>Rope</em> binary tree. Now we define <code>S[node]</code> recursively as follows:</p> <ul> <li>If <code>node</code> is some leaf node, <code>S[node] = node.val</code>,</li> <li>Otherwise if <code>node</code> is some internal node, <code>S[node] = concat(S[node.left], S[node.right])</code> and <code>S[node].length = node.len</code>.</li> </ul> <p>Return<em> k-th character of the string</em> <code>S[root]</code>.</p> <p><strong>Note:</strong> If <code>s</code> and <code>p</code> are two strings, <code>concat(s, p)</code> is a string obtained by concatenating <code>p</code> to <code>s</code>. For example, <code>concat(&quot;ab&quot;, &quot;zz&quot;) = &quot;abzz&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> root = [10,4,&quot;abcpoe&quot;,&quot;g&quot;,&quot;rta&quot;], k = 6 <strong>Output:</strong> &quot;b&quot; <strong>Explanation:</strong> In the picture below, we put an integer on internal nodes that represents node.len, and a string on leaf nodes that represents node.val. You can see that S[root] = concat(concat(&quot;g&quot;, &quot;rta&quot;), &quot;abcpoe&quot;) = &quot;grtaabcpoe&quot;. So S[root][5], which represents 6th character of it, is equal to &quot;b&quot;. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2689.Extract%20Kth%20Character%20From%20The%20Rope%20Tree/images/example1.png" style="width: 300px; height: 213px; margin-left: 280px; margin-right: 280px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [12,6,6,&quot;abc&quot;,&quot;efg&quot;,&quot;hij&quot;,&quot;klm&quot;], k = 3 <strong>Output:</strong> &quot;c&quot; <strong>Explanation:</strong> In the picture below, we put an integer on internal nodes that represents node.len, and a string on leaf nodes that represents node.val. You can see that S[root] = concat(concat(&quot;abc&quot;, &quot;efg&quot;), concat(&quot;hij&quot;, &quot;klm&quot;)) = &quot;abcefghijklm&quot;. So S[root][2], which represents the 3rd character of it, is equal to &quot;c&quot;. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2689.Extract%20Kth%20Character%20From%20The%20Rope%20Tree/images/example2.png" style="width: 400px; height: 232px; margin-left: 255px; margin-right: 255px;" /></p> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [&quot;ropetree&quot;], k = 8 <strong>Output:</strong> &quot;e&quot; <strong>Explanation:</strong> In the picture below, we put an integer on internal nodes that represents node.len, and a string on leaf nodes that represents node.val. You can see that S[root] = &quot;ropetree&quot;. So S[root][7], which represents 8th character of it, is equal to &quot;e&quot;. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2689.Extract%20Kth%20Character%20From%20The%20Rope%20Tree/images/example3.png" style="width: 80px; height: 78px; margin-left: 400px; margin-right: 400px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>3</sup>]</code></li> <li><code>node.val</code> contains only lowercase English letters</li> <li><code>0 &lt;= node.val.length &lt;= 50</code></li> <li><code>0 &lt;= node.len &lt;= 10<sup>4</sup></code></li> <li>for leaf nodes, <code>node.len = 0</code> and <code>node.val</code> is non-empty</li> <li>for internal nodes, <code>node.len &gt; 0</code> and <code>node.val</code> is empty</li> <li><code>1 &lt;= k &lt;= S[root].length</code></li> </ul>
Tree; Depth-First Search; Binary Tree
C++
/** * Definition for a rope tree node. * struct RopeTreeNode { * int len; * string val; * RopeTreeNode *left; * RopeTreeNode *right; * RopeTreeNode() : len(0), val(""), left(nullptr), right(nullptr) {} * RopeTreeNode(string s) : len(0), val(std::move(s)), left(nullptr), right(nullptr) {} * RopeTreeNode(int x) : len(x), val(""), left(nullptr), right(nullptr) {} * RopeTreeNode(int x, RopeTreeNode *left, RopeTreeNode *right) : len(x), val(""), left(left), right(right) {} * }; */ class Solution { public: char getKthCharacter(RopeTreeNode* root, int k) { function<string(RopeTreeNode * root)> dfs = [&](RopeTreeNode* root) -> string { if (root == nullptr) { return ""; } if (root->len == 0) { return root->val; } string left = dfs(root->left); string right = dfs(root->right); return left + right; }; return dfs(root)[k - 1]; } };
2,689
Extract Kth Character From The Rope Tree
Easy
<p>You are given the <code>root</code> of a binary tree and an integer <code>k</code>. Besides the left and right children, every node of this tree has two other properties, a <strong>string</strong> <code>node.val</code> containing only lowercase English letters (possibly empty) and a non-negative integer <code>node.len</code>. There are two types of nodes in this tree:</p> <ul> <li><strong>Leaf</strong>: These nodes have no children, <code>node.len = 0</code>, and <code>node.val</code> is some <strong>non-empty</strong> string.</li> <li><strong>Internal</strong>: These nodes have at least one child (also at most two children), <code>node.len &gt; 0</code>, and <code>node.val</code> is an <strong>empty</strong> string.</li> </ul> <p>The tree described above is called a <em>Rope</em> binary tree. Now we define <code>S[node]</code> recursively as follows:</p> <ul> <li>If <code>node</code> is some leaf node, <code>S[node] = node.val</code>,</li> <li>Otherwise if <code>node</code> is some internal node, <code>S[node] = concat(S[node.left], S[node.right])</code> and <code>S[node].length = node.len</code>.</li> </ul> <p>Return<em> k-th character of the string</em> <code>S[root]</code>.</p> <p><strong>Note:</strong> If <code>s</code> and <code>p</code> are two strings, <code>concat(s, p)</code> is a string obtained by concatenating <code>p</code> to <code>s</code>. For example, <code>concat(&quot;ab&quot;, &quot;zz&quot;) = &quot;abzz&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> root = [10,4,&quot;abcpoe&quot;,&quot;g&quot;,&quot;rta&quot;], k = 6 <strong>Output:</strong> &quot;b&quot; <strong>Explanation:</strong> In the picture below, we put an integer on internal nodes that represents node.len, and a string on leaf nodes that represents node.val. You can see that S[root] = concat(concat(&quot;g&quot;, &quot;rta&quot;), &quot;abcpoe&quot;) = &quot;grtaabcpoe&quot;. So S[root][5], which represents 6th character of it, is equal to &quot;b&quot;. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2689.Extract%20Kth%20Character%20From%20The%20Rope%20Tree/images/example1.png" style="width: 300px; height: 213px; margin-left: 280px; margin-right: 280px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [12,6,6,&quot;abc&quot;,&quot;efg&quot;,&quot;hij&quot;,&quot;klm&quot;], k = 3 <strong>Output:</strong> &quot;c&quot; <strong>Explanation:</strong> In the picture below, we put an integer on internal nodes that represents node.len, and a string on leaf nodes that represents node.val. You can see that S[root] = concat(concat(&quot;abc&quot;, &quot;efg&quot;), concat(&quot;hij&quot;, &quot;klm&quot;)) = &quot;abcefghijklm&quot;. So S[root][2], which represents the 3rd character of it, is equal to &quot;c&quot;. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2689.Extract%20Kth%20Character%20From%20The%20Rope%20Tree/images/example2.png" style="width: 400px; height: 232px; margin-left: 255px; margin-right: 255px;" /></p> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [&quot;ropetree&quot;], k = 8 <strong>Output:</strong> &quot;e&quot; <strong>Explanation:</strong> In the picture below, we put an integer on internal nodes that represents node.len, and a string on leaf nodes that represents node.val. You can see that S[root] = &quot;ropetree&quot;. So S[root][7], which represents 8th character of it, is equal to &quot;e&quot;. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2689.Extract%20Kth%20Character%20From%20The%20Rope%20Tree/images/example3.png" style="width: 80px; height: 78px; margin-left: 400px; margin-right: 400px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>3</sup>]</code></li> <li><code>node.val</code> contains only lowercase English letters</li> <li><code>0 &lt;= node.val.length &lt;= 50</code></li> <li><code>0 &lt;= node.len &lt;= 10<sup>4</sup></code></li> <li>for leaf nodes, <code>node.len = 0</code> and <code>node.val</code> is non-empty</li> <li>for internal nodes, <code>node.len &gt; 0</code> and <code>node.val</code> is empty</li> <li><code>1 &lt;= k &lt;= S[root].length</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Go
/** * Definition for a rope tree node. * type RopeTreeNode struct { * len int * val string * left *RopeTreeNode * right *RopeTreeNode * } */ func getKthCharacter(root *RopeTreeNode, k int) byte { var dfs func(root *RopeTreeNode) string dfs = func(root *RopeTreeNode) string { if root == nil { return "" } if root.len == 0 { return root.val } left, right := dfs(root.left), dfs(root.right) return left + right } return dfs(root)[k-1] }
2,689
Extract Kth Character From The Rope Tree
Easy
<p>You are given the <code>root</code> of a binary tree and an integer <code>k</code>. Besides the left and right children, every node of this tree has two other properties, a <strong>string</strong> <code>node.val</code> containing only lowercase English letters (possibly empty) and a non-negative integer <code>node.len</code>. There are two types of nodes in this tree:</p> <ul> <li><strong>Leaf</strong>: These nodes have no children, <code>node.len = 0</code>, and <code>node.val</code> is some <strong>non-empty</strong> string.</li> <li><strong>Internal</strong>: These nodes have at least one child (also at most two children), <code>node.len &gt; 0</code>, and <code>node.val</code> is an <strong>empty</strong> string.</li> </ul> <p>The tree described above is called a <em>Rope</em> binary tree. Now we define <code>S[node]</code> recursively as follows:</p> <ul> <li>If <code>node</code> is some leaf node, <code>S[node] = node.val</code>,</li> <li>Otherwise if <code>node</code> is some internal node, <code>S[node] = concat(S[node.left], S[node.right])</code> and <code>S[node].length = node.len</code>.</li> </ul> <p>Return<em> k-th character of the string</em> <code>S[root]</code>.</p> <p><strong>Note:</strong> If <code>s</code> and <code>p</code> are two strings, <code>concat(s, p)</code> is a string obtained by concatenating <code>p</code> to <code>s</code>. For example, <code>concat(&quot;ab&quot;, &quot;zz&quot;) = &quot;abzz&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> root = [10,4,&quot;abcpoe&quot;,&quot;g&quot;,&quot;rta&quot;], k = 6 <strong>Output:</strong> &quot;b&quot; <strong>Explanation:</strong> In the picture below, we put an integer on internal nodes that represents node.len, and a string on leaf nodes that represents node.val. You can see that S[root] = concat(concat(&quot;g&quot;, &quot;rta&quot;), &quot;abcpoe&quot;) = &quot;grtaabcpoe&quot;. So S[root][5], which represents 6th character of it, is equal to &quot;b&quot;. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2689.Extract%20Kth%20Character%20From%20The%20Rope%20Tree/images/example1.png" style="width: 300px; height: 213px; margin-left: 280px; margin-right: 280px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [12,6,6,&quot;abc&quot;,&quot;efg&quot;,&quot;hij&quot;,&quot;klm&quot;], k = 3 <strong>Output:</strong> &quot;c&quot; <strong>Explanation:</strong> In the picture below, we put an integer on internal nodes that represents node.len, and a string on leaf nodes that represents node.val. You can see that S[root] = concat(concat(&quot;abc&quot;, &quot;efg&quot;), concat(&quot;hij&quot;, &quot;klm&quot;)) = &quot;abcefghijklm&quot;. So S[root][2], which represents the 3rd character of it, is equal to &quot;c&quot;. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2689.Extract%20Kth%20Character%20From%20The%20Rope%20Tree/images/example2.png" style="width: 400px; height: 232px; margin-left: 255px; margin-right: 255px;" /></p> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [&quot;ropetree&quot;], k = 8 <strong>Output:</strong> &quot;e&quot; <strong>Explanation:</strong> In the picture below, we put an integer on internal nodes that represents node.len, and a string on leaf nodes that represents node.val. You can see that S[root] = &quot;ropetree&quot;. So S[root][7], which represents 8th character of it, is equal to &quot;e&quot;. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2689.Extract%20Kth%20Character%20From%20The%20Rope%20Tree/images/example3.png" style="width: 80px; height: 78px; margin-left: 400px; margin-right: 400px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>3</sup>]</code></li> <li><code>node.val</code> contains only lowercase English letters</li> <li><code>0 &lt;= node.val.length &lt;= 50</code></li> <li><code>0 &lt;= node.len &lt;= 10<sup>4</sup></code></li> <li>for leaf nodes, <code>node.len = 0</code> and <code>node.val</code> is non-empty</li> <li>for internal nodes, <code>node.len &gt; 0</code> and <code>node.val</code> is empty</li> <li><code>1 &lt;= k &lt;= S[root].length</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Java
/** * Definition for a rope tree node. * class RopeTreeNode { * int len; * String val; * RopeTreeNode left; * RopeTreeNode right; * RopeTreeNode() {} * RopeTreeNode(String val) { * this.len = 0; * this.val = val; * } * RopeTreeNode(int len) { * this.len = len; * this.val = ""; * } * RopeTreeNode(int len, TreeNode left, TreeNode right) { * this.len = len; * this.val = ""; * this.left = left; * this.right = right; * } * } */ class Solution { public char getKthCharacter(RopeTreeNode root, int k) { return dfs(root).charAt(k - 1); } private String dfs(RopeTreeNode root) { if (root == null) { return ""; } if (root.val.length() > 0) { return root.val; } String left = dfs(root.left); String right = dfs(root.right); return left + right; } }
2,689
Extract Kth Character From The Rope Tree
Easy
<p>You are given the <code>root</code> of a binary tree and an integer <code>k</code>. Besides the left and right children, every node of this tree has two other properties, a <strong>string</strong> <code>node.val</code> containing only lowercase English letters (possibly empty) and a non-negative integer <code>node.len</code>. There are two types of nodes in this tree:</p> <ul> <li><strong>Leaf</strong>: These nodes have no children, <code>node.len = 0</code>, and <code>node.val</code> is some <strong>non-empty</strong> string.</li> <li><strong>Internal</strong>: These nodes have at least one child (also at most two children), <code>node.len &gt; 0</code>, and <code>node.val</code> is an <strong>empty</strong> string.</li> </ul> <p>The tree described above is called a <em>Rope</em> binary tree. Now we define <code>S[node]</code> recursively as follows:</p> <ul> <li>If <code>node</code> is some leaf node, <code>S[node] = node.val</code>,</li> <li>Otherwise if <code>node</code> is some internal node, <code>S[node] = concat(S[node.left], S[node.right])</code> and <code>S[node].length = node.len</code>.</li> </ul> <p>Return<em> k-th character of the string</em> <code>S[root]</code>.</p> <p><strong>Note:</strong> If <code>s</code> and <code>p</code> are two strings, <code>concat(s, p)</code> is a string obtained by concatenating <code>p</code> to <code>s</code>. For example, <code>concat(&quot;ab&quot;, &quot;zz&quot;) = &quot;abzz&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> root = [10,4,&quot;abcpoe&quot;,&quot;g&quot;,&quot;rta&quot;], k = 6 <strong>Output:</strong> &quot;b&quot; <strong>Explanation:</strong> In the picture below, we put an integer on internal nodes that represents node.len, and a string on leaf nodes that represents node.val. You can see that S[root] = concat(concat(&quot;g&quot;, &quot;rta&quot;), &quot;abcpoe&quot;) = &quot;grtaabcpoe&quot;. So S[root][5], which represents 6th character of it, is equal to &quot;b&quot;. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2689.Extract%20Kth%20Character%20From%20The%20Rope%20Tree/images/example1.png" style="width: 300px; height: 213px; margin-left: 280px; margin-right: 280px;" /></p> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [12,6,6,&quot;abc&quot;,&quot;efg&quot;,&quot;hij&quot;,&quot;klm&quot;], k = 3 <strong>Output:</strong> &quot;c&quot; <strong>Explanation:</strong> In the picture below, we put an integer on internal nodes that represents node.len, and a string on leaf nodes that represents node.val. You can see that S[root] = concat(concat(&quot;abc&quot;, &quot;efg&quot;), concat(&quot;hij&quot;, &quot;klm&quot;)) = &quot;abcefghijklm&quot;. So S[root][2], which represents the 3rd character of it, is equal to &quot;c&quot;. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2689.Extract%20Kth%20Character%20From%20The%20Rope%20Tree/images/example2.png" style="width: 400px; height: 232px; margin-left: 255px; margin-right: 255px;" /></p> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [&quot;ropetree&quot;], k = 8 <strong>Output:</strong> &quot;e&quot; <strong>Explanation:</strong> In the picture below, we put an integer on internal nodes that represents node.len, and a string on leaf nodes that represents node.val. You can see that S[root] = &quot;ropetree&quot;. So S[root][7], which represents 8th character of it, is equal to &quot;e&quot;. </pre> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2689.Extract%20Kth%20Character%20From%20The%20Rope%20Tree/images/example3.png" style="width: 80px; height: 78px; margin-left: 400px; margin-right: 400px;" /></p> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>3</sup>]</code></li> <li><code>node.val</code> contains only lowercase English letters</li> <li><code>0 &lt;= node.val.length &lt;= 50</code></li> <li><code>0 &lt;= node.len &lt;= 10<sup>4</sup></code></li> <li>for leaf nodes, <code>node.len = 0</code> and <code>node.val</code> is non-empty</li> <li>for internal nodes, <code>node.len &gt; 0</code> and <code>node.val</code> is empty</li> <li><code>1 &lt;= k &lt;= S[root].length</code></li> </ul>
Tree; Depth-First Search; Binary Tree
Python
# Definition for a rope tree node. # class RopeTreeNode(object): # def __init__(self, len=0, val="", left=None, right=None): # self.len = len # self.val = val # self.left = left # self.right = right class Solution: def getKthCharacter(self, root: Optional[object], k: int) -> str: def dfs(root): if root is None: return "" if root.len == 0: return root.val return dfs(root.left) + dfs(root.right) return dfs(root)[k - 1]
2,690
Infinite Method Object
Easy
<p>Write a function that&nbsp;returns an&nbsp;<strong>infinite-method</strong><strong>&nbsp;object</strong>.</p> <p>An&nbsp;<strong>infinite-method</strong><strong>&nbsp;object</strong>&nbsp;is defined as an object that allows you to call any method and it will always return the name of the method.</p> <p>For example, if you execute&nbsp;<code>obj.abc123()</code>, it will return&nbsp;<code>&quot;abc123&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> method = &quot;abc123&quot; <strong>Output:</strong> &quot;abc123&quot; <strong>Explanation:</strong> const obj = createInfiniteObject(); obj[&#39;abc123&#39;](); // &quot;abc123&quot; The returned string should always match the method name.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> method = &quot;.-qw73n|^2It&quot; <strong>Output:</strong> &quot;.-qw73n|^2It&quot; <strong>Explanation:</strong> The returned string should always match the method name.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= method.length &lt;= 1000</code></li> </ul>
JavaScript
TypeScript
function createInfiniteObject(): Record<string, () => string> { return new Proxy( {}, { get: (_, prop) => () => prop.toString(), }, ); } /** * const obj = createInfiniteObject(); * obj['abc123'](); // "abc123" */
2,692
Make Object Immutable
Medium
<p>Write a function that takes an object&nbsp;<code>obj</code> and returns a new&nbsp;<strong>immutable</strong>&nbsp;version of this object.</p> <p>An&nbsp;<strong>immutable&nbsp;</strong>object is an object that can&#39;t be altered and will throw an error if any attempt is made to alter it.</p> <p>There are three types of error messages that can be produced from this new object.</p> <ul> <li>Attempting to modify a key on the object will result in this&nbsp;error message: <code>`Error Modifying: ${key}`</code>.</li> <li>Attempting to modify an index on an array will result in this error message: <code>`Error Modifying&nbsp;Index: ${index}`</code>.</li> <li>Attempting to call a method that mutates an array will result in this error message: <code>`Error Calling Method: ${methodName}`</code>. You may assume the only methods that can mutate&nbsp;an array are&nbsp;<code>[&#39;pop&#39;, &#39;push&#39;, &#39;shift&#39;, &#39;unshift&#39;, &#39;splice&#39;, &#39;sort&#39;, &#39;reverse&#39;]</code>.</li> </ul> <p><code>obj</code>&nbsp;is a valid JSON object or array, meaning it is the output of <code>JSON.parse()</code>.</p> <p>Note that a string literal should be thrown, not an&nbsp;<code>Error</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> obj = { &nbsp; &quot;x&quot;: 5 } fn = (obj) =&gt; { &nbsp; obj.x = 5; &nbsp; return obj.x; } <strong>Output:</strong> {&quot;value&quot;: null, &quot;error&quot;: &quot;Error Modifying:&nbsp;x&quot;} <strong>Explanation: </strong>Attempting to modify a key on an object resuts in a thrown error. Note that it doesn&#39;t matter that the value was set to the same value as it was before. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> obj = [1, 2, 3] fn = (arr) =&gt; { &nbsp; arr[1] = {}; &nbsp; return arr[2]; } <strong>Output:</strong> {&quot;value&quot;: null, &quot;error&quot;: &quot;Error Modifying&nbsp;Index: 1&quot;} <strong>Explanation: </strong>Attempting to modify an array results in a thrown error. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> obj = { &nbsp; &quot;arr&quot;: [1, 2, 3] } fn = (obj) =&gt; { &nbsp; obj.arr.push(4); &nbsp; return 42; } <strong>Output:</strong> { &quot;value&quot;: null, &quot;error&quot;: &quot;Error Calling Method: push&quot;} <strong>Explanation: </strong>Calling a method that can result in a mutation results in a thrown error. </pre> <p><strong class="example">Example 4:</strong></p> <pre> <strong>Input:</strong> obj = { &nbsp; &quot;x&quot;: 2, &nbsp; &quot;y&quot;: 2 } fn = (obj) =&gt; { &nbsp; return Object.keys(obj); } <strong>Output:</strong> {&quot;value&quot;: [&quot;x&quot;, &quot;y&quot;], &quot;error&quot;: null} <strong>Explanation: </strong>No mutations were attempted so the function returns as normal. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>obj</code>&nbsp;is a valid JSON object or array</li> <li><code>2 &lt;= JSON.stringify(obj).length &lt;= 10<sup>5</sup></code></li> </ul>
JavaScript
TypeScript
type Obj = Array<any> | Record<any, any>; function makeImmutable(obj: Obj): Obj { const arrayHandler: ProxyHandler<Array<any>> = { set: (_, prop) => { throw `Error Modifying Index: ${String(prop)}`; }, }; const objectHandler: ProxyHandler<Record<any, any>> = { set: (_, prop) => { throw `Error Modifying: ${String(prop)}`; }, }; const fnHandler: ProxyHandler<Function> = { apply: target => { throw `Error Calling Method: ${target.name}`; }, }; const fn = ['pop', 'push', 'shift', 'unshift', 'splice', 'sort', 'reverse']; const dfs = (obj: Obj) => { for (const key in obj) { if (typeof obj[key] === 'object' && obj[key] !== null) { obj[key] = dfs(obj[key]); } } if (Array.isArray(obj)) { fn.forEach(f => (obj[f] = new Proxy(obj[f], fnHandler))); return new Proxy(obj, arrayHandler); } return new Proxy(obj, objectHandler); }; return dfs(obj); } /** * const obj = makeImmutable({x: 5}); * obj.x = 6; // throws "Error Modifying x" */
2,693
Call Function with Custom Context
Medium
<p>Enhance all functions to have the&nbsp;<code>callPolyfill</code>&nbsp;method. The method accepts an object&nbsp;<code>obj</code>&nbsp;as its first parameter and any number of additional arguments. The&nbsp;<code>obj</code>&nbsp;becomes the&nbsp;<code>this</code>&nbsp;context for the function. The additional arguments are passed to the function (that the <code>callPolyfill</code>&nbsp;method belongs on).</p> <p>For example if you had the function:</p> <pre> function tax(price, taxRate) { const totalCost = price * (1 + taxRate); &nbsp; console.log(`The cost of ${this.item} is ${totalCost}`); } </pre> <p>Calling this function like&nbsp;<code>tax(10, 0.1)</code>&nbsp;will log&nbsp;<code>&quot;The cost of undefined is 11&quot;</code>. This is because the&nbsp;<code>this</code>&nbsp;context was not defined.</p> <p>However, calling the function like&nbsp;<code>tax.callPolyfill({item: &quot;salad&quot;}, 10, 0.1)</code>&nbsp;will log&nbsp;<code>&quot;The cost of salad is 11&quot;</code>. The&nbsp;<code>this</code>&nbsp;context was appropriately set, and the function logged an appropriate output.</p> <p>Please solve this without using&nbsp;the built-in&nbsp;<code>Function.call</code>&nbsp;method.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> fn = function add(b) { return this.a + b; } args = [{&quot;a&quot;: 5}, 7] <strong>Output:</strong> 12 <strong>Explanation:</strong> fn.callPolyfill({&quot;a&quot;: 5}, 7); // 12 callPolyfill sets the &quot;this&quot; context to {&quot;a&quot;: 5}. 7 is passed as an argument. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> fn = function tax(price, taxRate) { &nbsp;return `The cost of the ${this.item} is ${price * taxRate}`; } args = [{&quot;item&quot;: &quot;burger&quot;}, 10, 1.1] <strong>Output:</strong> &quot;The cost of the burger is 11&quot; <strong>Explanation:</strong> callPolyfill sets the &quot;this&quot; context to {&quot;item&quot;: &quot;burger&quot;}. 10 and 1.1 are passed as additional arguments. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code><font face="monospace">typeof args[0] == &#39;object&#39; and args[0] != null</font></code></li> <li><code>1 &lt;= args.length &lt;= 100</code></li> <li><code>2 &lt;= JSON.stringify(args[0]).length &lt;= 10<sup>5</sup></code></li> </ul>
JavaScript
TypeScript
declare global { interface Function { callPolyfill(context: Record<any, any>, ...args: any[]): any; } } Function.prototype.callPolyfill = function (context, ...args): any { const fn = this.bind(context); return fn(...args); }; /** * function increment() { this.count++; return this.count; } * increment.callPolyfill({count: 1}); // 2 */
2,694
Event Emitter
Medium
<p>Design an <code>EventEmitter</code> class. This interface&nbsp;is similar (but with some differences) to the one found in Node.js or the Event Target interface of the DOM. The <code>EventEmitter</code> should allow for subscribing to events and emitting them.</p> <p>Your <code>EventEmitter</code> class should have the following two methods:</p> <ul> <li><strong>subscribe</strong> - This method takes in two arguments: the name of an event as a string and a callback function. This callback function&nbsp;will later be called when the event is emitted.<br /> An event should be able to have multiple listeners for the same event. When emitting an event with multiple callbacks, each should be called in the order in which they were subscribed. An array of results should be returned. You can assume no callbacks passed to&nbsp;<code>subscribe</code>&nbsp;are referentially identical.<br /> The <code>subscribe</code> method should also return an object with an <code>unsubscribe</code>&nbsp;method that enables the user to unsubscribe. When it is called, the callback&nbsp;should be removed from the list of subscriptions and&nbsp;<code>undefined</code>&nbsp;should be returned.</li> <li><strong>emit</strong> - This method takes in two arguments: the name of an event as a string and an optional array of arguments that will be&nbsp;passed to the callback(s). If there are no callbacks subscribed to the given event, return an empty array. Otherwise, return an array of the results of all callback calls in the order they were subscribed.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> actions = [&quot;EventEmitter&quot;, &quot;emit&quot;, &quot;subscribe&quot;, &quot;subscribe&quot;, &quot;emit&quot;], values = [[], [&quot;firstEvent&quot;], [&quot;firstEvent&quot;, &quot;function cb1() { return 5; }&quot;],&nbsp; [&quot;firstEvent&quot;, &quot;function cb1() { return 6; }&quot;], [&quot;firstEvent&quot;]] <strong>Output:</strong> [[],[&quot;emitted&quot;,[]],[&quot;subscribed&quot;],[&quot;subscribed&quot;],[&quot;emitted&quot;,[5,6]]] <strong>Explanation:</strong> const emitter = new EventEmitter(); emitter.emit(&quot;firstEvent&quot;); // [], no callback are subscribed yet emitter.subscribe(&quot;firstEvent&quot;, function cb1() { return 5; }); emitter.subscribe(&quot;firstEvent&quot;, function cb2() { return 6; }); emitter.emit(&quot;firstEvent&quot;); // [5, 6], returns the output of cb1 and cb2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> actions = [&quot;EventEmitter&quot;, &quot;subscribe&quot;, &quot;emit&quot;, &quot;emit&quot;], values = [[], [&quot;firstEvent&quot;, &quot;function cb1(...args) { return args.join(&#39;,&#39;); }&quot;], [&quot;firstEvent&quot;, [1,2,3]], [&quot;firstEvent&quot;, [3,4,6]]] <strong>Output:</strong> [[],[&quot;subscribed&quot;],[&quot;emitted&quot;,[&quot;1,2,3&quot;]],[&quot;emitted&quot;,[&quot;3,4,6&quot;]]] <strong>Explanation: </strong>Note that the emit method should be able to accept an OPTIONAL array of arguments. const emitter = new EventEmitter(); emitter.subscribe(&quot;firstEvent, function cb1(...args) { return args.join(&#39;,&#39;); }); emitter.emit(&quot;firstEvent&quot;, [1, 2, 3]); // [&quot;1,2,3&quot;] emitter.emit(&quot;firstEvent&quot;, [3, 4, 6]); // [&quot;3,4,6&quot;] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> actions = [&quot;EventEmitter&quot;, &quot;subscribe&quot;, &quot;emit&quot;, &quot;unsubscribe&quot;, &quot;emit&quot;], values = [[], [&quot;firstEvent&quot;, &quot;(...args) =&gt; args.join(&#39;,&#39;)&quot;], [&quot;firstEvent&quot;, [1,2,3]], [0], [&quot;firstEvent&quot;, [4,5,6]]] <strong>Output:</strong> [[],[&quot;subscribed&quot;],[&quot;emitted&quot;,[&quot;1,2,3&quot;]],[&quot;unsubscribed&quot;,0],[&quot;emitted&quot;,[]]] <strong>Explanation:</strong> const emitter = new EventEmitter(); const sub = emitter.subscribe(&quot;firstEvent&quot;, (...args) =&gt; args.join(&#39;,&#39;)); emitter.emit(&quot;firstEvent&quot;, [1, 2, 3]); // [&quot;1,2,3&quot;] sub.unsubscribe(); // undefined emitter.emit(&quot;firstEvent&quot;, [4, 5, 6]); // [], there are no subscriptions </pre> <p><strong class="example">Example 4:</strong></p> <pre> <strong>Input:</strong> actions = [&quot;EventEmitter&quot;, &quot;subscribe&quot;, &quot;subscribe&quot;, &quot;unsubscribe&quot;, &quot;emit&quot;], values = [[], [&quot;firstEvent&quot;, &quot;x =&gt; x + 1&quot;], [&quot;firstEvent&quot;, &quot;x =&gt; x + 2&quot;], [0], [&quot;firstEvent&quot;, [5]]] <strong>Output:</strong> [[],[&quot;subscribed&quot;],[&quot;subscribed&quot;],[&quot;unsubscribed&quot;,0],[&quot;emitted&quot;,[7]]] <strong>Explanation:</strong> const emitter = new EventEmitter(); const sub1 = emitter.subscribe(&quot;firstEvent&quot;, x =&gt; x + 1); const sub2 = emitter.subscribe(&quot;firstEvent&quot;, x =&gt; x + 2); sub1.unsubscribe(); // undefined emitter.emit(&quot;firstEvent&quot;, [5]); // [7]</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= actions.length &lt;= 10</code></li> <li><code>values.length === actions.length</code></li> <li>All test cases are valid, e.g. you don&#39;t need to handle scenarios when unsubscribing from a non-existing subscription.</li> <li>There are only 4 different actions: <code>EventEmitter</code>, <code>emit</code>, <code>subscribe</code>, and <code>unsubscribe</code>.</li> <li>The <code>EventEmitter</code> action doesn&#39;t take any arguments.</li> <li>The <code>emit</code>&nbsp;action takes between either 1 or&nbsp;2&nbsp;arguments. The first argument is the name of the event we want to emit, and the 2nd argument is passed to the callback functions.</li> <li>The <code>subscribe</code> action takes 2 arguments, where the first one is the event name and the second is the callback function.</li> <li>The <code>unsubscribe</code>&nbsp;action takes one argument, which is the 0-indexed order of the subscription made before.</li> </ul>
JavaScript
TypeScript
type Callback = (...args: any[]) => any; type Subscription = { unsubscribe: () => void; }; class EventEmitter { private d: Map<string, Set<Callback>> = new Map(); subscribe(eventName: string, callback: Callback): Subscription { this.d.set(eventName, (this.d.get(eventName) || new Set()).add(callback)); return { unsubscribe: () => { this.d.get(eventName)?.delete(callback); }, }; } emit(eventName: string, args: any[] = []): any { const callbacks = this.d.get(eventName); if (!callbacks) { return []; } return [...callbacks].map(callback => callback(...args)); } } /** * const emitter = new EventEmitter(); * * // Subscribe to the onClick event with onClickCallback * function onClickCallback() { return 99 } * const sub = emitter.subscribe('onClick', onClickCallback); * * emitter.emit('onClick'); // [99] * sub.unsubscribe(); // undefined * emitter.emit('onClick'); // [] */
2,695
Array Wrapper
Easy
<p>Create a class&nbsp;<code>ArrayWrapper</code> that accepts&nbsp;an array of integers in its constructor. This class should have two features:</p> <ul> <li>When two instances of this class are added together with the&nbsp;<code>+</code>&nbsp;operator, the resulting value is the sum of all the elements in&nbsp;both arrays.</li> <li>When the&nbsp;<code>String()</code>&nbsp;function is called on the instance, it will return a comma separated string surrounded by brackets. For example, <code>[1,2,3]</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [[1,2],[3,4]], operation = &quot;Add&quot; <strong>Output:</strong> 10 <strong>Explanation:</strong> const obj1 = new ArrayWrapper([1,2]); const obj2 = new ArrayWrapper([3,4]); obj1 + obj2; // 10 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [[23,98,42,70]], operation = &quot;String&quot; <strong>Output:</strong> &quot;[23,98,42,70]&quot; <strong>Explanation:</strong> const obj = new ArrayWrapper([23,98,42,70]); String(obj); // &quot;[23,98,42,70]&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [[],[]], operation = &quot;Add&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> const obj1 = new ArrayWrapper([]); const obj2 = new ArrayWrapper([]); obj1 + obj2; // 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 1000</code></li> <li><code>0 &lt;= nums[i]&nbsp;&lt;= 1000</code></li> <li><code>Note: nums is the array passed to the constructor</code></li> </ul>
JavaScript
TypeScript
class ArrayWrapper { private nums: number[]; private s: number; constructor(nums: number[]) { this.nums = nums; this.s = nums.reduce((a, b) => a + b, 0); } valueOf() { return this.s; } toString() { return `[${this.nums}]`; } } /** * const obj1 = new ArrayWrapper([1,2]); * const obj2 = new ArrayWrapper([3,4]); * obj1 + obj2; // 10 * String(obj1); // "[1,2]" * String(obj2); // "[3,4]" */
2,696
Minimum String Length After Removing Substrings
Easy
<p>You are given a string <code>s</code> consisting only of <strong>uppercase</strong> English letters.</p> <p>You can apply some operations to this string where, in one operation, you can remove <strong>any</strong> occurrence of one of the substrings <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> from <code>s</code>.</p> <p>Return <em>the <strong>minimum</strong> possible length of the resulting string that you can obtain</em>.</p> <p><strong>Note</strong> that the string concatenates after removing the substring and could produce new <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> substrings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ABFCACDB&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can do the following operations: - Remove the substring &quot;<u>AB</u>FCACDB&quot;, so s = &quot;FCACDB&quot;. - Remove the substring &quot;FCA<u>CD</u>B&quot;, so s = &quot;FCAB&quot;. - Remove the substring &quot;FC<u>AB</u>&quot;, so s = &quot;FC&quot;. So the resulting length of the string is 2. It can be shown that it is the minimum length that we can obtain.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ACBBD&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> We cannot do any operations on the string so the length remains the same. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code>&nbsp;consists only of uppercase English letters.</li> </ul>
Stack; String; Simulation
C++
class Solution { public: int minLength(string s) { string stk = " "; for (char& c : s) { if ((c == 'B' && stk.back() == 'A') || (c == 'D' && stk.back() == 'C')) { stk.pop_back(); } else { stk.push_back(c); } } return stk.size() - 1; } };
2,696
Minimum String Length After Removing Substrings
Easy
<p>You are given a string <code>s</code> consisting only of <strong>uppercase</strong> English letters.</p> <p>You can apply some operations to this string where, in one operation, you can remove <strong>any</strong> occurrence of one of the substrings <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> from <code>s</code>.</p> <p>Return <em>the <strong>minimum</strong> possible length of the resulting string that you can obtain</em>.</p> <p><strong>Note</strong> that the string concatenates after removing the substring and could produce new <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> substrings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ABFCACDB&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can do the following operations: - Remove the substring &quot;<u>AB</u>FCACDB&quot;, so s = &quot;FCACDB&quot;. - Remove the substring &quot;FCA<u>CD</u>B&quot;, so s = &quot;FCAB&quot;. - Remove the substring &quot;FC<u>AB</u>&quot;, so s = &quot;FC&quot;. So the resulting length of the string is 2. It can be shown that it is the minimum length that we can obtain.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ACBBD&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> We cannot do any operations on the string so the length remains the same. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code>&nbsp;consists only of uppercase English letters.</li> </ul>
Stack; String; Simulation
Go
func minLength(s string) int { stk := []byte{' '} for _, c := range s { if (c == 'B' && stk[len(stk)-1] == 'A') || (c == 'D' && stk[len(stk)-1] == 'C') { stk = stk[:len(stk)-1] } else { stk = append(stk, byte(c)) } } return len(stk) - 1 }
2,696
Minimum String Length After Removing Substrings
Easy
<p>You are given a string <code>s</code> consisting only of <strong>uppercase</strong> English letters.</p> <p>You can apply some operations to this string where, in one operation, you can remove <strong>any</strong> occurrence of one of the substrings <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> from <code>s</code>.</p> <p>Return <em>the <strong>minimum</strong> possible length of the resulting string that you can obtain</em>.</p> <p><strong>Note</strong> that the string concatenates after removing the substring and could produce new <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> substrings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ABFCACDB&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can do the following operations: - Remove the substring &quot;<u>AB</u>FCACDB&quot;, so s = &quot;FCACDB&quot;. - Remove the substring &quot;FCA<u>CD</u>B&quot;, so s = &quot;FCAB&quot;. - Remove the substring &quot;FC<u>AB</u>&quot;, so s = &quot;FC&quot;. So the resulting length of the string is 2. It can be shown that it is the minimum length that we can obtain.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ACBBD&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> We cannot do any operations on the string so the length remains the same. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code>&nbsp;consists only of uppercase English letters.</li> </ul>
Stack; String; Simulation
Java
class Solution { public int minLength(String s) { Deque<Character> stk = new ArrayDeque<>(); stk.push(' '); for (char c : s.toCharArray()) { if ((c == 'B' && stk.peek() == 'A') || (c == 'D' && stk.peek() == 'C')) { stk.pop(); } else { stk.push(c); } } return stk.size() - 1; } }
2,696
Minimum String Length After Removing Substrings
Easy
<p>You are given a string <code>s</code> consisting only of <strong>uppercase</strong> English letters.</p> <p>You can apply some operations to this string where, in one operation, you can remove <strong>any</strong> occurrence of one of the substrings <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> from <code>s</code>.</p> <p>Return <em>the <strong>minimum</strong> possible length of the resulting string that you can obtain</em>.</p> <p><strong>Note</strong> that the string concatenates after removing the substring and could produce new <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> substrings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ABFCACDB&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can do the following operations: - Remove the substring &quot;<u>AB</u>FCACDB&quot;, so s = &quot;FCACDB&quot;. - Remove the substring &quot;FCA<u>CD</u>B&quot;, so s = &quot;FCAB&quot;. - Remove the substring &quot;FC<u>AB</u>&quot;, so s = &quot;FC&quot;. So the resulting length of the string is 2. It can be shown that it is the minimum length that we can obtain.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ACBBD&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> We cannot do any operations on the string so the length remains the same. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code>&nbsp;consists only of uppercase English letters.</li> </ul>
Stack; String; Simulation
JavaScript
function minLength(s) { const stk = []; for (const c of s) { if ((stk.at(-1) === 'A' && c === 'B') || (stk.at(-1) === 'C' && c === 'D')) { stk.pop(); } else { stk.push(c); } } return stk.length; }
2,696
Minimum String Length After Removing Substrings
Easy
<p>You are given a string <code>s</code> consisting only of <strong>uppercase</strong> English letters.</p> <p>You can apply some operations to this string where, in one operation, you can remove <strong>any</strong> occurrence of one of the substrings <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> from <code>s</code>.</p> <p>Return <em>the <strong>minimum</strong> possible length of the resulting string that you can obtain</em>.</p> <p><strong>Note</strong> that the string concatenates after removing the substring and could produce new <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> substrings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ABFCACDB&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can do the following operations: - Remove the substring &quot;<u>AB</u>FCACDB&quot;, so s = &quot;FCACDB&quot;. - Remove the substring &quot;FCA<u>CD</u>B&quot;, so s = &quot;FCAB&quot;. - Remove the substring &quot;FC<u>AB</u>&quot;, so s = &quot;FC&quot;. So the resulting length of the string is 2. It can be shown that it is the minimum length that we can obtain.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ACBBD&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> We cannot do any operations on the string so the length remains the same. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code>&nbsp;consists only of uppercase English letters.</li> </ul>
Stack; String; Simulation
Python
class Solution: def minLength(self, s: str) -> int: stk = [""] for c in s: if (c == "B" and stk[-1] == "A") or (c == "D" and stk[-1] == "C"): stk.pop() else: stk.append(c) return len(stk) - 1
2,696
Minimum String Length After Removing Substrings
Easy
<p>You are given a string <code>s</code> consisting only of <strong>uppercase</strong> English letters.</p> <p>You can apply some operations to this string where, in one operation, you can remove <strong>any</strong> occurrence of one of the substrings <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> from <code>s</code>.</p> <p>Return <em>the <strong>minimum</strong> possible length of the resulting string that you can obtain</em>.</p> <p><strong>Note</strong> that the string concatenates after removing the substring and could produce new <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> substrings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ABFCACDB&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can do the following operations: - Remove the substring &quot;<u>AB</u>FCACDB&quot;, so s = &quot;FCACDB&quot;. - Remove the substring &quot;FCA<u>CD</u>B&quot;, so s = &quot;FCAB&quot;. - Remove the substring &quot;FC<u>AB</u>&quot;, so s = &quot;FC&quot;. So the resulting length of the string is 2. It can be shown that it is the minimum length that we can obtain.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ACBBD&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> We cannot do any operations on the string so the length remains the same. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code>&nbsp;consists only of uppercase English letters.</li> </ul>
Stack; String; Simulation
Rust
impl Solution { pub fn min_length(s: String) -> i32 { let mut ans: Vec<u8> = Vec::new(); for c in s.bytes() { if let Some(last) = ans.last() { if *last == b'A' && c == b'B' { ans.pop(); } else if *last == b'C' && c == b'D' { ans.pop(); } else { ans.push(c); } } else { ans.push(c); } } ans.len() as i32 } }
2,696
Minimum String Length After Removing Substrings
Easy
<p>You are given a string <code>s</code> consisting only of <strong>uppercase</strong> English letters.</p> <p>You can apply some operations to this string where, in one operation, you can remove <strong>any</strong> occurrence of one of the substrings <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> from <code>s</code>.</p> <p>Return <em>the <strong>minimum</strong> possible length of the resulting string that you can obtain</em>.</p> <p><strong>Note</strong> that the string concatenates after removing the substring and could produce new <code>&quot;AB&quot;</code> or <code>&quot;CD&quot;</code> substrings.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ABFCACDB&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> We can do the following operations: - Remove the substring &quot;<u>AB</u>FCACDB&quot;, so s = &quot;FCACDB&quot;. - Remove the substring &quot;FCA<u>CD</u>B&quot;, so s = &quot;FCAB&quot;. - Remove the substring &quot;FC<u>AB</u>&quot;, so s = &quot;FC&quot;. So the resulting length of the string is 2. It can be shown that it is the minimum length that we can obtain.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ACBBD&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> We cannot do any operations on the string so the length remains the same. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 100</code></li> <li><code>s</code>&nbsp;consists only of uppercase English letters.</li> </ul>
Stack; String; Simulation
TypeScript
function minLength(s: string): number { const stk: string[] = []; for (const c of s) { if ((stk.at(-1) === 'A' && c === 'B') || (stk.at(-1) === 'C' && c === 'D')) { stk.pop(); } else { stk.push(c); } } return stk.length; }
2,697
Lexicographically Smallest Palindrome
Easy
<p>You are given a string <code node="[object Object]">s</code> consisting of <strong>lowercase English letters</strong>, and you are allowed to perform operations on it. In one operation, you can <strong>replace</strong> a character in <code node="[object Object]">s</code> with another lowercase English letter.</p> <p>Your task is to make <code node="[object Object]">s</code> a <strong>palindrome</strong> with the <strong>minimum</strong> <strong>number</strong> <strong>of operations</strong> possible. If there are <strong>multiple palindromes</strong> that can be <meta charset="utf-8" />made using the <strong>minimum</strong> number of operations, <meta charset="utf-8" />make the <strong>lexicographically smallest</strong> one.</p> <p>A string <code>a</code> is lexicographically smaller than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.</p> <p>Return <em>the resulting palindrome string.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;egcfe&quot; <strong>Output:</strong> &quot;efcfe&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;egcfe&quot; a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is &quot;efcfe&quot;, by changing &#39;g&#39;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot; <strong>Output:</strong> &quot;abba&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;abcd&quot; a palindrome is 2, and the lexicographically smallest palindrome string we can get by modifying two characters is &quot;abba&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;seven&quot; <strong>Output:</strong> &quot;neven&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;seven&quot; a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is &quot;neven&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code>&nbsp;consists of only lowercase English letters<b>.</b></li> </ul>
Greedy; Two Pointers; String
C++
class Solution { public: string makeSmallestPalindrome(string s) { for (int i = 0, j = s.size() - 1; i < j; ++i, --j) { s[i] = s[j] = min(s[i], s[j]); } return s; } };
2,697
Lexicographically Smallest Palindrome
Easy
<p>You are given a string <code node="[object Object]">s</code> consisting of <strong>lowercase English letters</strong>, and you are allowed to perform operations on it. In one operation, you can <strong>replace</strong> a character in <code node="[object Object]">s</code> with another lowercase English letter.</p> <p>Your task is to make <code node="[object Object]">s</code> a <strong>palindrome</strong> with the <strong>minimum</strong> <strong>number</strong> <strong>of operations</strong> possible. If there are <strong>multiple palindromes</strong> that can be <meta charset="utf-8" />made using the <strong>minimum</strong> number of operations, <meta charset="utf-8" />make the <strong>lexicographically smallest</strong> one.</p> <p>A string <code>a</code> is lexicographically smaller than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.</p> <p>Return <em>the resulting palindrome string.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;egcfe&quot; <strong>Output:</strong> &quot;efcfe&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;egcfe&quot; a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is &quot;efcfe&quot;, by changing &#39;g&#39;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot; <strong>Output:</strong> &quot;abba&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;abcd&quot; a palindrome is 2, and the lexicographically smallest palindrome string we can get by modifying two characters is &quot;abba&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;seven&quot; <strong>Output:</strong> &quot;neven&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;seven&quot; a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is &quot;neven&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code>&nbsp;consists of only lowercase English letters<b>.</b></li> </ul>
Greedy; Two Pointers; String
Go
func makeSmallestPalindrome(s string) string { cs := []byte(s) for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { cs[i] = min(cs[i], cs[j]) cs[j] = cs[i] } return string(cs) }
2,697
Lexicographically Smallest Palindrome
Easy
<p>You are given a string <code node="[object Object]">s</code> consisting of <strong>lowercase English letters</strong>, and you are allowed to perform operations on it. In one operation, you can <strong>replace</strong> a character in <code node="[object Object]">s</code> with another lowercase English letter.</p> <p>Your task is to make <code node="[object Object]">s</code> a <strong>palindrome</strong> with the <strong>minimum</strong> <strong>number</strong> <strong>of operations</strong> possible. If there are <strong>multiple palindromes</strong> that can be <meta charset="utf-8" />made using the <strong>minimum</strong> number of operations, <meta charset="utf-8" />make the <strong>lexicographically smallest</strong> one.</p> <p>A string <code>a</code> is lexicographically smaller than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.</p> <p>Return <em>the resulting palindrome string.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;egcfe&quot; <strong>Output:</strong> &quot;efcfe&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;egcfe&quot; a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is &quot;efcfe&quot;, by changing &#39;g&#39;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot; <strong>Output:</strong> &quot;abba&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;abcd&quot; a palindrome is 2, and the lexicographically smallest palindrome string we can get by modifying two characters is &quot;abba&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;seven&quot; <strong>Output:</strong> &quot;neven&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;seven&quot; a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is &quot;neven&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code>&nbsp;consists of only lowercase English letters<b>.</b></li> </ul>
Greedy; Two Pointers; String
Java
class Solution { public String makeSmallestPalindrome(String s) { char[] cs = s.toCharArray(); for (int i = 0, j = cs.length - 1; i < j; ++i, --j) { cs[i] = cs[j] = (char) Math.min(cs[i], cs[j]); } return new String(cs); } }
2,697
Lexicographically Smallest Palindrome
Easy
<p>You are given a string <code node="[object Object]">s</code> consisting of <strong>lowercase English letters</strong>, and you are allowed to perform operations on it. In one operation, you can <strong>replace</strong> a character in <code node="[object Object]">s</code> with another lowercase English letter.</p> <p>Your task is to make <code node="[object Object]">s</code> a <strong>palindrome</strong> with the <strong>minimum</strong> <strong>number</strong> <strong>of operations</strong> possible. If there are <strong>multiple palindromes</strong> that can be <meta charset="utf-8" />made using the <strong>minimum</strong> number of operations, <meta charset="utf-8" />make the <strong>lexicographically smallest</strong> one.</p> <p>A string <code>a</code> is lexicographically smaller than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.</p> <p>Return <em>the resulting palindrome string.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;egcfe&quot; <strong>Output:</strong> &quot;efcfe&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;egcfe&quot; a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is &quot;efcfe&quot;, by changing &#39;g&#39;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot; <strong>Output:</strong> &quot;abba&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;abcd&quot; a palindrome is 2, and the lexicographically smallest palindrome string we can get by modifying two characters is &quot;abba&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;seven&quot; <strong>Output:</strong> &quot;neven&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;seven&quot; a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is &quot;neven&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code>&nbsp;consists of only lowercase English letters<b>.</b></li> </ul>
Greedy; Two Pointers; String
Python
class Solution: def makeSmallestPalindrome(self, s: str) -> str: cs = list(s) i, j = 0, len(s) - 1 while i < j: cs[i] = cs[j] = min(cs[i], cs[j]) i, j = i + 1, j - 1 return "".join(cs)
2,697
Lexicographically Smallest Palindrome
Easy
<p>You are given a string <code node="[object Object]">s</code> consisting of <strong>lowercase English letters</strong>, and you are allowed to perform operations on it. In one operation, you can <strong>replace</strong> a character in <code node="[object Object]">s</code> with another lowercase English letter.</p> <p>Your task is to make <code node="[object Object]">s</code> a <strong>palindrome</strong> with the <strong>minimum</strong> <strong>number</strong> <strong>of operations</strong> possible. If there are <strong>multiple palindromes</strong> that can be <meta charset="utf-8" />made using the <strong>minimum</strong> number of operations, <meta charset="utf-8" />make the <strong>lexicographically smallest</strong> one.</p> <p>A string <code>a</code> is lexicographically smaller than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.</p> <p>Return <em>the resulting palindrome string.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;egcfe&quot; <strong>Output:</strong> &quot;efcfe&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;egcfe&quot; a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is &quot;efcfe&quot;, by changing &#39;g&#39;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot; <strong>Output:</strong> &quot;abba&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;abcd&quot; a palindrome is 2, and the lexicographically smallest palindrome string we can get by modifying two characters is &quot;abba&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;seven&quot; <strong>Output:</strong> &quot;neven&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;seven&quot; a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is &quot;neven&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code>&nbsp;consists of only lowercase English letters<b>.</b></li> </ul>
Greedy; Two Pointers; String
Rust
impl Solution { pub fn make_smallest_palindrome(s: String) -> String { let mut cs: Vec<char> = s.chars().collect(); let n = cs.len(); for i in 0..n / 2 { let j = n - 1 - i; cs[i] = std::cmp::min(cs[i], cs[j]); cs[j] = cs[i]; } cs.into_iter().collect() } }
2,697
Lexicographically Smallest Palindrome
Easy
<p>You are given a string <code node="[object Object]">s</code> consisting of <strong>lowercase English letters</strong>, and you are allowed to perform operations on it. In one operation, you can <strong>replace</strong> a character in <code node="[object Object]">s</code> with another lowercase English letter.</p> <p>Your task is to make <code node="[object Object]">s</code> a <strong>palindrome</strong> with the <strong>minimum</strong> <strong>number</strong> <strong>of operations</strong> possible. If there are <strong>multiple palindromes</strong> that can be <meta charset="utf-8" />made using the <strong>minimum</strong> number of operations, <meta charset="utf-8" />make the <strong>lexicographically smallest</strong> one.</p> <p>A string <code>a</code> is lexicographically smaller than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, string <code>a</code> has a letter that appears earlier in the alphabet than the corresponding letter in <code>b</code>.</p> <p>Return <em>the resulting palindrome string.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;egcfe&quot; <strong>Output:</strong> &quot;efcfe&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;egcfe&quot; a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is &quot;efcfe&quot;, by changing &#39;g&#39;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot; <strong>Output:</strong> &quot;abba&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;abcd&quot; a palindrome is 2, and the lexicographically smallest palindrome string we can get by modifying two characters is &quot;abba&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;seven&quot; <strong>Output:</strong> &quot;neven&quot; <strong>Explanation:</strong> The minimum number of operations to make &quot;seven&quot; a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is &quot;neven&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code>&nbsp;consists of only lowercase English letters<b>.</b></li> </ul>
Greedy; Two Pointers; String
TypeScript
function makeSmallestPalindrome(s: string): string { const cs = s.split(''); for (let i = 0, j = s.length - 1; i < j; ++i, --j) { cs[i] = cs[j] = s[i] < s[j] ? s[i] : s[j]; } return cs.join(''); }
2,698
Find the Punishment Number of an Integer
Medium
<p>Given a positive integer <code>n</code>, return <em>the <strong>punishment number</strong></em> of <code>n</code>.</p> <p>The <strong>punishment number</strong> of <code>n</code> is defined as the sum of the squares of all integers <code>i</code> such that:</p> <ul> <li><code>1 &lt;= i &lt;= n</code></li> <li>The decimal representation of <code>i * i</code> can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals <code>i</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 182 <strong>Explanation:</strong> There are exactly 3 integers i in the range [1, 10] that satisfy the conditions in the statement: - 1 since 1 * 1 = 1 - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 and 1 with a sum equal to 8 + 1 == 9. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 and 0 with a sum equal to 10 + 0 == 10. Hence, the punishment number of 10 is 1 + 81 + 100 = 182 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 37 <strong>Output:</strong> 1478 <strong>Explanation:</strong> There are exactly 4 integers i in the range [1, 37] that satisfy the conditions in the statement: - 1 since 1 * 1 = 1. - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. - 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6. Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Math; Backtracking
C++
class Solution { public: int punishmentNumber(int n) { int ans = 0; for (int i = 1; i <= n; ++i) { int x = i * i; string s = to_string(x); if (check(s, 0, i)) { ans += x; } } return ans; } bool check(const string& s, int i, int x) { int m = s.size(); if (i >= m) { return x == 0; } int y = 0; for (int j = i; j < m; ++j) { y = y * 10 + s[j] - '0'; if (y > x) { break; } if (check(s, j + 1, x - y)) { return true; } } return false; } };
2,698
Find the Punishment Number of an Integer
Medium
<p>Given a positive integer <code>n</code>, return <em>the <strong>punishment number</strong></em> of <code>n</code>.</p> <p>The <strong>punishment number</strong> of <code>n</code> is defined as the sum of the squares of all integers <code>i</code> such that:</p> <ul> <li><code>1 &lt;= i &lt;= n</code></li> <li>The decimal representation of <code>i * i</code> can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals <code>i</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 182 <strong>Explanation:</strong> There are exactly 3 integers i in the range [1, 10] that satisfy the conditions in the statement: - 1 since 1 * 1 = 1 - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 and 1 with a sum equal to 8 + 1 == 9. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 and 0 with a sum equal to 10 + 0 == 10. Hence, the punishment number of 10 is 1 + 81 + 100 = 182 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 37 <strong>Output:</strong> 1478 <strong>Explanation:</strong> There are exactly 4 integers i in the range [1, 37] that satisfy the conditions in the statement: - 1 since 1 * 1 = 1. - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. - 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6. Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Math; Backtracking
Go
func punishmentNumber(n int) (ans int) { var check func(string, int, int) bool check = func(s string, i, x int) bool { m := len(s) if i >= m { return x == 0 } y := 0 for j := i; j < m; j++ { y = y*10 + int(s[j]-'0') if y > x { break } if check(s, j+1, x-y) { return true } } return false } for i := 1; i <= n; i++ { x := i * i s := strconv.Itoa(x) if check(s, 0, i) { ans += x } } return }
2,698
Find the Punishment Number of an Integer
Medium
<p>Given a positive integer <code>n</code>, return <em>the <strong>punishment number</strong></em> of <code>n</code>.</p> <p>The <strong>punishment number</strong> of <code>n</code> is defined as the sum of the squares of all integers <code>i</code> such that:</p> <ul> <li><code>1 &lt;= i &lt;= n</code></li> <li>The decimal representation of <code>i * i</code> can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals <code>i</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 182 <strong>Explanation:</strong> There are exactly 3 integers i in the range [1, 10] that satisfy the conditions in the statement: - 1 since 1 * 1 = 1 - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 and 1 with a sum equal to 8 + 1 == 9. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 and 0 with a sum equal to 10 + 0 == 10. Hence, the punishment number of 10 is 1 + 81 + 100 = 182 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 37 <strong>Output:</strong> 1478 <strong>Explanation:</strong> There are exactly 4 integers i in the range [1, 37] that satisfy the conditions in the statement: - 1 since 1 * 1 = 1. - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. - 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6. Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Math; Backtracking
Java
class Solution { public int punishmentNumber(int n) { int ans = 0; for (int i = 1; i <= n; ++i) { int x = i * i; if (check(x + "", 0, i)) { ans += x; } } return ans; } private boolean check(String s, int i, int x) { int m = s.length(); if (i >= m) { return x == 0; } int y = 0; for (int j = i; j < m; ++j) { y = y * 10 + (s.charAt(j) - '0'); if (y > x) { break; } if (check(s, j + 1, x - y)) { return true; } } return false; } }
2,698
Find the Punishment Number of an Integer
Medium
<p>Given a positive integer <code>n</code>, return <em>the <strong>punishment number</strong></em> of <code>n</code>.</p> <p>The <strong>punishment number</strong> of <code>n</code> is defined as the sum of the squares of all integers <code>i</code> such that:</p> <ul> <li><code>1 &lt;= i &lt;= n</code></li> <li>The decimal representation of <code>i * i</code> can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals <code>i</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 182 <strong>Explanation:</strong> There are exactly 3 integers i in the range [1, 10] that satisfy the conditions in the statement: - 1 since 1 * 1 = 1 - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 and 1 with a sum equal to 8 + 1 == 9. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 and 0 with a sum equal to 10 + 0 == 10. Hence, the punishment number of 10 is 1 + 81 + 100 = 182 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 37 <strong>Output:</strong> 1478 <strong>Explanation:</strong> There are exactly 4 integers i in the range [1, 37] that satisfy the conditions in the statement: - 1 since 1 * 1 = 1. - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. - 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6. Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Math; Backtracking
Python
class Solution: def punishmentNumber(self, n: int) -> int: def check(s: str, i: int, x: int) -> bool: m = len(s) if i >= m: return x == 0 y = 0 for j in range(i, m): y = y * 10 + int(s[j]) if y > x: break if check(s, j + 1, x - y): return True return False ans = 0 for i in range(1, n + 1): x = i * i if check(str(x), 0, i): ans += x return ans
2,698
Find the Punishment Number of an Integer
Medium
<p>Given a positive integer <code>n</code>, return <em>the <strong>punishment number</strong></em> of <code>n</code>.</p> <p>The <strong>punishment number</strong> of <code>n</code> is defined as the sum of the squares of all integers <code>i</code> such that:</p> <ul> <li><code>1 &lt;= i &lt;= n</code></li> <li>The decimal representation of <code>i * i</code> can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals <code>i</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 182 <strong>Explanation:</strong> There are exactly 3 integers i in the range [1, 10] that satisfy the conditions in the statement: - 1 since 1 * 1 = 1 - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 and 1 with a sum equal to 8 + 1 == 9. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 and 0 with a sum equal to 10 + 0 == 10. Hence, the punishment number of 10 is 1 + 81 + 100 = 182 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 37 <strong>Output:</strong> 1478 <strong>Explanation:</strong> There are exactly 4 integers i in the range [1, 37] that satisfy the conditions in the statement: - 1 since 1 * 1 = 1. - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. - 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6. Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Math; Backtracking
TypeScript
function punishmentNumber(n: number): number { const check = (s: string, i: number, x: number): boolean => { const m = s.length; if (i >= m) { return x === 0; } let y = 0; for (let j = i; j < m; ++j) { y = y * 10 + Number(s[j]); if (y > x) { break; } if (check(s, j + 1, x - y)) { return true; } } return false; }; let ans = 0; for (let i = 1; i <= n; ++i) { const x = i * i; const s = x.toString(); if (check(s, 0, i)) { ans += x; } } return ans; }
2,699
Modify Graph Edge Weights
Hard
<p>You are given an <strong>undirected weighted</strong> <strong>connected</strong> graph containing <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and an integer array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, w<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> with weight <code>w<sub>i</sub></code>.</p> <p>Some edges have a weight of <code>-1</code> (<code>w<sub>i</sub> = -1</code>), while others have a <strong>positive</strong> weight (<code>w<sub>i</sub> &gt; 0</code>).</p> <p>Your task is to modify <strong>all edges</strong> with a weight of <code>-1</code> by assigning them <strong>positive integer values </strong>in the range <code>[1, 2 * 10<sup>9</sup>]</code> so that the <strong>shortest distance</strong> between the nodes <code>source</code> and <code>destination</code> becomes equal to an integer <code>target</code>. If there are <strong>multiple</strong> <strong>modifications</strong> that make the shortest distance between <code>source</code> and <code>destination</code> equal to <code>target</code>, any of them will be considered correct.</p> <p>Return <em>an array containing all edges (even unmodified ones) in any order if it is possible to make the shortest distance from </em><code>source</code><em> to </em><code>destination</code><em> equal to </em><code>target</code><em>, or an <strong>empty array</strong> if it&#39;s impossible.</em></p> <p><strong>Note:</strong> You are not allowed to modify the weights of edges with initial positive weights.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 5, edges = [[4,1,-1],[2,0,-1],[0,3,-1],[4,3,-1]], source = 0, destination = 1, target = 5 <strong>Output:</strong> [[4,1,1],[2,0,1],[0,3,3],[4,3,1]] <strong>Explanation:</strong> The graph above shows a possible modification to the edges, making the distance from 0 to 1 equal to 5. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph-2.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 3, edges = [[0,1,-1],[0,2,5]], source = 0, destination = 2, target = 6 <strong>Output:</strong> [] <strong>Explanation:</strong> The graph above contains the initial edges. It is not possible to make the distance from 0 to 2 equal to 6 by modifying the edge with weight -1. So, an empty array is returned. </pre> <p><strong class="example">Example 3:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph-3.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 4, edges = [[1,0,4],[1,2,3],[2,3,5],[0,3,-1]], source = 0, destination = 2, target = 6 <strong>Output:</strong> [[1,0,4],[1,2,3],[2,3,5],[0,3,1]] <strong>Explanation:</strong> The graph above shows a modified graph having the shortest distance from 0 to 2 as 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code><font face="monospace">1 &lt;= edges.length &lt;= n * (n - 1) / 2</font></code></li> <li><code>edges[i].length == 3</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i&nbsp;</sub>&lt;&nbsp;n</code></li> <li><code><font face="monospace">w<sub>i</sub>&nbsp;= -1&nbsp;</font></code>or <code><font face="monospace">1 &lt;= w<sub>i&nbsp;</sub>&lt;= 10<sup><span style="font-size: 10.8333px;">7</span></sup></font></code></li> <li><code>a<sub>i&nbsp;</sub>!=&nbsp;b<sub>i</sub></code></li> <li><code>0 &lt;= source, destination &lt; n</code></li> <li><code>source != destination</code></li> <li><code><font face="monospace">1 &lt;= target &lt;= 10<sup>9</sup></font></code></li> <li>The graph is connected, and there are no self-loops or repeated edges</li> </ul>
Graph; Shortest Path; Heap (Priority Queue)
C++
using ll = long long; const int inf = 2e9; class Solution { public: vector<vector<int>> modifiedGraphEdges(int n, vector<vector<int>>& edges, int source, int destination, int target) { ll d = dijkstra(edges, n, source, destination); if (d < target) { return {}; } bool ok = d == target; for (auto& e : edges) { if (e[2] > 0) { continue; } if (ok) { e[2] = inf; continue; } e[2] = 1; d = dijkstra(edges, n, source, destination); if (d <= target) { ok = true; e[2] += target - d; } } return ok ? edges : vector<vector<int>>{}; } ll dijkstra(vector<vector<int>>& edges, int n, int src, int dest) { ll g[n][n]; ll dist[n]; bool vis[n]; for (int i = 0; i < n; ++i) { fill(g[i], g[i] + n, inf); dist[i] = inf; vis[i] = false; } dist[src] = 0; for (auto& e : edges) { int a = e[0], b = e[1], w = e[2]; if (w == -1) { continue; } g[a][b] = w; g[b][a] = w; } for (int i = 0; i < n; ++i) { int k = -1; for (int j = 0; j < n; ++j) { if (!vis[j] && (k == -1 || dist[j] < dist[k])) { k = j; } } vis[k] = true; for (int j = 0; j < n; ++j) { dist[j] = min(dist[j], dist[k] + g[k][j]); } } return dist[dest]; } };
2,699
Modify Graph Edge Weights
Hard
<p>You are given an <strong>undirected weighted</strong> <strong>connected</strong> graph containing <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and an integer array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, w<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> with weight <code>w<sub>i</sub></code>.</p> <p>Some edges have a weight of <code>-1</code> (<code>w<sub>i</sub> = -1</code>), while others have a <strong>positive</strong> weight (<code>w<sub>i</sub> &gt; 0</code>).</p> <p>Your task is to modify <strong>all edges</strong> with a weight of <code>-1</code> by assigning them <strong>positive integer values </strong>in the range <code>[1, 2 * 10<sup>9</sup>]</code> so that the <strong>shortest distance</strong> between the nodes <code>source</code> and <code>destination</code> becomes equal to an integer <code>target</code>. If there are <strong>multiple</strong> <strong>modifications</strong> that make the shortest distance between <code>source</code> and <code>destination</code> equal to <code>target</code>, any of them will be considered correct.</p> <p>Return <em>an array containing all edges (even unmodified ones) in any order if it is possible to make the shortest distance from </em><code>source</code><em> to </em><code>destination</code><em> equal to </em><code>target</code><em>, or an <strong>empty array</strong> if it&#39;s impossible.</em></p> <p><strong>Note:</strong> You are not allowed to modify the weights of edges with initial positive weights.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 5, edges = [[4,1,-1],[2,0,-1],[0,3,-1],[4,3,-1]], source = 0, destination = 1, target = 5 <strong>Output:</strong> [[4,1,1],[2,0,1],[0,3,3],[4,3,1]] <strong>Explanation:</strong> The graph above shows a possible modification to the edges, making the distance from 0 to 1 equal to 5. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph-2.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 3, edges = [[0,1,-1],[0,2,5]], source = 0, destination = 2, target = 6 <strong>Output:</strong> [] <strong>Explanation:</strong> The graph above contains the initial edges. It is not possible to make the distance from 0 to 2 equal to 6 by modifying the edge with weight -1. So, an empty array is returned. </pre> <p><strong class="example">Example 3:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph-3.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 4, edges = [[1,0,4],[1,2,3],[2,3,5],[0,3,-1]], source = 0, destination = 2, target = 6 <strong>Output:</strong> [[1,0,4],[1,2,3],[2,3,5],[0,3,1]] <strong>Explanation:</strong> The graph above shows a modified graph having the shortest distance from 0 to 2 as 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code><font face="monospace">1 &lt;= edges.length &lt;= n * (n - 1) / 2</font></code></li> <li><code>edges[i].length == 3</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i&nbsp;</sub>&lt;&nbsp;n</code></li> <li><code><font face="monospace">w<sub>i</sub>&nbsp;= -1&nbsp;</font></code>or <code><font face="monospace">1 &lt;= w<sub>i&nbsp;</sub>&lt;= 10<sup><span style="font-size: 10.8333px;">7</span></sup></font></code></li> <li><code>a<sub>i&nbsp;</sub>!=&nbsp;b<sub>i</sub></code></li> <li><code>0 &lt;= source, destination &lt; n</code></li> <li><code>source != destination</code></li> <li><code><font face="monospace">1 &lt;= target &lt;= 10<sup>9</sup></font></code></li> <li>The graph is connected, and there are no self-loops or repeated edges</li> </ul>
Graph; Shortest Path; Heap (Priority Queue)
Go
func modifiedGraphEdges(n int, edges [][]int, source int, destination int, target int) [][]int { const inf int = 2e9 dijkstra := func(edges [][]int) int { g := make([][]int, n) dist := make([]int, n) vis := make([]bool, n) for i := range g { g[i] = make([]int, n) for j := range g[i] { g[i][j] = inf } dist[i] = inf } dist[source] = 0 for _, e := range edges { a, b, w := e[0], e[1], e[2] if w == -1 { continue } g[a][b], g[b][a] = w, w } for i := 0; i < n; i++ { k := -1 for j := 0; j < n; j++ { if !vis[j] && (k == -1 || dist[j] < dist[k]) { k = j } } vis[k] = true for j := 0; j < n; j++ { dist[j] = min(dist[j], dist[k]+g[k][j]) } } return dist[destination] } d := dijkstra(edges) if d < target { return [][]int{} } ok := d == target for _, e := range edges { if e[2] > 0 { continue } if ok { e[2] = inf continue } e[2] = 1 d := dijkstra(edges) if d <= target { ok = true e[2] += target - d } } if ok { return edges } return [][]int{} }
2,699
Modify Graph Edge Weights
Hard
<p>You are given an <strong>undirected weighted</strong> <strong>connected</strong> graph containing <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and an integer array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, w<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> with weight <code>w<sub>i</sub></code>.</p> <p>Some edges have a weight of <code>-1</code> (<code>w<sub>i</sub> = -1</code>), while others have a <strong>positive</strong> weight (<code>w<sub>i</sub> &gt; 0</code>).</p> <p>Your task is to modify <strong>all edges</strong> with a weight of <code>-1</code> by assigning them <strong>positive integer values </strong>in the range <code>[1, 2 * 10<sup>9</sup>]</code> so that the <strong>shortest distance</strong> between the nodes <code>source</code> and <code>destination</code> becomes equal to an integer <code>target</code>. If there are <strong>multiple</strong> <strong>modifications</strong> that make the shortest distance between <code>source</code> and <code>destination</code> equal to <code>target</code>, any of them will be considered correct.</p> <p>Return <em>an array containing all edges (even unmodified ones) in any order if it is possible to make the shortest distance from </em><code>source</code><em> to </em><code>destination</code><em> equal to </em><code>target</code><em>, or an <strong>empty array</strong> if it&#39;s impossible.</em></p> <p><strong>Note:</strong> You are not allowed to modify the weights of edges with initial positive weights.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 5, edges = [[4,1,-1],[2,0,-1],[0,3,-1],[4,3,-1]], source = 0, destination = 1, target = 5 <strong>Output:</strong> [[4,1,1],[2,0,1],[0,3,3],[4,3,1]] <strong>Explanation:</strong> The graph above shows a possible modification to the edges, making the distance from 0 to 1 equal to 5. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph-2.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 3, edges = [[0,1,-1],[0,2,5]], source = 0, destination = 2, target = 6 <strong>Output:</strong> [] <strong>Explanation:</strong> The graph above contains the initial edges. It is not possible to make the distance from 0 to 2 equal to 6 by modifying the edge with weight -1. So, an empty array is returned. </pre> <p><strong class="example">Example 3:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph-3.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 4, edges = [[1,0,4],[1,2,3],[2,3,5],[0,3,-1]], source = 0, destination = 2, target = 6 <strong>Output:</strong> [[1,0,4],[1,2,3],[2,3,5],[0,3,1]] <strong>Explanation:</strong> The graph above shows a modified graph having the shortest distance from 0 to 2 as 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code><font face="monospace">1 &lt;= edges.length &lt;= n * (n - 1) / 2</font></code></li> <li><code>edges[i].length == 3</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i&nbsp;</sub>&lt;&nbsp;n</code></li> <li><code><font face="monospace">w<sub>i</sub>&nbsp;= -1&nbsp;</font></code>or <code><font face="monospace">1 &lt;= w<sub>i&nbsp;</sub>&lt;= 10<sup><span style="font-size: 10.8333px;">7</span></sup></font></code></li> <li><code>a<sub>i&nbsp;</sub>!=&nbsp;b<sub>i</sub></code></li> <li><code>0 &lt;= source, destination &lt; n</code></li> <li><code>source != destination</code></li> <li><code><font face="monospace">1 &lt;= target &lt;= 10<sup>9</sup></font></code></li> <li>The graph is connected, and there are no self-loops or repeated edges</li> </ul>
Graph; Shortest Path; Heap (Priority Queue)
Java
class Solution { private final int inf = 2000000000; public int[][] modifiedGraphEdges( int n, int[][] edges, int source, int destination, int target) { long d = dijkstra(edges, n, source, destination); if (d < target) { return new int[0][]; } boolean ok = d == target; for (var e : edges) { if (e[2] > 0) { continue; } if (ok) { e[2] = inf; continue; } e[2] = 1; d = dijkstra(edges, n, source, destination); if (d <= target) { ok = true; e[2] += target - d; } } return ok ? edges : new int[0][]; } private long dijkstra(int[][] edges, int n, int src, int dest) { int[][] g = new int[n][n]; long[] dist = new long[n]; Arrays.fill(dist, inf); dist[src] = 0; for (var f : g) { Arrays.fill(f, inf); } for (var e : edges) { int a = e[0], b = e[1], w = e[2]; if (w == -1) { continue; } g[a][b] = w; g[b][a] = w; } boolean[] vis = new boolean[n]; for (int i = 0; i < n; ++i) { int k = -1; for (int j = 0; j < n; ++j) { if (!vis[j] && (k == -1 || dist[k] > dist[j])) { k = j; } } vis[k] = true; for (int j = 0; j < n; ++j) { dist[j] = Math.min(dist[j], dist[k] + g[k][j]); } } return dist[dest]; } }
2,699
Modify Graph Edge Weights
Hard
<p>You are given an <strong>undirected weighted</strong> <strong>connected</strong> graph containing <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and an integer array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, w<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> with weight <code>w<sub>i</sub></code>.</p> <p>Some edges have a weight of <code>-1</code> (<code>w<sub>i</sub> = -1</code>), while others have a <strong>positive</strong> weight (<code>w<sub>i</sub> &gt; 0</code>).</p> <p>Your task is to modify <strong>all edges</strong> with a weight of <code>-1</code> by assigning them <strong>positive integer values </strong>in the range <code>[1, 2 * 10<sup>9</sup>]</code> so that the <strong>shortest distance</strong> between the nodes <code>source</code> and <code>destination</code> becomes equal to an integer <code>target</code>. If there are <strong>multiple</strong> <strong>modifications</strong> that make the shortest distance between <code>source</code> and <code>destination</code> equal to <code>target</code>, any of them will be considered correct.</p> <p>Return <em>an array containing all edges (even unmodified ones) in any order if it is possible to make the shortest distance from </em><code>source</code><em> to </em><code>destination</code><em> equal to </em><code>target</code><em>, or an <strong>empty array</strong> if it&#39;s impossible.</em></p> <p><strong>Note:</strong> You are not allowed to modify the weights of edges with initial positive weights.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 5, edges = [[4,1,-1],[2,0,-1],[0,3,-1],[4,3,-1]], source = 0, destination = 1, target = 5 <strong>Output:</strong> [[4,1,1],[2,0,1],[0,3,3],[4,3,1]] <strong>Explanation:</strong> The graph above shows a possible modification to the edges, making the distance from 0 to 1 equal to 5. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph-2.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 3, edges = [[0,1,-1],[0,2,5]], source = 0, destination = 2, target = 6 <strong>Output:</strong> [] <strong>Explanation:</strong> The graph above contains the initial edges. It is not possible to make the distance from 0 to 2 equal to 6 by modifying the edge with weight -1. So, an empty array is returned. </pre> <p><strong class="example">Example 3:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph-3.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 4, edges = [[1,0,4],[1,2,3],[2,3,5],[0,3,-1]], source = 0, destination = 2, target = 6 <strong>Output:</strong> [[1,0,4],[1,2,3],[2,3,5],[0,3,1]] <strong>Explanation:</strong> The graph above shows a modified graph having the shortest distance from 0 to 2 as 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code><font face="monospace">1 &lt;= edges.length &lt;= n * (n - 1) / 2</font></code></li> <li><code>edges[i].length == 3</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i&nbsp;</sub>&lt;&nbsp;n</code></li> <li><code><font face="monospace">w<sub>i</sub>&nbsp;= -1&nbsp;</font></code>or <code><font face="monospace">1 &lt;= w<sub>i&nbsp;</sub>&lt;= 10<sup><span style="font-size: 10.8333px;">7</span></sup></font></code></li> <li><code>a<sub>i&nbsp;</sub>!=&nbsp;b<sub>i</sub></code></li> <li><code>0 &lt;= source, destination &lt; n</code></li> <li><code>source != destination</code></li> <li><code><font face="monospace">1 &lt;= target &lt;= 10<sup>9</sup></font></code></li> <li>The graph is connected, and there are no self-loops or repeated edges</li> </ul>
Graph; Shortest Path; Heap (Priority Queue)
Python
class Solution: def modifiedGraphEdges( self, n: int, edges: List[List[int]], source: int, destination: int, target: int ) -> List[List[int]]: def dijkstra(edges: List[List[int]]) -> int: g = [[inf] * n for _ in range(n)] for a, b, w in edges: if w == -1: continue g[a][b] = g[b][a] = w dist = [inf] * n dist[source] = 0 vis = [False] * n for _ in range(n): k = -1 for j in range(n): if not vis[j] and (k == -1 or dist[k] > dist[j]): k = j vis[k] = True for j in range(n): dist[j] = min(dist[j], dist[k] + g[k][j]) return dist[destination] inf = 2 * 10**9 d = dijkstra(edges) if d < target: return [] ok = d == target for e in edges: if e[2] > 0: continue if ok: e[2] = inf continue e[2] = 1 d = dijkstra(edges) if d <= target: ok = True e[2] += target - d return edges if ok else []
2,699
Modify Graph Edge Weights
Hard
<p>You are given an <strong>undirected weighted</strong> <strong>connected</strong> graph containing <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and an integer array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>, w<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> with weight <code>w<sub>i</sub></code>.</p> <p>Some edges have a weight of <code>-1</code> (<code>w<sub>i</sub> = -1</code>), while others have a <strong>positive</strong> weight (<code>w<sub>i</sub> &gt; 0</code>).</p> <p>Your task is to modify <strong>all edges</strong> with a weight of <code>-1</code> by assigning them <strong>positive integer values </strong>in the range <code>[1, 2 * 10<sup>9</sup>]</code> so that the <strong>shortest distance</strong> between the nodes <code>source</code> and <code>destination</code> becomes equal to an integer <code>target</code>. If there are <strong>multiple</strong> <strong>modifications</strong> that make the shortest distance between <code>source</code> and <code>destination</code> equal to <code>target</code>, any of them will be considered correct.</p> <p>Return <em>an array containing all edges (even unmodified ones) in any order if it is possible to make the shortest distance from </em><code>source</code><em> to </em><code>destination</code><em> equal to </em><code>target</code><em>, or an <strong>empty array</strong> if it&#39;s impossible.</em></p> <p><strong>Note:</strong> You are not allowed to modify the weights of edges with initial positive weights.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 5, edges = [[4,1,-1],[2,0,-1],[0,3,-1],[4,3,-1]], source = 0, destination = 1, target = 5 <strong>Output:</strong> [[4,1,1],[2,0,1],[0,3,3],[4,3,1]] <strong>Explanation:</strong> The graph above shows a possible modification to the edges, making the distance from 0 to 1 equal to 5. </pre> <p><strong class="example">Example 2:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph-2.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 3, edges = [[0,1,-1],[0,2,5]], source = 0, destination = 2, target = 6 <strong>Output:</strong> [] <strong>Explanation:</strong> The graph above contains the initial edges. It is not possible to make the distance from 0 to 2 equal to 6 by modifying the edge with weight -1. So, an empty array is returned. </pre> <p><strong class="example">Example 3:</strong></p> <p><strong class="example"><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2699.Modify%20Graph%20Edge%20Weights/images/graph-3.png" style="width: 300px; height: 300px;" /></strong></p> <pre> <strong>Input:</strong> n = 4, edges = [[1,0,4],[1,2,3],[2,3,5],[0,3,-1]], source = 0, destination = 2, target = 6 <strong>Output:</strong> [[1,0,4],[1,2,3],[2,3,5],[0,3,1]] <strong>Explanation:</strong> The graph above shows a modified graph having the shortest distance from 0 to 2 as 6. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 100</code></li> <li><code><font face="monospace">1 &lt;= edges.length &lt;= n * (n - 1) / 2</font></code></li> <li><code>edges[i].length == 3</code></li> <li><code>0 &lt;= a<sub>i</sub>, b<sub>i&nbsp;</sub>&lt;&nbsp;n</code></li> <li><code><font face="monospace">w<sub>i</sub>&nbsp;= -1&nbsp;</font></code>or <code><font face="monospace">1 &lt;= w<sub>i&nbsp;</sub>&lt;= 10<sup><span style="font-size: 10.8333px;">7</span></sup></font></code></li> <li><code>a<sub>i&nbsp;</sub>!=&nbsp;b<sub>i</sub></code></li> <li><code>0 &lt;= source, destination &lt; n</code></li> <li><code>source != destination</code></li> <li><code><font face="monospace">1 &lt;= target &lt;= 10<sup>9</sup></font></code></li> <li>The graph is connected, and there are no self-loops or repeated edges</li> </ul>
Graph; Shortest Path; Heap (Priority Queue)
TypeScript
function modifiedGraphEdges( n: number, edges: number[][], source: number, destination: number, target: number, ): number[][] { const inf = 2e9; const dijkstra = (edges: number[][]): number => { const g: number[][] = Array(n) .fill(0) .map(() => Array(n).fill(inf)); const dist: number[] = Array(n).fill(inf); const vis: boolean[] = Array(n).fill(false); for (const [a, b, w] of edges) { if (w === -1) { continue; } g[a][b] = w; g[b][a] = w; } dist[source] = 0; for (let i = 0; i < n; ++i) { let k = -1; for (let j = 0; j < n; ++j) { if (!vis[j] && (k === -1 || dist[j] < dist[k])) { k = j; } } vis[k] = true; for (let j = 0; j < n; ++j) { dist[j] = Math.min(dist[j], dist[k] + g[k][j]); } } return dist[destination]; }; let d = dijkstra(edges); if (d < target) { return []; } let ok = d === target; for (const e of edges) { if (e[2] > 0) { continue; } if (ok) { e[2] = inf; continue; } e[2] = 1; d = dijkstra(edges); if (d <= target) { ok = true; e[2] += target - d; } } return ok ? edges : []; }
2,700
Differences Between Two Objects
Medium
<p>Write a function that accepts two deeply nested objects or arrays&nbsp;<code>obj1</code> and&nbsp;<code>obj2</code>&nbsp;and returns a new&nbsp;object representing their differences.</p> <p>The function should compare the properties of the two objects and identify any changes.&nbsp;The returned object should only contains keys where the value is different from&nbsp;<code>obj1</code> to&nbsp;<code>obj2</code>.</p> <p>For each changed key, the value should be represented as an&nbsp;array <code>[obj1 value, obj2&nbsp;value]</code>. Keys that exist in one object but not in the other should not be included in the returned object.&nbsp;The end result should be a deeply nested object where each leaf value is a difference array.</p> <p>When comparing two arrays, the indices of the arrays are considered to be their keys.&nbsp;</p> <p>You may assume that both objects are the output of <code>JSON.parse</code>.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> obj1 = {} obj2 = { &nbsp; &quot;a&quot;: 1, &quot;b&quot;: 2 } <strong>Output:</strong> {} <strong>Explanation:</strong> There were no modifications made to obj1. New keys &quot;a&quot; and &quot;b&quot; appear in obj2, but keys that are added or removed should be ignored. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> obj1 = { &nbsp; &quot;a&quot;: 1, &nbsp; &quot;v&quot;: 3, &nbsp; &quot;x&quot;: [], &nbsp; &quot;z&quot;: { &nbsp; &nbsp; &quot;a&quot;: null &nbsp; } } obj2 = { &nbsp; &quot;a&quot;: 2, &nbsp; &quot;v&quot;: 4, &nbsp; &quot;x&quot;: [], &nbsp; &quot;z&quot;: { &nbsp; &nbsp; &quot;a&quot;: 2 &nbsp; } } <strong>Output:</strong> { &nbsp; &quot;a&quot;: [1, 2], &quot;v&quot;: [3, 4], &nbsp; &quot;z&quot;: { &nbsp; &quot;a&quot;: [null, 2] &nbsp; } } <strong>Explanation:</strong> The keys &quot;a&quot;, &quot;v&quot;, and &quot;z&quot; all had changes applied. &quot;a&quot; was changed from 1 to 2. &quot;v&quot; was changed from 3 to 4. &quot;z&quot; had a change applied to a child object. &quot;z.a&quot; was changed from null to 2. </pre> <p><strong>Example 3:</strong></p> <pre> <strong>Input:</strong> obj1 = { &nbsp; &quot;a&quot;: 5, &nbsp; &quot;v&quot;: 6, &nbsp; &quot;z&quot;: [1, 2, 4, [2, 5, 7]] } obj2 = { &nbsp; &quot;a&quot;: 5, &nbsp; &quot;v&quot;: 7, &nbsp; &quot;z&quot;: [1, 2, 3, [1]] } <strong>Output:</strong> { &nbsp; &quot;v&quot;: [6, 7], &nbsp; &quot;z&quot;: { &nbsp; &quot;2&quot;: [4, 3], &nbsp; &quot;3&quot;: { &nbsp; &quot;0&quot;: [2, 1] &nbsp; } &nbsp; } } <strong>Explanation:</strong> In obj1 and obj2, the keys &quot;v&quot; and &quot;z&quot; have different assigned values. &quot;a&quot; is ignored because the value is unchanged. In the key &quot;z&quot;, there is a nested array. Arrays are treated like objects where the indices are keys. There were two alterations to the the array: z[2] and z[3][0]. z[0] and z[1] were unchanged and thus not included. z[3][1] and z[3][2] were removed and thus not included. </pre> <p><strong>Example 4:</strong></p> <pre> <strong>Input:</strong> obj1 = { &nbsp; &quot;a&quot;: {&quot;b&quot;: 1}, } obj2 = { &nbsp; &quot;a&quot;: [5], } <strong>Output:</strong> { &quot;a&quot;: [{&quot;b&quot;: 1}, [5]] } <strong>Explanation:</strong> The key &quot;a&quot; exists in both objects. Since the two associated values have different types, they are placed in the difference array.</pre> <p><strong>Example 5:</strong></p> <pre> <strong>Input:</strong> obj1 = { &nbsp; &quot;a&quot;: [1, 2, {}], &nbsp; &quot;b&quot;: false } obj2 = { &nbsp; &nbsp; &quot;b&quot;: false, &nbsp; &quot;a&quot;: [1, 2, {}] } <strong>Output:</strong> {} <strong>Explanation:</strong> Apart from a different ordering of keys, the two objects are identical so an empty object is returned.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>obj1</code> and <code>obj2</code> are valid JSON objects or arrays</li> <li><code>2 &lt;= JSON.stringify(obj1).length &lt;= 10<sup>4</sup></code></li> <li><code>2 &lt;= JSON.stringify(obj2).length &lt;= 10<sup>4</sup></code></li> </ul>
JavaScript
TypeScript
function objDiff(obj1: any, obj2: any): any { if (type(obj1) !== type(obj2)) return [obj1, obj2]; if (!isObject(obj1)) return obj1 === obj2 ? {} : [obj1, obj2]; const diff: Record<string, unknown> = {}; const sameKeys = Object.keys(obj1).filter(key => key in obj2); sameKeys.forEach(key => { const subDiff = objDiff(obj1[key], obj2[key]); if (Object.keys(subDiff).length) diff[key] = subDiff; }); return diff; } function type(obj: unknown): string { return Object.prototype.toString.call(obj).slice(8, -1); } function isObject(obj: unknown): obj is Record<string, unknown> { return typeof obj === 'object' && obj !== null; }
2,701
Consecutive Transactions with Increasing Amounts
Hard
<p>Table: <code>Transactions</code></p> <pre> +------------------+------+ | Column Name | Type | +------------------+------+ | transaction_id | int | | customer_id | int | | transaction_date | date | | amount | int | +------------------+------+ transaction_id is the primary key of this table. Each row contains information about transactions that includes unique (customer_id, transaction_date) along with the corresponding customer_id and amount. </pre> <p>Write an SQL query to find the customers who have made consecutive transactions with increasing <code>amount</code>&nbsp;for at least three consecutive days. Include the <code>customer_id</code>,&nbsp;start date of the consecutive transactions&nbsp;period and the end date of the consecutive transactions period. There can be multiple consecutive transactions by a customer.</p> <p>Return <em>the result table ordered by</em> <code>customer_id, consecutive_start, consecutive_end</code> <em>in <strong>ascending</strong> order.</em></p> <p>The query result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong>&nbsp; Transactions table: +----------------+-------------+------------------+--------+ | transaction_id | customer_id | transaction_date | amount | +----------------+-------------+------------------+--------+ | 1 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 101 &nbsp; &nbsp; &nbsp; &nbsp; | 2023-05-01 &nbsp; &nbsp; &nbsp; | 100 &nbsp; &nbsp;| | 2 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 101 &nbsp; &nbsp; &nbsp; &nbsp; | 2023-05-02 &nbsp; &nbsp; &nbsp; | 150 &nbsp; &nbsp;| | 3 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 101 &nbsp; &nbsp; &nbsp; &nbsp; | 2023-05-03 &nbsp; &nbsp; &nbsp; | 200 &nbsp; &nbsp;| | 4 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 102 &nbsp; &nbsp; &nbsp; &nbsp; | 2023-05-01 &nbsp; &nbsp; &nbsp; | 50 &nbsp; &nbsp; | | 5 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 102 &nbsp; &nbsp; &nbsp; &nbsp; | 2023-05-03 &nbsp; &nbsp; &nbsp; | 100 &nbsp; &nbsp;| | 6 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 102 &nbsp; &nbsp; &nbsp; &nbsp; | 2023-05-04 &nbsp; &nbsp; &nbsp; | 200 &nbsp; &nbsp;| | 7 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 105 &nbsp; &nbsp; &nbsp; &nbsp; | 2023-05-01 &nbsp; &nbsp; &nbsp; | 100 &nbsp; &nbsp;| | 8 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 105 &nbsp; &nbsp; &nbsp; &nbsp; | 2023-05-02 &nbsp; &nbsp; &nbsp; | 150 &nbsp; &nbsp;| | 9 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| 105 &nbsp; &nbsp; &nbsp; &nbsp; | 2023-05-03 &nbsp; &nbsp; &nbsp; | 200 &nbsp; &nbsp;| | 10 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | 105 &nbsp; &nbsp; &nbsp; &nbsp; | 2023-05-04 &nbsp; &nbsp; &nbsp; | 300 &nbsp; &nbsp;| | 11 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | 105 &nbsp; &nbsp; &nbsp; &nbsp; | 2023-05-12 &nbsp; &nbsp; &nbsp; | 250 &nbsp; &nbsp;| | 12 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | 105 &nbsp; &nbsp; &nbsp; &nbsp; | 2023-05-13 &nbsp; &nbsp; &nbsp; | 260 &nbsp; &nbsp;| | 13 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | 105 &nbsp; &nbsp; &nbsp; &nbsp; | 2023-05-14 &nbsp; &nbsp; &nbsp; | 270 &nbsp; &nbsp;| +----------------+-------------+------------------+--------+ <strong>Output:</strong>&nbsp; +-------------+-------------------+-----------------+ | customer_id | consecutive_start | consecutive_end |&nbsp; +-------------+-------------------+-----------------+ | 101 &nbsp; &nbsp; &nbsp; &nbsp; |&nbsp; 2023-05-01 &nbsp; &nbsp; &nbsp; |&nbsp;2023-05-03 &nbsp; &nbsp; &nbsp;|&nbsp; | 105 &nbsp; &nbsp; &nbsp; &nbsp; |&nbsp; 2023-05-01 &nbsp; &nbsp; &nbsp; |&nbsp;2023-05-04 &nbsp; &nbsp; &nbsp;| | 105 &nbsp; &nbsp; &nbsp; &nbsp; |&nbsp; 2023-05-12 &nbsp; &nbsp; &nbsp; |&nbsp;2023-05-14 &nbsp; &nbsp; &nbsp;|&nbsp; +-------------+-------------------+-----------------+ <strong>Explanation:</strong>&nbsp; - customer_id 101 has made consecutive transactions with increasing amounts from May 1st, 2023, to May 3rd, 2023 - customer_id 102 does not have any consecutive transactions for at least 3 days.&nbsp; - customer_id 105 has two sets of consecutive transactions: from May 1st, 2023, to May 4th, 2023, and from May 12th, 2023, to May 14th, 2023.&nbsp; customer_id is sorted in ascending order. </pre> <p>&nbsp;</p>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT t1.*, SUM( CASE WHEN t2.customer_id IS NULL THEN 1 ELSE 0 END ) OVER (ORDER BY customer_id, transaction_date) AS s FROM Transactions AS t1 LEFT JOIN Transactions AS t2 ON t1.customer_id = t2.customer_id AND t1.amount > t2.amount AND DATEDIFF(t1.transaction_date, t2.transaction_date) = 1 ) SELECT customer_id, MIN(transaction_date) AS consecutive_start, MAX(transaction_date) AS consecutive_end FROM T GROUP BY customer_id, s HAVING COUNT(1) >= 3 ORDER BY customer_id;
2,702
Minimum Operations to Make Numbers Non-positive
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and two integers <code>x</code> and <code>y</code>. In one operation, you must choose an index <code>i</code> such that <code>0 &lt;= i &lt; nums.length</code> and perform the following:</p> <ul> <li>Decrement <code>nums[i]</code> by <code>x</code>.</li> <li>Decrement values by <code>y</code> at all indices except the <code>i<sup>th</sup></code> one.</li> </ul> <p>Return <em>the minimum number of operations to make all the integers in </em><code>nums</code> <em><strong>less than or equal to zero.</strong></em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,1,7,6], x = 4, y = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> You will need three operations. One of the optimal sequence of operations is: Operation 1: Choose i = 3. Then, nums = [1,2,-1,3,4]. Operation 2: Choose i = 3. Then, nums = [-1,0,-3,-1,2]. Operation 3: Choose i = 4. Then, nums = [-3,-2,-5,-3,-2]. Now, all the numbers in nums are non-positive. Therefore, we return 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1], x = 2, y = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can perform the operation once on i = 1. Then, nums becomes [0,0,0]. All the positive numbers are removed, and therefore, we return 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= y &lt; x &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
C++
class Solution { public: int minOperations(vector<int>& nums, int x, int y) { int l = 0, r = *max_element(nums.begin(), nums.end()); auto check = [&](int t) { long long cnt = 0; for (int v : nums) { if (v > 1LL * t * y) { cnt += (v - 1LL * t * y + x - y - 1) / (x - y); } } return cnt <= t; }; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } };
2,702
Minimum Operations to Make Numbers Non-positive
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and two integers <code>x</code> and <code>y</code>. In one operation, you must choose an index <code>i</code> such that <code>0 &lt;= i &lt; nums.length</code> and perform the following:</p> <ul> <li>Decrement <code>nums[i]</code> by <code>x</code>.</li> <li>Decrement values by <code>y</code> at all indices except the <code>i<sup>th</sup></code> one.</li> </ul> <p>Return <em>the minimum number of operations to make all the integers in </em><code>nums</code> <em><strong>less than or equal to zero.</strong></em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,1,7,6], x = 4, y = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> You will need three operations. One of the optimal sequence of operations is: Operation 1: Choose i = 3. Then, nums = [1,2,-1,3,4]. Operation 2: Choose i = 3. Then, nums = [-1,0,-3,-1,2]. Operation 3: Choose i = 4. Then, nums = [-3,-2,-5,-3,-2]. Now, all the numbers in nums are non-positive. Therefore, we return 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1], x = 2, y = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can perform the operation once on i = 1. Then, nums becomes [0,0,0]. All the positive numbers are removed, and therefore, we return 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= y &lt; x &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
Go
func minOperations(nums []int, x int, y int) int { check := func(t int) bool { cnt := 0 for _, v := range nums { if v > t*y { cnt += (v - t*y + x - y - 1) / (x - y) } } return cnt <= t } l, r := 0, slices.Max(nums) for l < r { mid := (l + r) >> 1 if check(mid) { r = mid } else { l = mid + 1 } } return l }
2,702
Minimum Operations to Make Numbers Non-positive
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and two integers <code>x</code> and <code>y</code>. In one operation, you must choose an index <code>i</code> such that <code>0 &lt;= i &lt; nums.length</code> and perform the following:</p> <ul> <li>Decrement <code>nums[i]</code> by <code>x</code>.</li> <li>Decrement values by <code>y</code> at all indices except the <code>i<sup>th</sup></code> one.</li> </ul> <p>Return <em>the minimum number of operations to make all the integers in </em><code>nums</code> <em><strong>less than or equal to zero.</strong></em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,1,7,6], x = 4, y = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> You will need three operations. One of the optimal sequence of operations is: Operation 1: Choose i = 3. Then, nums = [1,2,-1,3,4]. Operation 2: Choose i = 3. Then, nums = [-1,0,-3,-1,2]. Operation 3: Choose i = 4. Then, nums = [-3,-2,-5,-3,-2]. Now, all the numbers in nums are non-positive. Therefore, we return 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1], x = 2, y = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can perform the operation once on i = 1. Then, nums becomes [0,0,0]. All the positive numbers are removed, and therefore, we return 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= y &lt; x &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
Java
class Solution { private int[] nums; private int x; private int y; public int minOperations(int[] nums, int x, int y) { this.nums = nums; this.x = x; this.y = y; int l = 0, r = 0; for (int v : nums) { r = Math.max(r, v); } while (l < r) { int mid = (l + r) >>> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; } private boolean check(int t) { long cnt = 0; for (int v : nums) { if (v > (long) t * y) { cnt += (v - (long) t * y + x - y - 1) / (x - y); } } return cnt <= t; } }
2,702
Minimum Operations to Make Numbers Non-positive
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and two integers <code>x</code> and <code>y</code>. In one operation, you must choose an index <code>i</code> such that <code>0 &lt;= i &lt; nums.length</code> and perform the following:</p> <ul> <li>Decrement <code>nums[i]</code> by <code>x</code>.</li> <li>Decrement values by <code>y</code> at all indices except the <code>i<sup>th</sup></code> one.</li> </ul> <p>Return <em>the minimum number of operations to make all the integers in </em><code>nums</code> <em><strong>less than or equal to zero.</strong></em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,1,7,6], x = 4, y = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> You will need three operations. One of the optimal sequence of operations is: Operation 1: Choose i = 3. Then, nums = [1,2,-1,3,4]. Operation 2: Choose i = 3. Then, nums = [-1,0,-3,-1,2]. Operation 3: Choose i = 4. Then, nums = [-3,-2,-5,-3,-2]. Now, all the numbers in nums are non-positive. Therefore, we return 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1], x = 2, y = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can perform the operation once on i = 1. Then, nums becomes [0,0,0]. All the positive numbers are removed, and therefore, we return 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= y &lt; x &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
Python
class Solution: def minOperations(self, nums: List[int], x: int, y: int) -> int: def check(t: int) -> bool: cnt = 0 for v in nums: if v > t * y: cnt += ceil((v - t * y) / (x - y)) return cnt <= t l, r = 0, max(nums) while l < r: mid = (l + r) >> 1 if check(mid): r = mid else: l = mid + 1 return l
2,702
Minimum Operations to Make Numbers Non-positive
Hard
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and two integers <code>x</code> and <code>y</code>. In one operation, you must choose an index <code>i</code> such that <code>0 &lt;= i &lt; nums.length</code> and perform the following:</p> <ul> <li>Decrement <code>nums[i]</code> by <code>x</code>.</li> <li>Decrement values by <code>y</code> at all indices except the <code>i<sup>th</sup></code> one.</li> </ul> <p>Return <em>the minimum number of operations to make all the integers in </em><code>nums</code> <em><strong>less than or equal to zero.</strong></em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,1,7,6], x = 4, y = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> You will need three operations. One of the optimal sequence of operations is: Operation 1: Choose i = 3. Then, nums = [1,2,-1,3,4]. Operation 2: Choose i = 3. Then, nums = [-1,0,-3,-1,2]. Operation 3: Choose i = 4. Then, nums = [-3,-2,-5,-3,-2]. Now, all the numbers in nums are non-positive. Therefore, we return 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1], x = 2, y = 1 <strong>Output:</strong> 1 <strong>Explanation:</strong> We can perform the operation once on i = 1. Then, nums becomes [0,0,0]. All the positive numbers are removed, and therefore, we return 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= y &lt; x &lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
TypeScript
function minOperations(nums: number[], x: number, y: number): number { let l = 0; let r = Math.max(...nums); const check = (t: number): boolean => { let cnt = 0; for (const v of nums) { if (v > t * y) { cnt += Math.ceil((v - t * y) / (x - y)); } } return cnt <= t; }; while (l < r) { const mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l; }
2,703
Return Length of Arguments Passed
Easy
Write a function&nbsp;<code>argumentsLength</code> that returns the count of arguments passed to it. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> args = [5] <strong>Output:</strong> 1 <strong>Explanation:</strong> argumentsLength(5); // 1 One value was passed to the function so it should return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> args = [{}, null, &quot;3&quot;] <strong>Output:</strong> 3 <strong>Explanation:</strong> argumentsLength({}, null, &quot;3&quot;); // 3 Three values were passed to the function so it should return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>args</code>&nbsp;is a valid JSON array</li> <li><code>0 &lt;= args.length &lt;= 100</code></li> </ul>
JavaScript
TypeScript
function argumentsLength(...args: any[]): number { return args.length; } /** * argumentsLength(1, 2, 3); // 3 */
2,704
To Be Or Not To Be
Easy
<p>Write a function&nbsp;<code>expect</code> that helps developers test their code. It should take in any value&nbsp;<code>val</code>&nbsp;and return an object with the following two functions.</p> <ul> <li><code>toBe(val)</code>&nbsp;accepts another value and returns&nbsp;<code>true</code>&nbsp;if the two values&nbsp;<code>===</code>&nbsp;each other. If they are not equal, it should throw an error&nbsp;<code>&quot;Not Equal&quot;</code>.</li> <li><code>notToBe(val)</code>&nbsp;accepts another value and returns&nbsp;<code>true</code>&nbsp;if the two values&nbsp;<code>!==</code>&nbsp;each other. If they are equal, it should throw an error&nbsp;<code>&quot;Equal&quot;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> func = () =&gt; expect(5).toBe(5) <strong>Output:</strong> {&quot;value&quot;: true} <strong>Explanation:</strong> 5 === 5 so this expression returns true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> func = () =&gt; expect(5).toBe(null) <strong>Output:</strong> {&quot;error&quot;: &quot;Not Equal&quot;} <strong>Explanation:</strong> 5 !== null so this expression throw the error &quot;Not Equal&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> func = () =&gt; expect(5).notToBe(null) <strong>Output:</strong> {&quot;value&quot;: true} <strong>Explanation:</strong> 5 !== null so this expression returns true. </pre>
JavaScript
JavaScript
/** * @param {string} val * @return {Object} */ var expect = function (val) { return { toBe: function (expected) { if (val !== expected) { throw new Error('Not Equal'); } return true; }, notToBe: function (expected) { if (val === expected) { throw new Error('Equal'); } return true; }, }; }; /** * expect(5).toBe(5); // true * expect(5).notToBe(5); // throws "Equal" */
2,704
To Be Or Not To Be
Easy
<p>Write a function&nbsp;<code>expect</code> that helps developers test their code. It should take in any value&nbsp;<code>val</code>&nbsp;and return an object with the following two functions.</p> <ul> <li><code>toBe(val)</code>&nbsp;accepts another value and returns&nbsp;<code>true</code>&nbsp;if the two values&nbsp;<code>===</code>&nbsp;each other. If they are not equal, it should throw an error&nbsp;<code>&quot;Not Equal&quot;</code>.</li> <li><code>notToBe(val)</code>&nbsp;accepts another value and returns&nbsp;<code>true</code>&nbsp;if the two values&nbsp;<code>!==</code>&nbsp;each other. If they are equal, it should throw an error&nbsp;<code>&quot;Equal&quot;</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> func = () =&gt; expect(5).toBe(5) <strong>Output:</strong> {&quot;value&quot;: true} <strong>Explanation:</strong> 5 === 5 so this expression returns true. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> func = () =&gt; expect(5).toBe(null) <strong>Output:</strong> {&quot;error&quot;: &quot;Not Equal&quot;} <strong>Explanation:</strong> 5 !== null so this expression throw the error &quot;Not Equal&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> func = () =&gt; expect(5).notToBe(null) <strong>Output:</strong> {&quot;value&quot;: true} <strong>Explanation:</strong> 5 !== null so this expression returns true. </pre>
JavaScript
TypeScript
type ToBeOrNotToBe = { toBe: (val: any) => boolean; notToBe: (val: any) => boolean; }; function expect(val: any): ToBeOrNotToBe { return { toBe: (toBeVal: any) => { if (val !== toBeVal) { throw new Error('Not Equal'); } return true; }, notToBe: (notToBeVal: any) => { if (val === notToBeVal) { throw new Error('Equal'); } return true; }, }; } /** * expect(5).toBe(5); // true * expect(5).notToBe(5); // throws "Equal" */
2,705
Compact Object
Medium
<p>Given an object or array&nbsp;<code>obj</code>, return a <strong>compact object</strong>.</p> <p>A <strong>compact object</strong>&nbsp;is the same as the original object, except with keys containing <strong>falsy</strong> values removed. This operation applies to the object and any nested objects. Arrays are considered objects where&nbsp;the indices are&nbsp;keys. A value is&nbsp;considered <strong>falsy</strong>&nbsp;when <code>Boolean(value)</code> returns <code>false</code>.</p> <p>You may assume the&nbsp;<code>obj</code> is&nbsp;the output of&nbsp;<code>JSON.parse</code>. In other words, it is valid JSON.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> obj = [null, 0, false, 1] <strong>Output:</strong> [1] <strong>Explanation:</strong> All falsy values have been removed from the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> obj = {&quot;a&quot;: null, &quot;b&quot;: [false, 1]} <strong>Output:</strong> {&quot;b&quot;: [1]} <strong>Explanation:</strong> obj[&quot;a&quot;] and obj[&quot;b&quot;][0] had falsy values and were removed.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> obj = [null, 0, 5, [0], [false, 16]] <strong>Output:</strong> [5, [], [16]] <strong>Explanation:</strong> obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>obj</code> is a valid JSON object</li> <li><code>2 &lt;= JSON.stringify(obj).length &lt;= 10<sup>6</sup></code></li> </ul>
JavaScript
JavaScript
/** * @param {Object|Array} obj * @return {Object|Array} */ var compactObject = function (obj) { if (!obj || typeof obj !== 'object') { return obj; } if (Array.isArray(obj)) { return obj.filter(Boolean).map(compactObject); } return Object.entries(obj).reduce((acc, [key, value]) => { if (value) { acc[key] = compactObject(value); } return acc; }, {}); };
2,705
Compact Object
Medium
<p>Given an object or array&nbsp;<code>obj</code>, return a <strong>compact object</strong>.</p> <p>A <strong>compact object</strong>&nbsp;is the same as the original object, except with keys containing <strong>falsy</strong> values removed. This operation applies to the object and any nested objects. Arrays are considered objects where&nbsp;the indices are&nbsp;keys. A value is&nbsp;considered <strong>falsy</strong>&nbsp;when <code>Boolean(value)</code> returns <code>false</code>.</p> <p>You may assume the&nbsp;<code>obj</code> is&nbsp;the output of&nbsp;<code>JSON.parse</code>. In other words, it is valid JSON.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> obj = [null, 0, false, 1] <strong>Output:</strong> [1] <strong>Explanation:</strong> All falsy values have been removed from the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> obj = {&quot;a&quot;: null, &quot;b&quot;: [false, 1]} <strong>Output:</strong> {&quot;b&quot;: [1]} <strong>Explanation:</strong> obj[&quot;a&quot;] and obj[&quot;b&quot;][0] had falsy values and were removed.</pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> obj = [null, 0, 5, [0], [false, 16]] <strong>Output:</strong> [5, [], [16]] <strong>Explanation:</strong> obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>obj</code> is a valid JSON object</li> <li><code>2 &lt;= JSON.stringify(obj).length &lt;= 10<sup>6</sup></code></li> </ul>
JavaScript
TypeScript
type Obj = Record<any, any>; function compactObject(obj: Obj): Obj { if (!obj || typeof obj !== 'object') { return obj; } if (Array.isArray(obj)) { return obj.filter(Boolean).map(compactObject); } return Object.entries(obj).reduce((acc, [key, value]) => { if (value) { acc[key] = compactObject(value); } return acc; }, {} as Obj); }
2,706
Buy Two Chocolates
Easy
<p>You are given an integer array <code>prices</code> representing the prices of various chocolates in a store. You are also given a single integer <code>money</code>, which represents your initial amount of money.</p> <p>You must buy <strong>exactly</strong> two chocolates in such a way that you still have some <strong>non-negative</strong> leftover money. You would like to minimize the sum of the prices of the two chocolates you buy.</p> <p>Return <em>the amount of money you will have leftover after buying the two chocolates</em>. If there is no way for you to buy two chocolates without ending up in debt, return <code>money</code>. Note that the leftover must be non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,2], money = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [3,2,3], money = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> You cannot buy 2 chocolates without going in debt, so we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= prices.length &lt;= 50</code></li> <li><code>1 &lt;= prices[i] &lt;= 100</code></li> <li><code>1 &lt;= money &lt;= 100</code></li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: int buyChoco(vector<int>& prices, int money) { sort(prices.begin(), prices.end()); int cost = prices[0] + prices[1]; return money < cost ? money : money - cost; } };
2,706
Buy Two Chocolates
Easy
<p>You are given an integer array <code>prices</code> representing the prices of various chocolates in a store. You are also given a single integer <code>money</code>, which represents your initial amount of money.</p> <p>You must buy <strong>exactly</strong> two chocolates in such a way that you still have some <strong>non-negative</strong> leftover money. You would like to minimize the sum of the prices of the two chocolates you buy.</p> <p>Return <em>the amount of money you will have leftover after buying the two chocolates</em>. If there is no way for you to buy two chocolates without ending up in debt, return <code>money</code>. Note that the leftover must be non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,2], money = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [3,2,3], money = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> You cannot buy 2 chocolates without going in debt, so we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= prices.length &lt;= 50</code></li> <li><code>1 &lt;= prices[i] &lt;= 100</code></li> <li><code>1 &lt;= money &lt;= 100</code></li> </ul>
Greedy; Array; Sorting
Go
func buyChoco(prices []int, money int) int { sort.Ints(prices) cost := prices[0] + prices[1] if money < cost { return money } return money - cost }
2,706
Buy Two Chocolates
Easy
<p>You are given an integer array <code>prices</code> representing the prices of various chocolates in a store. You are also given a single integer <code>money</code>, which represents your initial amount of money.</p> <p>You must buy <strong>exactly</strong> two chocolates in such a way that you still have some <strong>non-negative</strong> leftover money. You would like to minimize the sum of the prices of the two chocolates you buy.</p> <p>Return <em>the amount of money you will have leftover after buying the two chocolates</em>. If there is no way for you to buy two chocolates without ending up in debt, return <code>money</code>. Note that the leftover must be non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,2], money = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [3,2,3], money = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> You cannot buy 2 chocolates without going in debt, so we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= prices.length &lt;= 50</code></li> <li><code>1 &lt;= prices[i] &lt;= 100</code></li> <li><code>1 &lt;= money &lt;= 100</code></li> </ul>
Greedy; Array; Sorting
Java
class Solution { public int buyChoco(int[] prices, int money) { Arrays.sort(prices); int cost = prices[0] + prices[1]; return money < cost ? money : money - cost; } }
2,706
Buy Two Chocolates
Easy
<p>You are given an integer array <code>prices</code> representing the prices of various chocolates in a store. You are also given a single integer <code>money</code>, which represents your initial amount of money.</p> <p>You must buy <strong>exactly</strong> two chocolates in such a way that you still have some <strong>non-negative</strong> leftover money. You would like to minimize the sum of the prices of the two chocolates you buy.</p> <p>Return <em>the amount of money you will have leftover after buying the two chocolates</em>. If there is no way for you to buy two chocolates without ending up in debt, return <code>money</code>. Note that the leftover must be non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,2], money = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [3,2,3], money = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> You cannot buy 2 chocolates without going in debt, so we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= prices.length &lt;= 50</code></li> <li><code>1 &lt;= prices[i] &lt;= 100</code></li> <li><code>1 &lt;= money &lt;= 100</code></li> </ul>
Greedy; Array; Sorting
Python
class Solution: def buyChoco(self, prices: List[int], money: int) -> int: prices.sort() cost = prices[0] + prices[1] return money if money < cost else money - cost
2,706
Buy Two Chocolates
Easy
<p>You are given an integer array <code>prices</code> representing the prices of various chocolates in a store. You are also given a single integer <code>money</code>, which represents your initial amount of money.</p> <p>You must buy <strong>exactly</strong> two chocolates in such a way that you still have some <strong>non-negative</strong> leftover money. You would like to minimize the sum of the prices of the two chocolates you buy.</p> <p>Return <em>the amount of money you will have leftover after buying the two chocolates</em>. If there is no way for you to buy two chocolates without ending up in debt, return <code>money</code>. Note that the leftover must be non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,2], money = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [3,2,3], money = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> You cannot buy 2 chocolates without going in debt, so we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= prices.length &lt;= 50</code></li> <li><code>1 &lt;= prices[i] &lt;= 100</code></li> <li><code>1 &lt;= money &lt;= 100</code></li> </ul>
Greedy; Array; Sorting
Rust
impl Solution { pub fn buy_choco(mut prices: Vec<i32>, money: i32) -> i32 { prices.sort(); let cost = prices[0] + prices[1]; if cost > money { return money; } money - cost } }
2,706
Buy Two Chocolates
Easy
<p>You are given an integer array <code>prices</code> representing the prices of various chocolates in a store. You are also given a single integer <code>money</code>, which represents your initial amount of money.</p> <p>You must buy <strong>exactly</strong> two chocolates in such a way that you still have some <strong>non-negative</strong> leftover money. You would like to minimize the sum of the prices of the two chocolates you buy.</p> <p>Return <em>the amount of money you will have leftover after buying the two chocolates</em>. If there is no way for you to buy two chocolates without ending up in debt, return <code>money</code>. Note that the leftover must be non-negative.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> prices = [1,2,2], money = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> prices = [3,2,3], money = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> You cannot buy 2 chocolates without going in debt, so we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= prices.length &lt;= 50</code></li> <li><code>1 &lt;= prices[i] &lt;= 100</code></li> <li><code>1 &lt;= money &lt;= 100</code></li> </ul>
Greedy; Array; Sorting
TypeScript
function buyChoco(prices: number[], money: number): number { prices.sort((a, b) => a - b); const cost = prices[0] + prices[1]; return money < cost ? money : money - cost; }
2,707
Extra Characters in a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>s</code> and a dictionary of words <code>dictionary</code>. You have to break <code>s</code> into one or more <strong>non-overlapping</strong> substrings such that each substring is present in <code>dictionary</code>. There may be some <strong>extra characters</strong> in <code>s</code> which are not present in any of the substrings.</p> <p>Return <em>the <strong>minimum</strong> number of extra characters left over if you break up </em><code>s</code><em> optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;leetscode&quot;, dictionary = [&quot;leet&quot;,&quot;code&quot;,&quot;leetcode&quot;] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can break s in two substrings: &quot;leet&quot; from index 0 to 3 and &quot;code&quot; from index 5 to 8. There is only 1 unused character (at index 4), so we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;sayhelloworld&quot;, dictionary = [&quot;hello&quot;,&quot;world&quot;] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can break s in two substrings: &quot;hello&quot; from index 3 to 7 and &quot;world&quot; from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 50</code></li> <li><code>dictionary[i]</code>&nbsp;and <code>s</code> consists of only lowercase English letters</li> <li><code>dictionary</code> contains distinct words</li> </ul>
Trie; Array; Hash Table; String; Dynamic Programming
C++
class Solution { public: int minExtraChar(string s, vector<string>& dictionary) { unordered_set<string> ss(dictionary.begin(), dictionary.end()); int n = s.size(); int f[n + 1]; f[0] = 0; for (int i = 1; i <= n; ++i) { f[i] = f[i - 1] + 1; for (int j = 0; j < i; ++j) { if (ss.count(s.substr(j, i - j))) { f[i] = min(f[i], f[j]); } } } return f[n]; } };
2,707
Extra Characters in a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>s</code> and a dictionary of words <code>dictionary</code>. You have to break <code>s</code> into one or more <strong>non-overlapping</strong> substrings such that each substring is present in <code>dictionary</code>. There may be some <strong>extra characters</strong> in <code>s</code> which are not present in any of the substrings.</p> <p>Return <em>the <strong>minimum</strong> number of extra characters left over if you break up </em><code>s</code><em> optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;leetscode&quot;, dictionary = [&quot;leet&quot;,&quot;code&quot;,&quot;leetcode&quot;] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can break s in two substrings: &quot;leet&quot; from index 0 to 3 and &quot;code&quot; from index 5 to 8. There is only 1 unused character (at index 4), so we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;sayhelloworld&quot;, dictionary = [&quot;hello&quot;,&quot;world&quot;] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can break s in two substrings: &quot;hello&quot; from index 3 to 7 and &quot;world&quot; from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 50</code></li> <li><code>dictionary[i]</code>&nbsp;and <code>s</code> consists of only lowercase English letters</li> <li><code>dictionary</code> contains distinct words</li> </ul>
Trie; Array; Hash Table; String; Dynamic Programming
Go
func minExtraChar(s string, dictionary []string) int { ss := map[string]bool{} for _, w := range dictionary { ss[w] = true } n := len(s) f := make([]int, n+1) for i := 1; i <= n; i++ { f[i] = f[i-1] + 1 for j := 0; j < i; j++ { if ss[s[j:i]] && f[j] < f[i] { f[i] = f[j] } } } return f[n] }
2,707
Extra Characters in a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>s</code> and a dictionary of words <code>dictionary</code>. You have to break <code>s</code> into one or more <strong>non-overlapping</strong> substrings such that each substring is present in <code>dictionary</code>. There may be some <strong>extra characters</strong> in <code>s</code> which are not present in any of the substrings.</p> <p>Return <em>the <strong>minimum</strong> number of extra characters left over if you break up </em><code>s</code><em> optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;leetscode&quot;, dictionary = [&quot;leet&quot;,&quot;code&quot;,&quot;leetcode&quot;] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can break s in two substrings: &quot;leet&quot; from index 0 to 3 and &quot;code&quot; from index 5 to 8. There is only 1 unused character (at index 4), so we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;sayhelloworld&quot;, dictionary = [&quot;hello&quot;,&quot;world&quot;] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can break s in two substrings: &quot;hello&quot; from index 3 to 7 and &quot;world&quot; from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 50</code></li> <li><code>dictionary[i]</code>&nbsp;and <code>s</code> consists of only lowercase English letters</li> <li><code>dictionary</code> contains distinct words</li> </ul>
Trie; Array; Hash Table; String; Dynamic Programming
Java
class Solution { public int minExtraChar(String s, String[] dictionary) { Set<String> ss = new HashSet<>(); for (String w : dictionary) { ss.add(w); } int n = s.length(); int[] f = new int[n + 1]; f[0] = 0; for (int i = 1; i <= n; ++i) { f[i] = f[i - 1] + 1; for (int j = 0; j < i; ++j) { if (ss.contains(s.substring(j, i))) { f[i] = Math.min(f[i], f[j]); } } } return f[n]; } }
2,707
Extra Characters in a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>s</code> and a dictionary of words <code>dictionary</code>. You have to break <code>s</code> into one or more <strong>non-overlapping</strong> substrings such that each substring is present in <code>dictionary</code>. There may be some <strong>extra characters</strong> in <code>s</code> which are not present in any of the substrings.</p> <p>Return <em>the <strong>minimum</strong> number of extra characters left over if you break up </em><code>s</code><em> optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;leetscode&quot;, dictionary = [&quot;leet&quot;,&quot;code&quot;,&quot;leetcode&quot;] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can break s in two substrings: &quot;leet&quot; from index 0 to 3 and &quot;code&quot; from index 5 to 8. There is only 1 unused character (at index 4), so we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;sayhelloworld&quot;, dictionary = [&quot;hello&quot;,&quot;world&quot;] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can break s in two substrings: &quot;hello&quot; from index 3 to 7 and &quot;world&quot; from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 50</code></li> <li><code>dictionary[i]</code>&nbsp;and <code>s</code> consists of only lowercase English letters</li> <li><code>dictionary</code> contains distinct words</li> </ul>
Trie; Array; Hash Table; String; Dynamic Programming
JavaScript
/** * @param {string} s * @param {string[]} dictionary * @return {number} */ var minExtraChar = function (s, dictionary) { const ss = new Set(dictionary); const n = s.length; const f = Array(n + 1).fill(0); for (let i = 1; i <= n; ++i) { f[i] = f[i - 1] + 1; for (let j = 0; j < i; ++j) { if (ss.has(s.slice(j, i))) { f[i] = Math.min(f[i], f[j]); } } } return f[n]; };
2,707
Extra Characters in a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>s</code> and a dictionary of words <code>dictionary</code>. You have to break <code>s</code> into one or more <strong>non-overlapping</strong> substrings such that each substring is present in <code>dictionary</code>. There may be some <strong>extra characters</strong> in <code>s</code> which are not present in any of the substrings.</p> <p>Return <em>the <strong>minimum</strong> number of extra characters left over if you break up </em><code>s</code><em> optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;leetscode&quot;, dictionary = [&quot;leet&quot;,&quot;code&quot;,&quot;leetcode&quot;] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can break s in two substrings: &quot;leet&quot; from index 0 to 3 and &quot;code&quot; from index 5 to 8. There is only 1 unused character (at index 4), so we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;sayhelloworld&quot;, dictionary = [&quot;hello&quot;,&quot;world&quot;] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can break s in two substrings: &quot;hello&quot; from index 3 to 7 and &quot;world&quot; from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 50</code></li> <li><code>dictionary[i]</code>&nbsp;and <code>s</code> consists of only lowercase English letters</li> <li><code>dictionary</code> contains distinct words</li> </ul>
Trie; Array; Hash Table; String; Dynamic Programming
Python
class Solution: def minExtraChar(self, s: str, dictionary: List[str]) -> int: ss = set(dictionary) n = len(s) f = [0] * (n + 1) for i in range(1, n + 1): f[i] = f[i - 1] + 1 for j in range(i): if s[j:i] in ss and f[j] < f[i]: f[i] = f[j] return f[n]
2,707
Extra Characters in a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>s</code> and a dictionary of words <code>dictionary</code>. You have to break <code>s</code> into one or more <strong>non-overlapping</strong> substrings such that each substring is present in <code>dictionary</code>. There may be some <strong>extra characters</strong> in <code>s</code> which are not present in any of the substrings.</p> <p>Return <em>the <strong>minimum</strong> number of extra characters left over if you break up </em><code>s</code><em> optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;leetscode&quot;, dictionary = [&quot;leet&quot;,&quot;code&quot;,&quot;leetcode&quot;] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can break s in two substrings: &quot;leet&quot; from index 0 to 3 and &quot;code&quot; from index 5 to 8. There is only 1 unused character (at index 4), so we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;sayhelloworld&quot;, dictionary = [&quot;hello&quot;,&quot;world&quot;] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can break s in two substrings: &quot;hello&quot; from index 3 to 7 and &quot;world&quot; from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 50</code></li> <li><code>dictionary[i]</code>&nbsp;and <code>s</code> consists of only lowercase English letters</li> <li><code>dictionary</code> contains distinct words</li> </ul>
Trie; Array; Hash Table; String; Dynamic Programming
Rust
use std::collections::HashSet; impl Solution { pub fn min_extra_char(s: String, dictionary: Vec<String>) -> i32 { let ss: HashSet<String> = dictionary.into_iter().collect(); let n = s.len(); let mut f = vec![0; n + 1]; for i in 1..=n { f[i] = f[i - 1] + 1; for j in 0..i { if ss.contains(&s[j..i]) { f[i] = f[i].min(f[j]); } } } f[n] } }
2,707
Extra Characters in a String
Medium
<p>You are given a <strong>0-indexed</strong> string <code>s</code> and a dictionary of words <code>dictionary</code>. You have to break <code>s</code> into one or more <strong>non-overlapping</strong> substrings such that each substring is present in <code>dictionary</code>. There may be some <strong>extra characters</strong> in <code>s</code> which are not present in any of the substrings.</p> <p>Return <em>the <strong>minimum</strong> number of extra characters left over if you break up </em><code>s</code><em> optimally.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;leetscode&quot;, dictionary = [&quot;leet&quot;,&quot;code&quot;,&quot;leetcode&quot;] <strong>Output:</strong> 1 <strong>Explanation:</strong> We can break s in two substrings: &quot;leet&quot; from index 0 to 3 and &quot;code&quot; from index 5 to 8. There is only 1 unused character (at index 4), so we return 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;sayhelloworld&quot;, dictionary = [&quot;hello&quot;,&quot;world&quot;] <strong>Output:</strong> 3 <strong>Explanation:</strong> We can break s in two substrings: &quot;hello&quot; from index 3 to 7 and &quot;world&quot; from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary.length &lt;= 50</code></li> <li><code>1 &lt;= dictionary[i].length &lt;= 50</code></li> <li><code>dictionary[i]</code>&nbsp;and <code>s</code> consists of only lowercase English letters</li> <li><code>dictionary</code> contains distinct words</li> </ul>
Trie; Array; Hash Table; String; Dynamic Programming
TypeScript
function minExtraChar(s: string, dictionary: string[]): number { const ss = new Set(dictionary); const n = s.length; const f = new Array(n + 1).fill(0); for (let i = 1; i <= n; ++i) { f[i] = f[i - 1] + 1; for (let j = 0; j < i; ++j) { if (ss.has(s.substring(j, i))) { f[i] = Math.min(f[i], f[j]); } } } return f[n]; }
2,708
Maximum Strength of a Group
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the score of students in an exam. The teacher would like to form one <strong>non-empty</strong> group of students with maximal <strong>strength</strong>, where the strength of a group of students of indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, <code>i<sub>2</sub></code>, ... , <code>i<sub>k</sub></code> is defined as <code>nums[i<sub>0</sub>] * nums[i<sub>1</sub>] * nums[i<sub>2</sub>] * ... * nums[i<sub>k</sub>​]</code>.</p> <p>Return <em>the maximum strength of a group the teacher can create</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,-1,-5,2,5,-9] <strong>Output:</strong> 1350 <strong>Explanation:</strong> One way to form a group of maximal strength is to group the students at indices [0,2,3,4,5]. Their strength is 3 * (-5) * 2 * 5 * (-9) = 1350, which we can show is optimal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-4,-5,-4] <strong>Output:</strong> 20 <strong>Explanation:</strong> Group the students at indices [0, 1] . Then, we&rsquo;ll have a resulting strength of 20. We cannot achieve greater strength. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 13</code></li> <li><code>-9 &lt;= nums[i] &lt;= 9</code></li> </ul>
Greedy; Bit Manipulation; Array; Dynamic Programming; Backtracking; Enumeration; Sorting
C++
class Solution { public: long long maxStrength(vector<int>& nums) { long long ans = -1e14; int n = nums.size(); for (int i = 1; i < 1 << n; ++i) { long long t = 1; for (int j = 0; j < n; ++j) { if (i >> j & 1) { t *= nums[j]; } } ans = max(ans, t); } return ans; } };
2,708
Maximum Strength of a Group
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the score of students in an exam. The teacher would like to form one <strong>non-empty</strong> group of students with maximal <strong>strength</strong>, where the strength of a group of students of indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, <code>i<sub>2</sub></code>, ... , <code>i<sub>k</sub></code> is defined as <code>nums[i<sub>0</sub>] * nums[i<sub>1</sub>] * nums[i<sub>2</sub>] * ... * nums[i<sub>k</sub>​]</code>.</p> <p>Return <em>the maximum strength of a group the teacher can create</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,-1,-5,2,5,-9] <strong>Output:</strong> 1350 <strong>Explanation:</strong> One way to form a group of maximal strength is to group the students at indices [0,2,3,4,5]. Their strength is 3 * (-5) * 2 * 5 * (-9) = 1350, which we can show is optimal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-4,-5,-4] <strong>Output:</strong> 20 <strong>Explanation:</strong> Group the students at indices [0, 1] . Then, we&rsquo;ll have a resulting strength of 20. We cannot achieve greater strength. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 13</code></li> <li><code>-9 &lt;= nums[i] &lt;= 9</code></li> </ul>
Greedy; Bit Manipulation; Array; Dynamic Programming; Backtracking; Enumeration; Sorting
Go
func maxStrength(nums []int) int64 { ans := int64(-1e14) for i := 1; i < 1<<len(nums); i++ { var t int64 = 1 for j, x := range nums { if i>>j&1 == 1 { t *= int64(x) } } ans = max(ans, t) } return ans }
2,708
Maximum Strength of a Group
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> representing the score of students in an exam. The teacher would like to form one <strong>non-empty</strong> group of students with maximal <strong>strength</strong>, where the strength of a group of students of indices <code>i<sub>0</sub></code>, <code>i<sub>1</sub></code>, <code>i<sub>2</sub></code>, ... , <code>i<sub>k</sub></code> is defined as <code>nums[i<sub>0</sub>] * nums[i<sub>1</sub>] * nums[i<sub>2</sub>] * ... * nums[i<sub>k</sub>​]</code>.</p> <p>Return <em>the maximum strength of a group the teacher can create</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,-1,-5,2,5,-9] <strong>Output:</strong> 1350 <strong>Explanation:</strong> One way to form a group of maximal strength is to group the students at indices [0,2,3,4,5]. Their strength is 3 * (-5) * 2 * 5 * (-9) = 1350, which we can show is optimal. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-4,-5,-4] <strong>Output:</strong> 20 <strong>Explanation:</strong> Group the students at indices [0, 1] . Then, we&rsquo;ll have a resulting strength of 20. We cannot achieve greater strength. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 13</code></li> <li><code>-9 &lt;= nums[i] &lt;= 9</code></li> </ul>
Greedy; Bit Manipulation; Array; Dynamic Programming; Backtracking; Enumeration; Sorting
Java
class Solution { public long maxStrength(int[] nums) { long ans = (long) -1e14; int n = nums.length; for (int i = 1; i < 1 << n; ++i) { long t = 1; for (int j = 0; j < n; ++j) { if ((i >> j & 1) == 1) { t *= nums[j]; } } ans = Math.max(ans, t); } return ans; } }