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,654
Minimum Number of Operations to Make All Array Elements Equal to 1
Medium
<p>You are given a <strong>0-indexed</strong>&nbsp;array <code>nums</code> consisiting of <strong>positive</strong> integers. You can do the following operation on the array <strong>any</strong> number of times:</p> <ul> <li>Select an index <code>i</code> such that <code>0 &lt;= i &lt; n - 1</code> and replace either of&nbsp;<code>nums[i]</code> or <code>nums[i+1]</code> with their gcd value.</li> </ul> <p>Return <em>the <strong>minimum</strong> number of operations to make all elements of </em><code>nums</code><em> equal to </em><code>1</code>. If it is impossible, return <code>-1</code>.</p> <p>The gcd of two integers is the greatest common divisor of the two integers.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,3,4] <strong>Output:</strong> 4 <strong>Explanation:</strong> We can do the following operations: - Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4]. - Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4]. - Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4]. - Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,10,6,14] <strong>Output:</strong> -1 <strong>Explanation:</strong> It can be shown that it is impossible to make all the elements equal to 1. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> </ul>
Array; Math; Number Theory
TypeScript
function minOperations(nums: number[]): number { const n = nums.length; let cnt = 0; for (const x of nums) { if (x === 1) { ++cnt; } } if (cnt > 0) { return n - cnt; } let mi = n + 1; for (let i = 0; i < n; ++i) { let g = 0; for (let j = i; j < n; ++j) { g = gcd(g, nums[j]); if (g === 1) { mi = Math.min(mi, j - i + 1); } } } return mi > n ? -1 : n - 1 + mi - 1; } function gcd(a: number, b: number): number { return b === 0 ? a : gcd(b, a % b); }
2,655
Find Maximal Uncovered Ranges
Medium
<p>You are given&nbsp;an integer <code>n</code>&nbsp;which is the length of a <strong>0-indexed</strong> array <code>nums</code>, and a <strong>0-indexed</strong> 2D-array <code>ranges</code>, which is a list of sub-ranges of <code>nums</code>&nbsp;(sub-ranges may <strong>overlap</strong>).</p> <p>Each row <code>ranges[i]</code> has exactly 2 cells:</p> <ul> <li><code>ranges[i][0]</code>, which shows the start of the i<sup>th</sup> range (inclusive)</li> <li><code>ranges[i][1]</code>, which shows the end of the i<sup>th</sup> range (inclusive)</li> </ul> <p>These ranges cover some cells of <code>nums</code>&nbsp;and leave&nbsp;some cells uncovered. Your task is to find all of the <b>uncovered </b>ranges with <strong>maximal</strong> length.</p> <p>Return <em>a 2D-array </em><code>answer</code><em> of the uncovered ranges, <strong>sorted</strong> by the starting point in <strong>ascending order</strong>.</em></p> <p>By all of the&nbsp;<strong>uncovered</strong> ranges with <strong>maximal</strong> length, we mean satisfying two conditions:</p> <ul> <li>Each uncovered cell should belong to <strong>exactly</strong> one sub-range</li> <li>There should <strong>not exist</strong>&nbsp;two ranges (l<sub>1</sub>, r<sub>1</sub>) and (l<sub>2</sub>, r<sub>2</sub>) such that r<sub>1 </sub>+ 1 = l<sub>2</sub></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, ranges = [[3,5],[7,8]] <strong>Output:</strong> [[0,2],[6,6],[9,9]] <strong>Explanation:</strong> The ranges (3, 5) and (7, 8) are covered, so if we simplify the array nums to a binary array where 0 shows an uncovered cell and 1 shows a covered cell, the array becomes [0,0,0,1,1,1,0,1,1,0] in which we can observe that the ranges (0, 2), (6, 6) and (9, 9) aren&#39;t covered. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, ranges = [[0,2]] <strong>Output:</strong> [] <strong>Explanation: </strong>In this example, the whole of the array nums is covered and there are no uncovered cells so the output is an empty array. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 7, ranges = [[2,4],[0,3]] <strong>Output:</strong> [[5,6]] <strong>Explanation:</strong> The ranges (0, 3) and (2, 4) are covered, so if we simplify the array nums to a binary array where 0 shows an uncovered cell and 1 shows a covered cell, the array becomes [1,1,1,1,1,0,0] in which we can observe that the range (5, 6) is uncovered. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;=&nbsp;10<sup>9</sup></code></li> <li><code>0 &lt;= ranges.length &lt;= 10<sup>6</sup></code></li> <li><code>ranges[i].length = 2</code></li> <li><code>0 &lt;= ranges[i][j] &lt;= n - 1</code></li> <li><code>ranges[i][0] &lt;=&nbsp;ranges[i][1]</code></li> </ul>
Array; Sorting
C++
class Solution { public: vector<vector<int>> findMaximalUncoveredRanges(int n, vector<vector<int>>& ranges) { sort(ranges.begin(), ranges.end(), [](const vector<int>& a, const vector<int>& b) { return a[0] < b[0]; }); int last = -1; vector<vector<int>> ans; for (auto& range : ranges) { int l = range[0], r = range[1]; if (last + 1 < l) { ans.push_back({last + 1, l - 1}); } last = max(last, r); } if (last + 1 < n) { ans.push_back({last + 1, n - 1}); } return ans; } };
2,655
Find Maximal Uncovered Ranges
Medium
<p>You are given&nbsp;an integer <code>n</code>&nbsp;which is the length of a <strong>0-indexed</strong> array <code>nums</code>, and a <strong>0-indexed</strong> 2D-array <code>ranges</code>, which is a list of sub-ranges of <code>nums</code>&nbsp;(sub-ranges may <strong>overlap</strong>).</p> <p>Each row <code>ranges[i]</code> has exactly 2 cells:</p> <ul> <li><code>ranges[i][0]</code>, which shows the start of the i<sup>th</sup> range (inclusive)</li> <li><code>ranges[i][1]</code>, which shows the end of the i<sup>th</sup> range (inclusive)</li> </ul> <p>These ranges cover some cells of <code>nums</code>&nbsp;and leave&nbsp;some cells uncovered. Your task is to find all of the <b>uncovered </b>ranges with <strong>maximal</strong> length.</p> <p>Return <em>a 2D-array </em><code>answer</code><em> of the uncovered ranges, <strong>sorted</strong> by the starting point in <strong>ascending order</strong>.</em></p> <p>By all of the&nbsp;<strong>uncovered</strong> ranges with <strong>maximal</strong> length, we mean satisfying two conditions:</p> <ul> <li>Each uncovered cell should belong to <strong>exactly</strong> one sub-range</li> <li>There should <strong>not exist</strong>&nbsp;two ranges (l<sub>1</sub>, r<sub>1</sub>) and (l<sub>2</sub>, r<sub>2</sub>) such that r<sub>1 </sub>+ 1 = l<sub>2</sub></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, ranges = [[3,5],[7,8]] <strong>Output:</strong> [[0,2],[6,6],[9,9]] <strong>Explanation:</strong> The ranges (3, 5) and (7, 8) are covered, so if we simplify the array nums to a binary array where 0 shows an uncovered cell and 1 shows a covered cell, the array becomes [0,0,0,1,1,1,0,1,1,0] in which we can observe that the ranges (0, 2), (6, 6) and (9, 9) aren&#39;t covered. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, ranges = [[0,2]] <strong>Output:</strong> [] <strong>Explanation: </strong>In this example, the whole of the array nums is covered and there are no uncovered cells so the output is an empty array. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 7, ranges = [[2,4],[0,3]] <strong>Output:</strong> [[5,6]] <strong>Explanation:</strong> The ranges (0, 3) and (2, 4) are covered, so if we simplify the array nums to a binary array where 0 shows an uncovered cell and 1 shows a covered cell, the array becomes [1,1,1,1,1,0,0] in which we can observe that the range (5, 6) is uncovered. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;=&nbsp;10<sup>9</sup></code></li> <li><code>0 &lt;= ranges.length &lt;= 10<sup>6</sup></code></li> <li><code>ranges[i].length = 2</code></li> <li><code>0 &lt;= ranges[i][j] &lt;= n - 1</code></li> <li><code>ranges[i][0] &lt;=&nbsp;ranges[i][1]</code></li> </ul>
Array; Sorting
Go
func findMaximalUncoveredRanges(n int, ranges [][]int) (ans [][]int) { sort.Slice(ranges, func(i, j int) bool { return ranges[i][0] < ranges[j][0] }) last := -1 for _, r := range ranges { if last+1 < r[0] { ans = append(ans, []int{last + 1, r[0] - 1}) } last = max(last, r[1]) } if last+1 < n { ans = append(ans, []int{last + 1, n - 1}) } return }
2,655
Find Maximal Uncovered Ranges
Medium
<p>You are given&nbsp;an integer <code>n</code>&nbsp;which is the length of a <strong>0-indexed</strong> array <code>nums</code>, and a <strong>0-indexed</strong> 2D-array <code>ranges</code>, which is a list of sub-ranges of <code>nums</code>&nbsp;(sub-ranges may <strong>overlap</strong>).</p> <p>Each row <code>ranges[i]</code> has exactly 2 cells:</p> <ul> <li><code>ranges[i][0]</code>, which shows the start of the i<sup>th</sup> range (inclusive)</li> <li><code>ranges[i][1]</code>, which shows the end of the i<sup>th</sup> range (inclusive)</li> </ul> <p>These ranges cover some cells of <code>nums</code>&nbsp;and leave&nbsp;some cells uncovered. Your task is to find all of the <b>uncovered </b>ranges with <strong>maximal</strong> length.</p> <p>Return <em>a 2D-array </em><code>answer</code><em> of the uncovered ranges, <strong>sorted</strong> by the starting point in <strong>ascending order</strong>.</em></p> <p>By all of the&nbsp;<strong>uncovered</strong> ranges with <strong>maximal</strong> length, we mean satisfying two conditions:</p> <ul> <li>Each uncovered cell should belong to <strong>exactly</strong> one sub-range</li> <li>There should <strong>not exist</strong>&nbsp;two ranges (l<sub>1</sub>, r<sub>1</sub>) and (l<sub>2</sub>, r<sub>2</sub>) such that r<sub>1 </sub>+ 1 = l<sub>2</sub></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, ranges = [[3,5],[7,8]] <strong>Output:</strong> [[0,2],[6,6],[9,9]] <strong>Explanation:</strong> The ranges (3, 5) and (7, 8) are covered, so if we simplify the array nums to a binary array where 0 shows an uncovered cell and 1 shows a covered cell, the array becomes [0,0,0,1,1,1,0,1,1,0] in which we can observe that the ranges (0, 2), (6, 6) and (9, 9) aren&#39;t covered. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, ranges = [[0,2]] <strong>Output:</strong> [] <strong>Explanation: </strong>In this example, the whole of the array nums is covered and there are no uncovered cells so the output is an empty array. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 7, ranges = [[2,4],[0,3]] <strong>Output:</strong> [[5,6]] <strong>Explanation:</strong> The ranges (0, 3) and (2, 4) are covered, so if we simplify the array nums to a binary array where 0 shows an uncovered cell and 1 shows a covered cell, the array becomes [1,1,1,1,1,0,0] in which we can observe that the range (5, 6) is uncovered. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;=&nbsp;10<sup>9</sup></code></li> <li><code>0 &lt;= ranges.length &lt;= 10<sup>6</sup></code></li> <li><code>ranges[i].length = 2</code></li> <li><code>0 &lt;= ranges[i][j] &lt;= n - 1</code></li> <li><code>ranges[i][0] &lt;=&nbsp;ranges[i][1]</code></li> </ul>
Array; Sorting
Java
class Solution { public int[][] findMaximalUncoveredRanges(int n, int[][] ranges) { Arrays.sort(ranges, (a, b) -> a[0] - b[0]); int last = -1; List<int[]> ans = new ArrayList<>(); for (int[] range : ranges) { int l = range[0], r = range[1]; if (last + 1 < l) { ans.add(new int[] {last + 1, l - 1}); } last = Math.max(last, r); } if (last + 1 < n) { ans.add(new int[] {last + 1, n - 1}); } return ans.toArray(new int[0][]); } }
2,655
Find Maximal Uncovered Ranges
Medium
<p>You are given&nbsp;an integer <code>n</code>&nbsp;which is the length of a <strong>0-indexed</strong> array <code>nums</code>, and a <strong>0-indexed</strong> 2D-array <code>ranges</code>, which is a list of sub-ranges of <code>nums</code>&nbsp;(sub-ranges may <strong>overlap</strong>).</p> <p>Each row <code>ranges[i]</code> has exactly 2 cells:</p> <ul> <li><code>ranges[i][0]</code>, which shows the start of the i<sup>th</sup> range (inclusive)</li> <li><code>ranges[i][1]</code>, which shows the end of the i<sup>th</sup> range (inclusive)</li> </ul> <p>These ranges cover some cells of <code>nums</code>&nbsp;and leave&nbsp;some cells uncovered. Your task is to find all of the <b>uncovered </b>ranges with <strong>maximal</strong> length.</p> <p>Return <em>a 2D-array </em><code>answer</code><em> of the uncovered ranges, <strong>sorted</strong> by the starting point in <strong>ascending order</strong>.</em></p> <p>By all of the&nbsp;<strong>uncovered</strong> ranges with <strong>maximal</strong> length, we mean satisfying two conditions:</p> <ul> <li>Each uncovered cell should belong to <strong>exactly</strong> one sub-range</li> <li>There should <strong>not exist</strong>&nbsp;two ranges (l<sub>1</sub>, r<sub>1</sub>) and (l<sub>2</sub>, r<sub>2</sub>) such that r<sub>1 </sub>+ 1 = l<sub>2</sub></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 10, ranges = [[3,5],[7,8]] <strong>Output:</strong> [[0,2],[6,6],[9,9]] <strong>Explanation:</strong> The ranges (3, 5) and (7, 8) are covered, so if we simplify the array nums to a binary array where 0 shows an uncovered cell and 1 shows a covered cell, the array becomes [0,0,0,1,1,1,0,1,1,0] in which we can observe that the ranges (0, 2), (6, 6) and (9, 9) aren&#39;t covered. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 3, ranges = [[0,2]] <strong>Output:</strong> [] <strong>Explanation: </strong>In this example, the whole of the array nums is covered and there are no uncovered cells so the output is an empty array. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 7, ranges = [[2,4],[0,3]] <strong>Output:</strong> [[5,6]] <strong>Explanation:</strong> The ranges (0, 3) and (2, 4) are covered, so if we simplify the array nums to a binary array where 0 shows an uncovered cell and 1 shows a covered cell, the array becomes [1,1,1,1,1,0,0] in which we can observe that the range (5, 6) is uncovered. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;=&nbsp;10<sup>9</sup></code></li> <li><code>0 &lt;= ranges.length &lt;= 10<sup>6</sup></code></li> <li><code>ranges[i].length = 2</code></li> <li><code>0 &lt;= ranges[i][j] &lt;= n - 1</code></li> <li><code>ranges[i][0] &lt;=&nbsp;ranges[i][1]</code></li> </ul>
Array; Sorting
Python
class Solution: def findMaximalUncoveredRanges( self, n: int, ranges: List[List[int]] ) -> List[List[int]]: ranges.sort() last = -1 ans = [] for l, r in ranges: if last + 1 < l: ans.append([last + 1, l - 1]) last = max(last, r) if last + 1 < n: ans.append([last + 1, n - 1]) return ans
2,656
Maximum Sum With Exactly K Elements
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>. Your task is to perform the following operation <strong>exactly</strong> <code>k</code> times in order to maximize your score:</p> <ol> <li>Select an element <code>m</code> from <code>nums</code>.</li> <li>Remove the selected element <code>m</code> from the array.</li> <li>Add a new element with a value of <code>m + 1</code> to the array.</li> <li>Increase your score by <code>m</code>.</li> </ol> <p>Return <em>the maximum score you can achieve after performing the operation exactly</em> <code>k</code> <em>times.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 3 <strong>Output:</strong> 18 <strong>Explanation:</strong> We need to choose exactly 3 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [1,2,3,4,6] For the second iteration, we choose 6. Then sum is 5 + 6 and nums = [1,2,3,4,7] For the third iteration, we choose 7. Then sum is 5 + 6 + 7 = 18 and nums = [1,2,3,4,8] So, we will return 18. It can be proven, that 18 is the maximum answer that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5], k = 2 <strong>Output:</strong> 11 <strong>Explanation:</strong> We need to choose exactly 2 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [5,5,6] For the second iteration, we choose 6. Then sum is 5 + 6 = 11 and nums = [5,5,7] So, we will return 11. It can be proven, that 11 is the maximum answer that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Greedy; Array
C++
class Solution { public: int maximizeSum(vector<int>& nums, int k) { int x = *max_element(nums.begin(), nums.end()); return k * x + k * (k - 1) / 2; } };
2,656
Maximum Sum With Exactly K Elements
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>. Your task is to perform the following operation <strong>exactly</strong> <code>k</code> times in order to maximize your score:</p> <ol> <li>Select an element <code>m</code> from <code>nums</code>.</li> <li>Remove the selected element <code>m</code> from the array.</li> <li>Add a new element with a value of <code>m + 1</code> to the array.</li> <li>Increase your score by <code>m</code>.</li> </ol> <p>Return <em>the maximum score you can achieve after performing the operation exactly</em> <code>k</code> <em>times.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 3 <strong>Output:</strong> 18 <strong>Explanation:</strong> We need to choose exactly 3 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [1,2,3,4,6] For the second iteration, we choose 6. Then sum is 5 + 6 and nums = [1,2,3,4,7] For the third iteration, we choose 7. Then sum is 5 + 6 + 7 = 18 and nums = [1,2,3,4,8] So, we will return 18. It can be proven, that 18 is the maximum answer that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5], k = 2 <strong>Output:</strong> 11 <strong>Explanation:</strong> We need to choose exactly 2 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [5,5,6] For the second iteration, we choose 6. Then sum is 5 + 6 = 11 and nums = [5,5,7] So, we will return 11. It can be proven, that 11 is the maximum answer that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Greedy; Array
Go
func maximizeSum(nums []int, k int) int { x := slices.Max(nums) return k*x + k*(k-1)/2 }
2,656
Maximum Sum With Exactly K Elements
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>. Your task is to perform the following operation <strong>exactly</strong> <code>k</code> times in order to maximize your score:</p> <ol> <li>Select an element <code>m</code> from <code>nums</code>.</li> <li>Remove the selected element <code>m</code> from the array.</li> <li>Add a new element with a value of <code>m + 1</code> to the array.</li> <li>Increase your score by <code>m</code>.</li> </ol> <p>Return <em>the maximum score you can achieve after performing the operation exactly</em> <code>k</code> <em>times.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 3 <strong>Output:</strong> 18 <strong>Explanation:</strong> We need to choose exactly 3 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [1,2,3,4,6] For the second iteration, we choose 6. Then sum is 5 + 6 and nums = [1,2,3,4,7] For the third iteration, we choose 7. Then sum is 5 + 6 + 7 = 18 and nums = [1,2,3,4,8] So, we will return 18. It can be proven, that 18 is the maximum answer that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5], k = 2 <strong>Output:</strong> 11 <strong>Explanation:</strong> We need to choose exactly 2 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [5,5,6] For the second iteration, we choose 6. Then sum is 5 + 6 = 11 and nums = [5,5,7] So, we will return 11. It can be proven, that 11 is the maximum answer that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Greedy; Array
Java
class Solution { public int maximizeSum(int[] nums, int k) { int x = 0; for (int v : nums) { x = Math.max(x, v); } return k * x + k * (k - 1) / 2; } }
2,656
Maximum Sum With Exactly K Elements
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>. Your task is to perform the following operation <strong>exactly</strong> <code>k</code> times in order to maximize your score:</p> <ol> <li>Select an element <code>m</code> from <code>nums</code>.</li> <li>Remove the selected element <code>m</code> from the array.</li> <li>Add a new element with a value of <code>m + 1</code> to the array.</li> <li>Increase your score by <code>m</code>.</li> </ol> <p>Return <em>the maximum score you can achieve after performing the operation exactly</em> <code>k</code> <em>times.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 3 <strong>Output:</strong> 18 <strong>Explanation:</strong> We need to choose exactly 3 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [1,2,3,4,6] For the second iteration, we choose 6. Then sum is 5 + 6 and nums = [1,2,3,4,7] For the third iteration, we choose 7. Then sum is 5 + 6 + 7 = 18 and nums = [1,2,3,4,8] So, we will return 18. It can be proven, that 18 is the maximum answer that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5], k = 2 <strong>Output:</strong> 11 <strong>Explanation:</strong> We need to choose exactly 2 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [5,5,6] For the second iteration, we choose 6. Then sum is 5 + 6 = 11 and nums = [5,5,7] So, we will return 11. It can be proven, that 11 is the maximum answer that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Greedy; Array
Python
class Solution: def maximizeSum(self, nums: List[int], k: int) -> int: x = max(nums) return k * x + k * (k - 1) // 2
2,656
Maximum Sum With Exactly K Elements
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>. Your task is to perform the following operation <strong>exactly</strong> <code>k</code> times in order to maximize your score:</p> <ol> <li>Select an element <code>m</code> from <code>nums</code>.</li> <li>Remove the selected element <code>m</code> from the array.</li> <li>Add a new element with a value of <code>m + 1</code> to the array.</li> <li>Increase your score by <code>m</code>.</li> </ol> <p>Return <em>the maximum score you can achieve after performing the operation exactly</em> <code>k</code> <em>times.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 3 <strong>Output:</strong> 18 <strong>Explanation:</strong> We need to choose exactly 3 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [1,2,3,4,6] For the second iteration, we choose 6. Then sum is 5 + 6 and nums = [1,2,3,4,7] For the third iteration, we choose 7. Then sum is 5 + 6 + 7 = 18 and nums = [1,2,3,4,8] So, we will return 18. It can be proven, that 18 is the maximum answer that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5], k = 2 <strong>Output:</strong> 11 <strong>Explanation:</strong> We need to choose exactly 2 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [5,5,6] For the second iteration, we choose 6. Then sum is 5 + 6 = 11 and nums = [5,5,7] So, we will return 11. It can be proven, that 11 is the maximum answer that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Greedy; Array
Rust
impl Solution { pub fn maximize_sum(nums: Vec<i32>, k: i32) -> i32 { let mut mx = 0; for &n in &nums { if n > mx { mx = n; } } ((0 + k - 1) * k) / 2 + k * mx } }
2,656
Maximum Sum With Exactly K Elements
Easy
<p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>. Your task is to perform the following operation <strong>exactly</strong> <code>k</code> times in order to maximize your score:</p> <ol> <li>Select an element <code>m</code> from <code>nums</code>.</li> <li>Remove the selected element <code>m</code> from the array.</li> <li>Add a new element with a value of <code>m + 1</code> to the array.</li> <li>Increase your score by <code>m</code>.</li> </ol> <p>Return <em>the maximum score you can achieve after performing the operation exactly</em> <code>k</code> <em>times.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5], k = 3 <strong>Output:</strong> 18 <strong>Explanation:</strong> We need to choose exactly 3 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [1,2,3,4,6] For the second iteration, we choose 6. Then sum is 5 + 6 and nums = [1,2,3,4,7] For the third iteration, we choose 7. Then sum is 5 + 6 + 7 = 18 and nums = [1,2,3,4,8] So, we will return 18. It can be proven, that 18 is the maximum answer that we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [5,5,5], k = 2 <strong>Output:</strong> 11 <strong>Explanation:</strong> We need to choose exactly 2 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [5,5,6] For the second iteration, we choose 6. Then sum is 5 + 6 = 11 and nums = [5,5,7] So, we will return 11. It can be proven, that 11 is the maximum answer that we can achieve. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>1 &lt;= nums[i] &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul> <p>&nbsp;</p> <style type="text/css">.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton[value="Show Message"] + .spoiler > div {margin-top:-500%;} .spoilerbutton[value="Hide Message"] + .spoiler {padding:5px;} </style>
Greedy; Array
TypeScript
function maximizeSum(nums: number[], k: number): number { const x = Math.max(...nums); return k * x + (k * (k - 1)) / 2; }
2,657
Find the Prefix Common Array of Two Arrays
Medium
<p>You are given two <strong>0-indexed </strong>integer<strong> </strong>permutations <code>A</code> and <code>B</code> of length <code>n</code>.</p> <p>A <strong>prefix common array</strong> of <code>A</code> and <code>B</code> is an array <code>C</code> such that <code>C[i]</code> is equal to the count of numbers that are present at or before the index <code>i</code> in both <code>A</code> and <code>B</code>.</p> <p>Return <em>the <strong>prefix common array</strong> of </em><code>A</code><em> and </em><code>B</code>.</p> <p>A sequence of <code>n</code> integers is called a&nbsp;<strong>permutation</strong> if it contains all integers from <code>1</code> to <code>n</code> exactly once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> A = [1,3,2,4], B = [3,1,2,4] <strong>Output:</strong> [0,2,3,4] <strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0. At i = 1: 1 and 3 are common in A and B, so C[1] = 2. At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3. At i = 3: 1, 2, 3, and 4 are common in A and B, so C[3] = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> A = [2,3,1], B = [3,1,2] <strong>Output:</strong> [0,1,3] <strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0. At i = 1: only 3 is common in A and B, so C[1] = 1. At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= A.length == B.length == n &lt;= 50</code></li> <li><code>1 &lt;= A[i], B[i] &lt;= n</code></li> <li><code>It is guaranteed that A and B are both a permutation of n integers.</code></li> </ul>
Bit Manipulation; Array; Hash Table
C++
class Solution { public: vector<int> findThePrefixCommonArray(vector<int>& A, vector<int>& B) { int n = A.size(); vector<int> ans(n); vector<int> cnt1(n + 1), cnt2(n + 1); for (int i = 0; i < n; ++i) { ++cnt1[A[i]]; ++cnt2[B[i]]; for (int j = 1; j <= n; ++j) { ans[i] += min(cnt1[j], cnt2[j]); } } return ans; } };
2,657
Find the Prefix Common Array of Two Arrays
Medium
<p>You are given two <strong>0-indexed </strong>integer<strong> </strong>permutations <code>A</code> and <code>B</code> of length <code>n</code>.</p> <p>A <strong>prefix common array</strong> of <code>A</code> and <code>B</code> is an array <code>C</code> such that <code>C[i]</code> is equal to the count of numbers that are present at or before the index <code>i</code> in both <code>A</code> and <code>B</code>.</p> <p>Return <em>the <strong>prefix common array</strong> of </em><code>A</code><em> and </em><code>B</code>.</p> <p>A sequence of <code>n</code> integers is called a&nbsp;<strong>permutation</strong> if it contains all integers from <code>1</code> to <code>n</code> exactly once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> A = [1,3,2,4], B = [3,1,2,4] <strong>Output:</strong> [0,2,3,4] <strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0. At i = 1: 1 and 3 are common in A and B, so C[1] = 2. At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3. At i = 3: 1, 2, 3, and 4 are common in A and B, so C[3] = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> A = [2,3,1], B = [3,1,2] <strong>Output:</strong> [0,1,3] <strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0. At i = 1: only 3 is common in A and B, so C[1] = 1. At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= A.length == B.length == n &lt;= 50</code></li> <li><code>1 &lt;= A[i], B[i] &lt;= n</code></li> <li><code>It is guaranteed that A and B are both a permutation of n integers.</code></li> </ul>
Bit Manipulation; Array; Hash Table
Go
func findThePrefixCommonArray(A []int, B []int) []int { n := len(A) cnt1 := make([]int, n+1) cnt2 := make([]int, n+1) ans := make([]int, n) for i, a := range A { b := B[i] cnt1[a]++ cnt2[b]++ for j := 1; j <= n; j++ { ans[i] += min(cnt1[j], cnt2[j]) } } return ans }
2,657
Find the Prefix Common Array of Two Arrays
Medium
<p>You are given two <strong>0-indexed </strong>integer<strong> </strong>permutations <code>A</code> and <code>B</code> of length <code>n</code>.</p> <p>A <strong>prefix common array</strong> of <code>A</code> and <code>B</code> is an array <code>C</code> such that <code>C[i]</code> is equal to the count of numbers that are present at or before the index <code>i</code> in both <code>A</code> and <code>B</code>.</p> <p>Return <em>the <strong>prefix common array</strong> of </em><code>A</code><em> and </em><code>B</code>.</p> <p>A sequence of <code>n</code> integers is called a&nbsp;<strong>permutation</strong> if it contains all integers from <code>1</code> to <code>n</code> exactly once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> A = [1,3,2,4], B = [3,1,2,4] <strong>Output:</strong> [0,2,3,4] <strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0. At i = 1: 1 and 3 are common in A and B, so C[1] = 2. At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3. At i = 3: 1, 2, 3, and 4 are common in A and B, so C[3] = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> A = [2,3,1], B = [3,1,2] <strong>Output:</strong> [0,1,3] <strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0. At i = 1: only 3 is common in A and B, so C[1] = 1. At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= A.length == B.length == n &lt;= 50</code></li> <li><code>1 &lt;= A[i], B[i] &lt;= n</code></li> <li><code>It is guaranteed that A and B are both a permutation of n integers.</code></li> </ul>
Bit Manipulation; Array; Hash Table
Java
class Solution { public int[] findThePrefixCommonArray(int[] A, int[] B) { int n = A.length; int[] ans = new int[n]; int[] cnt1 = new int[n + 1]; int[] cnt2 = new int[n + 1]; for (int i = 0; i < n; ++i) { ++cnt1[A[i]]; ++cnt2[B[i]]; for (int j = 1; j <= n; ++j) { ans[i] += Math.min(cnt1[j], cnt2[j]); } } return ans; } }
2,657
Find the Prefix Common Array of Two Arrays
Medium
<p>You are given two <strong>0-indexed </strong>integer<strong> </strong>permutations <code>A</code> and <code>B</code> of length <code>n</code>.</p> <p>A <strong>prefix common array</strong> of <code>A</code> and <code>B</code> is an array <code>C</code> such that <code>C[i]</code> is equal to the count of numbers that are present at or before the index <code>i</code> in both <code>A</code> and <code>B</code>.</p> <p>Return <em>the <strong>prefix common array</strong> of </em><code>A</code><em> and </em><code>B</code>.</p> <p>A sequence of <code>n</code> integers is called a&nbsp;<strong>permutation</strong> if it contains all integers from <code>1</code> to <code>n</code> exactly once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> A = [1,3,2,4], B = [3,1,2,4] <strong>Output:</strong> [0,2,3,4] <strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0. At i = 1: 1 and 3 are common in A and B, so C[1] = 2. At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3. At i = 3: 1, 2, 3, and 4 are common in A and B, so C[3] = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> A = [2,3,1], B = [3,1,2] <strong>Output:</strong> [0,1,3] <strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0. At i = 1: only 3 is common in A and B, so C[1] = 1. At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= A.length == B.length == n &lt;= 50</code></li> <li><code>1 &lt;= A[i], B[i] &lt;= n</code></li> <li><code>It is guaranteed that A and B are both a permutation of n integers.</code></li> </ul>
Bit Manipulation; Array; Hash Table
Python
class Solution: def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]: ans = [] cnt1 = Counter() cnt2 = Counter() for a, b in zip(A, B): cnt1[a] += 1 cnt2[b] += 1 t = sum(min(v, cnt2[x]) for x, v in cnt1.items()) ans.append(t) return ans
2,657
Find the Prefix Common Array of Two Arrays
Medium
<p>You are given two <strong>0-indexed </strong>integer<strong> </strong>permutations <code>A</code> and <code>B</code> of length <code>n</code>.</p> <p>A <strong>prefix common array</strong> of <code>A</code> and <code>B</code> is an array <code>C</code> such that <code>C[i]</code> is equal to the count of numbers that are present at or before the index <code>i</code> in both <code>A</code> and <code>B</code>.</p> <p>Return <em>the <strong>prefix common array</strong> of </em><code>A</code><em> and </em><code>B</code>.</p> <p>A sequence of <code>n</code> integers is called a&nbsp;<strong>permutation</strong> if it contains all integers from <code>1</code> to <code>n</code> exactly once.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> A = [1,3,2,4], B = [3,1,2,4] <strong>Output:</strong> [0,2,3,4] <strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0. At i = 1: 1 and 3 are common in A and B, so C[1] = 2. At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3. At i = 3: 1, 2, 3, and 4 are common in A and B, so C[3] = 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> A = [2,3,1], B = [3,1,2] <strong>Output:</strong> [0,1,3] <strong>Explanation:</strong> At i = 0: no number is common, so C[0] = 0. At i = 1: only 3 is common in A and B, so C[1] = 1. At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= A.length == B.length == n &lt;= 50</code></li> <li><code>1 &lt;= A[i], B[i] &lt;= n</code></li> <li><code>It is guaranteed that A and B are both a permutation of n integers.</code></li> </ul>
Bit Manipulation; Array; Hash Table
TypeScript
function findThePrefixCommonArray(A: number[], B: number[]): number[] { const n = A.length; const cnt1: number[] = Array(n + 1).fill(0); const cnt2: number[] = Array(n + 1).fill(0); const ans: number[] = Array(n).fill(0); for (let i = 0; i < n; ++i) { ++cnt1[A[i]]; ++cnt2[B[i]]; for (let j = 1; j <= n; ++j) { ans[i] += Math.min(cnt1[j], cnt2[j]); } } return ans; }
2,658
Maximum Number of Fish in a Grid
Medium
<p>You are given a <strong>0-indexed</strong> 2D matrix <code>grid</code> of size <code>m x n</code>, where <code>(r, c)</code> represents:</p> <ul> <li>A <strong>land</strong> cell if <code>grid[r][c] = 0</code>, or</li> <li>A <strong>water</strong> cell containing <code>grid[r][c]</code> fish, if <code>grid[r][c] &gt; 0</code>.</li> </ul> <p>A fisher can start at any <strong>water</strong> cell <code>(r, c)</code> and can do the following operations any number of times:</p> <ul> <li>Catch all the fish at cell <code>(r, c)</code>, or</li> <li>Move to any adjacent <strong>water</strong> cell.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of fish the fisher can catch if he chooses his starting cell optimally, or </em><code>0</code> if no water cell exists.</p> <p>An <strong>adjacent</strong> cell of the cell <code>(r, c)</code>, is one of the cells <code>(r, c + 1)</code>, <code>(r, c - 1)</code>, <code>(r + 1, c)</code> or <code>(r - 1, c)</code> if it exists.</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/2658.Maximum%20Number%20of%20Fish%20in%20a%20Grid/images/example.png" style="width: 241px; height: 161px;" /> <pre> <strong>Input:</strong> grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The fisher can start at cell <code>(1,3)</code> and collect 3 fish, then move to cell <code>(2,3)</code>&nbsp;and collect 4 fish. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2658.Maximum%20Number%20of%20Fish%20in%20a%20Grid/images/example2.png" /> <pre> <strong>Input:</strong> grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The fisher can start at cells (0,0) or (3,3) and collect a single fish. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
C++
class Solution { public: int findMaxFish(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); int ans = 0; function<int(int, int)> dfs = [&](int i, int j) -> int { int cnt = grid[i][j]; grid[i][j] = 0; int dirs[5] = {-1, 0, 1, 0, -1}; for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]) { cnt += dfs(x, y); } } return cnt; }; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j]) { ans = max(ans, dfs(i, j)); } } } return ans; } };
2,658
Maximum Number of Fish in a Grid
Medium
<p>You are given a <strong>0-indexed</strong> 2D matrix <code>grid</code> of size <code>m x n</code>, where <code>(r, c)</code> represents:</p> <ul> <li>A <strong>land</strong> cell if <code>grid[r][c] = 0</code>, or</li> <li>A <strong>water</strong> cell containing <code>grid[r][c]</code> fish, if <code>grid[r][c] &gt; 0</code>.</li> </ul> <p>A fisher can start at any <strong>water</strong> cell <code>(r, c)</code> and can do the following operations any number of times:</p> <ul> <li>Catch all the fish at cell <code>(r, c)</code>, or</li> <li>Move to any adjacent <strong>water</strong> cell.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of fish the fisher can catch if he chooses his starting cell optimally, or </em><code>0</code> if no water cell exists.</p> <p>An <strong>adjacent</strong> cell of the cell <code>(r, c)</code>, is one of the cells <code>(r, c + 1)</code>, <code>(r, c - 1)</code>, <code>(r + 1, c)</code> or <code>(r - 1, c)</code> if it exists.</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/2658.Maximum%20Number%20of%20Fish%20in%20a%20Grid/images/example.png" style="width: 241px; height: 161px;" /> <pre> <strong>Input:</strong> grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The fisher can start at cell <code>(1,3)</code> and collect 3 fish, then move to cell <code>(2,3)</code>&nbsp;and collect 4 fish. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2658.Maximum%20Number%20of%20Fish%20in%20a%20Grid/images/example2.png" /> <pre> <strong>Input:</strong> grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The fisher can start at cells (0,0) or (3,3) and collect a single fish. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
Go
func findMaxFish(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) dirs := [5]int{-1, 0, 1, 0, -1} var dfs func(i, j int) int dfs = func(i, j int) int { cnt := grid[i][j] grid[i][j] = 0 for k := 0; k < 4; k++ { x, y := i+dirs[k], j+dirs[k+1] if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] > 0 { cnt += dfs(x, y) } } return cnt } for i := range grid { for j := range grid[i] { if grid[i][j] > 0 { ans = max(ans, dfs(i, j)) } } } return }
2,658
Maximum Number of Fish in a Grid
Medium
<p>You are given a <strong>0-indexed</strong> 2D matrix <code>grid</code> of size <code>m x n</code>, where <code>(r, c)</code> represents:</p> <ul> <li>A <strong>land</strong> cell if <code>grid[r][c] = 0</code>, or</li> <li>A <strong>water</strong> cell containing <code>grid[r][c]</code> fish, if <code>grid[r][c] &gt; 0</code>.</li> </ul> <p>A fisher can start at any <strong>water</strong> cell <code>(r, c)</code> and can do the following operations any number of times:</p> <ul> <li>Catch all the fish at cell <code>(r, c)</code>, or</li> <li>Move to any adjacent <strong>water</strong> cell.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of fish the fisher can catch if he chooses his starting cell optimally, or </em><code>0</code> if no water cell exists.</p> <p>An <strong>adjacent</strong> cell of the cell <code>(r, c)</code>, is one of the cells <code>(r, c + 1)</code>, <code>(r, c - 1)</code>, <code>(r + 1, c)</code> or <code>(r - 1, c)</code> if it exists.</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/2658.Maximum%20Number%20of%20Fish%20in%20a%20Grid/images/example.png" style="width: 241px; height: 161px;" /> <pre> <strong>Input:</strong> grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The fisher can start at cell <code>(1,3)</code> and collect 3 fish, then move to cell <code>(2,3)</code>&nbsp;and collect 4 fish. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2658.Maximum%20Number%20of%20Fish%20in%20a%20Grid/images/example2.png" /> <pre> <strong>Input:</strong> grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The fisher can start at cells (0,0) or (3,3) and collect a single fish. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
Java
class Solution { private int[][] grid; private int m; private int n; public int findMaxFish(int[][] grid) { m = grid.length; n = grid[0].length; this.grid = grid; int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] > 0) { ans = Math.max(ans, dfs(i, j)); } } } return ans; } private int dfs(int i, int j) { int cnt = grid[i][j]; grid[i][j] = 0; int[] dirs = {-1, 0, 1, 0, -1}; for (int k = 0; k < 4; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] > 0) { cnt += dfs(x, y); } } return cnt; } }
2,658
Maximum Number of Fish in a Grid
Medium
<p>You are given a <strong>0-indexed</strong> 2D matrix <code>grid</code> of size <code>m x n</code>, where <code>(r, c)</code> represents:</p> <ul> <li>A <strong>land</strong> cell if <code>grid[r][c] = 0</code>, or</li> <li>A <strong>water</strong> cell containing <code>grid[r][c]</code> fish, if <code>grid[r][c] &gt; 0</code>.</li> </ul> <p>A fisher can start at any <strong>water</strong> cell <code>(r, c)</code> and can do the following operations any number of times:</p> <ul> <li>Catch all the fish at cell <code>(r, c)</code>, or</li> <li>Move to any adjacent <strong>water</strong> cell.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of fish the fisher can catch if he chooses his starting cell optimally, or </em><code>0</code> if no water cell exists.</p> <p>An <strong>adjacent</strong> cell of the cell <code>(r, c)</code>, is one of the cells <code>(r, c + 1)</code>, <code>(r, c - 1)</code>, <code>(r + 1, c)</code> or <code>(r - 1, c)</code> if it exists.</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/2658.Maximum%20Number%20of%20Fish%20in%20a%20Grid/images/example.png" style="width: 241px; height: 161px;" /> <pre> <strong>Input:</strong> grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The fisher can start at cell <code>(1,3)</code> and collect 3 fish, then move to cell <code>(2,3)</code>&nbsp;and collect 4 fish. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2658.Maximum%20Number%20of%20Fish%20in%20a%20Grid/images/example2.png" /> <pre> <strong>Input:</strong> grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The fisher can start at cells (0,0) or (3,3) and collect a single fish. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
Python
class Solution: def findMaxFish(self, grid: List[List[int]]) -> int: def dfs(i: int, j: int) -> int: cnt = grid[i][j] grid[i][j] = 0 for a, b in pairwise((-1, 0, 1, 0, -1)): x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and grid[x][y]: cnt += dfs(x, y) return cnt m, n = len(grid), len(grid[0]) ans = 0 for i in range(m): for j in range(n): if grid[i][j]: ans = max(ans, dfs(i, j)) return ans
2,658
Maximum Number of Fish in a Grid
Medium
<p>You are given a <strong>0-indexed</strong> 2D matrix <code>grid</code> of size <code>m x n</code>, where <code>(r, c)</code> represents:</p> <ul> <li>A <strong>land</strong> cell if <code>grid[r][c] = 0</code>, or</li> <li>A <strong>water</strong> cell containing <code>grid[r][c]</code> fish, if <code>grid[r][c] &gt; 0</code>.</li> </ul> <p>A fisher can start at any <strong>water</strong> cell <code>(r, c)</code> and can do the following operations any number of times:</p> <ul> <li>Catch all the fish at cell <code>(r, c)</code>, or</li> <li>Move to any adjacent <strong>water</strong> cell.</li> </ul> <p>Return <em>the <strong>maximum</strong> number of fish the fisher can catch if he chooses his starting cell optimally, or </em><code>0</code> if no water cell exists.</p> <p>An <strong>adjacent</strong> cell of the cell <code>(r, c)</code>, is one of the cells <code>(r, c + 1)</code>, <code>(r, c - 1)</code>, <code>(r + 1, c)</code> or <code>(r - 1, c)</code> if it exists.</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/2658.Maximum%20Number%20of%20Fish%20in%20a%20Grid/images/example.png" style="width: 241px; height: 161px;" /> <pre> <strong>Input:</strong> grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The fisher can start at cell <code>(1,3)</code> and collect 3 fish, then move to cell <code>(2,3)</code>&nbsp;and collect 4 fish. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2658.Maximum%20Number%20of%20Fish%20in%20a%20Grid/images/example2.png" /> <pre> <strong>Input:</strong> grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> The fisher can start at cells (0,0) or (3,3) and collect a single fish. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == grid.length</code></li> <li><code>n == grid[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 10</code></li> <li><code>0 &lt;= grid[i][j] &lt;= 10</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Array; Matrix
TypeScript
function findMaxFish(grid: number[][]): number { const m = grid.length; const n = grid[0].length; const dirs = [-1, 0, 1, 0, -1]; const dfs = (i: number, j: number): number => { let cnt = grid[i][j]; grid[i][j] = 0; for (let k = 0; k < 4; ++k) { const x = i + dirs[k]; const y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] > 0) { cnt += dfs(x, y); } } return cnt; }; let ans = 0; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (grid[i][j] > 0) { ans = Math.max(ans, dfs(i, j)); } } } return ans; }
2,659
Make Array Empty
Hard
<p>You are given an integer array <code>nums</code> containing <strong>distinct</strong> numbers, and you can perform the following operations <strong>until the array is empty</strong>:</p> <ul> <li>If the first element has the <strong>smallest</strong> value, remove it</li> <li>Otherwise, put the first element at the <strong>end</strong> of the array.</li> </ul> <p>Return <em>an integer denoting the number of operations it takes to make </em><code>nums</code><em> empty.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1] <strong>Output:</strong> 5 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[4, -1, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[-1, 3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">4</td> <td style="border: 2px solid black; padding: 5px;">[4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">5</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,4,3] <strong>Output:</strong> 5 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[2, 4, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[4, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">4</td> <td style="border: 2px solid black; padding: 5px;">[4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">5</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[2, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9&nbsp;</sup>&lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>All values in <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Greedy; Binary Indexed Tree; Segment Tree; Array; Binary Search; Ordered Set; Sorting
C++
class BinaryIndexedTree { public: BinaryIndexedTree(int _n) : n(_n) , c(_n + 1) {} void update(int x, int delta) { while (x <= n) { c[x] += delta; x += x & -x; } } int query(int x) { int s = 0; while (x) { s += c[x]; x -= x & -x; } return s; } private: int n; vector<int> c; }; class Solution { public: long long countOperationsToEmptyArray(vector<int>& nums) { unordered_map<int, int> pos; int n = nums.size(); for (int i = 0; i < n; ++i) { pos[nums[i]] = i; } sort(nums.begin(), nums.end()); BinaryIndexedTree tree(n); long long ans = pos[nums[0]] + 1; for (int k = 0; k < n - 1; ++k) { int i = pos[nums[k]], j = pos[nums[k + 1]]; long long d = j - i - (tree.query(j + 1) - tree.query(i + 1)); ans += d + (n - k) * int(i > j); tree.update(i + 1, 1); } return ans; } };
2,659
Make Array Empty
Hard
<p>You are given an integer array <code>nums</code> containing <strong>distinct</strong> numbers, and you can perform the following operations <strong>until the array is empty</strong>:</p> <ul> <li>If the first element has the <strong>smallest</strong> value, remove it</li> <li>Otherwise, put the first element at the <strong>end</strong> of the array.</li> </ul> <p>Return <em>an integer denoting the number of operations it takes to make </em><code>nums</code><em> empty.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1] <strong>Output:</strong> 5 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[4, -1, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[-1, 3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">4</td> <td style="border: 2px solid black; padding: 5px;">[4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">5</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,4,3] <strong>Output:</strong> 5 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[2, 4, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[4, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">4</td> <td style="border: 2px solid black; padding: 5px;">[4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">5</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[2, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9&nbsp;</sup>&lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>All values in <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Greedy; Binary Indexed Tree; Segment Tree; Array; Binary Search; Ordered Set; Sorting
Go
type BinaryIndexedTree struct { n int c []int } func newBinaryIndexedTree(n int) *BinaryIndexedTree { c := make([]int, n+1) return &BinaryIndexedTree{n, c} } func (this *BinaryIndexedTree) update(x, delta int) { for x <= this.n { this.c[x] += delta x += x & -x } } func (this *BinaryIndexedTree) query(x int) int { s := 0 for x > 0 { s += this.c[x] x -= x & -x } return s } func countOperationsToEmptyArray(nums []int) int64 { n := len(nums) pos := map[int]int{} for i, x := range nums { pos[x] = i } sort.Ints(nums) tree := newBinaryIndexedTree(n) ans := pos[nums[0]] + 1 for k := 0; k < n-1; k++ { i, j := pos[nums[k]], pos[nums[k+1]] d := j - i - (tree.query(j+1) - tree.query(i+1)) if i > j { d += n - k } ans += d tree.update(i+1, 1) } return int64(ans) }
2,659
Make Array Empty
Hard
<p>You are given an integer array <code>nums</code> containing <strong>distinct</strong> numbers, and you can perform the following operations <strong>until the array is empty</strong>:</p> <ul> <li>If the first element has the <strong>smallest</strong> value, remove it</li> <li>Otherwise, put the first element at the <strong>end</strong> of the array.</li> </ul> <p>Return <em>an integer denoting the number of operations it takes to make </em><code>nums</code><em> empty.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1] <strong>Output:</strong> 5 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[4, -1, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[-1, 3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">4</td> <td style="border: 2px solid black; padding: 5px;">[4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">5</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,4,3] <strong>Output:</strong> 5 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[2, 4, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[4, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">4</td> <td style="border: 2px solid black; padding: 5px;">[4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">5</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[2, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9&nbsp;</sup>&lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>All values in <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Greedy; Binary Indexed Tree; Segment Tree; Array; Binary Search; Ordered Set; Sorting
Java
class BinaryIndexedTree { private int n; private int[] c; public BinaryIndexedTree(int n) { this.n = n; c = new int[n + 1]; } public void update(int x, int delta) { while (x <= n) { c[x] += delta; x += x & -x; } } public int query(int x) { int s = 0; while (x > 0) { s += c[x]; x -= x & -x; } return s; } } class Solution { public long countOperationsToEmptyArray(int[] nums) { int n = nums.length; Map<Integer, Integer> pos = new HashMap<>(); for (int i = 0; i < n; ++i) { pos.put(nums[i], i); } Arrays.sort(nums); long ans = pos.get(nums[0]) + 1; BinaryIndexedTree tree = new BinaryIndexedTree(n); for (int k = 0; k < n - 1; ++k) { int i = pos.get(nums[k]), j = pos.get(nums[k + 1]); long d = j - i - (tree.query(j + 1) - tree.query(i + 1)); ans += d + (n - k) * (i > j ? 1 : 0); tree.update(i + 1, 1); } return ans; } }
2,659
Make Array Empty
Hard
<p>You are given an integer array <code>nums</code> containing <strong>distinct</strong> numbers, and you can perform the following operations <strong>until the array is empty</strong>:</p> <ul> <li>If the first element has the <strong>smallest</strong> value, remove it</li> <li>Otherwise, put the first element at the <strong>end</strong> of the array.</li> </ul> <p>Return <em>an integer denoting the number of operations it takes to make </em><code>nums</code><em> empty.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1] <strong>Output:</strong> 5 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[4, -1, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[-1, 3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">4</td> <td style="border: 2px solid black; padding: 5px;">[4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">5</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,4,3] <strong>Output:</strong> 5 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[2, 4, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[4, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">4</td> <td style="border: 2px solid black; padding: 5px;">[4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">5</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[2, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9&nbsp;</sup>&lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>All values in <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Greedy; Binary Indexed Tree; Segment Tree; Array; Binary Search; Ordered Set; Sorting
Python
class Solution: def countOperationsToEmptyArray(self, nums: List[int]) -> int: pos = {x: i for i, x in enumerate(nums)} nums.sort() sl = SortedList() ans = pos[nums[0]] + 1 n = len(nums) for k, (a, b) in enumerate(pairwise(nums)): i, j = pos[a], pos[b] d = j - i - sl.bisect(j) + sl.bisect(i) ans += d + (n - k) * int(i > j) sl.add(i) return ans
2,659
Make Array Empty
Hard
<p>You are given an integer array <code>nums</code> containing <strong>distinct</strong> numbers, and you can perform the following operations <strong>until the array is empty</strong>:</p> <ul> <li>If the first element has the <strong>smallest</strong> value, remove it</li> <li>Otherwise, put the first element at the <strong>end</strong> of the array.</li> </ul> <p>Return <em>an integer denoting the number of operations it takes to make </em><code>nums</code><em> empty.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1] <strong>Output:</strong> 5 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[4, -1, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[-1, 3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">4</td> <td style="border: 2px solid black; padding: 5px;">[4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">5</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,4,3] <strong>Output:</strong> 5 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[2, 4, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[4, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[3, 4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">4</td> <td style="border: 2px solid black; padding: 5px;">[4]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">5</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 </pre> <table style="border: 2px solid black; border-collapse: collapse;"> <thead> <tr> <th style="border: 2px solid black; padding: 5px;">Operation</th> <th style="border: 2px solid black; padding: 5px;">Array</th> </tr> </thead> <tbody> <tr> <td style="border: 2px solid black; padding: 5px;">1</td> <td style="border: 2px solid black; padding: 5px;">[2, 3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">2</td> <td style="border: 2px solid black; padding: 5px;">[3]</td> </tr> <tr> <td style="border: 2px solid black; padding: 5px;">3</td> <td style="border: 2px solid black; padding: 5px;">[]</td> </tr> </tbody> </table> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9&nbsp;</sup>&lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>All values in <code>nums</code> are <strong>distinct</strong>.</li> </ul>
Greedy; Binary Indexed Tree; Segment Tree; Array; Binary Search; Ordered Set; Sorting
TypeScript
class BinaryIndexedTree { private n: number; private c: number[]; constructor(n: number) { this.n = n; this.c = Array(n + 1).fill(0); } public update(x: number, v: number): void { while (x <= this.n) { this.c[x] += v; x += x & -x; } } public query(x: number): number { let s = 0; while (x > 0) { s += this.c[x]; x -= x & -x; } return s; } } function countOperationsToEmptyArray(nums: number[]): number { const pos: Map<number, number> = new Map(); const n = nums.length; for (let i = 0; i < n; ++i) { pos.set(nums[i], i); } nums.sort((a, b) => a - b); const tree = new BinaryIndexedTree(n); let ans = pos.get(nums[0])! + 1; for (let k = 0; k < n - 1; ++k) { const i = pos.get(nums[k])!; const j = pos.get(nums[k + 1])!; let d = j - i - (tree.query(j + 1) - tree.query(i + 1)); if (i > j) { d += n - k; } ans += d; tree.update(i + 1, 1); } return ans; }
2,660
Determine the Winner of a Bowling Game
Easy
<p>You are given two <strong>0-indexed</strong> integer arrays <code><font face="monospace">player1</font></code> and <code>player2</code>, representing the number of pins that player 1 and player 2 hit in a bowling game, respectively.</p> <p>The bowling game consists of <code>n</code> turns, and the number of pins in each turn is exactly 10.</p> <p>Assume a player hits <code>x<sub>i</sub></code> pins in the i<sup>th</sup> turn. The value of the i<sup>th</sup> turn for the player is:</p> <ul> <li><code>2x<sub>i</sub></code> if the player hits 10 pins <b>in either (i - 1)<sup>th</sup> or (i - 2)<sup>th</sup> turn</b>.</li> <li>Otherwise, it is <code>x<sub>i</sub></code>.</li> </ul> <p>The <strong>score</strong> of the player is the sum of the values of their <code>n</code> turns.</p> <p>Return</p> <ul> <li>1 if the score of player 1 is more than the score of player 2,</li> <li>2 if the score of player 2 is more than the score of player 1, and</li> <li>0 in case of a draw.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [5,10,3,2], player2 = [6,5,7,3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The score of player 1 is 5 + 10 + 2*3 + 2*2 = 25.</p> <p>The score of player 2 is 6 + 5 + 7 + 3 = 21.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [3,5,7,6], player2 = [8,10,10,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The score of player 1 is 3 + 5 + 7 + 6 = 21.</p> <p>The score of player 2 is 8 + 10 + 2*10 + 2*2 = 42.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [2,3], player2 = [4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The score of player1 is 2 + 3 = 5.</p> <p>The score of player2 is 4 + 1 = 5.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [1,1,1,10,10,10,10], player2 = [10,10,10,10,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The score of player1 is 1 + 1 + 1 + 10 + 2*10 + 2*10 + 2*10 = 73.</p> <p>The score of player2 is 10 + 2*10 + 2*10 + 2*10 + 2*1 + 2*1 + 1 = 75.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == player1.length == player2.length</code></li> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>0 &lt;= player1[i], player2[i] &lt;= 10</code></li> </ul>
Array; Simulation
C++
class Solution { public: int isWinner(vector<int>& player1, vector<int>& player2) { auto f = [](vector<int>& arr) { int s = 0; for (int i = 0, n = arr.size(); i < n; ++i) { int k = (i && arr[i - 1] == 10) || (i > 1 && arr[i - 2] == 10) ? 2 : 1; s += k * arr[i]; } return s; }; int a = f(player1), b = f(player2); return a > b ? 1 : (b > a ? 2 : 0); } };
2,660
Determine the Winner of a Bowling Game
Easy
<p>You are given two <strong>0-indexed</strong> integer arrays <code><font face="monospace">player1</font></code> and <code>player2</code>, representing the number of pins that player 1 and player 2 hit in a bowling game, respectively.</p> <p>The bowling game consists of <code>n</code> turns, and the number of pins in each turn is exactly 10.</p> <p>Assume a player hits <code>x<sub>i</sub></code> pins in the i<sup>th</sup> turn. The value of the i<sup>th</sup> turn for the player is:</p> <ul> <li><code>2x<sub>i</sub></code> if the player hits 10 pins <b>in either (i - 1)<sup>th</sup> or (i - 2)<sup>th</sup> turn</b>.</li> <li>Otherwise, it is <code>x<sub>i</sub></code>.</li> </ul> <p>The <strong>score</strong> of the player is the sum of the values of their <code>n</code> turns.</p> <p>Return</p> <ul> <li>1 if the score of player 1 is more than the score of player 2,</li> <li>2 if the score of player 2 is more than the score of player 1, and</li> <li>0 in case of a draw.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [5,10,3,2], player2 = [6,5,7,3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The score of player 1 is 5 + 10 + 2*3 + 2*2 = 25.</p> <p>The score of player 2 is 6 + 5 + 7 + 3 = 21.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [3,5,7,6], player2 = [8,10,10,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The score of player 1 is 3 + 5 + 7 + 6 = 21.</p> <p>The score of player 2 is 8 + 10 + 2*10 + 2*2 = 42.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [2,3], player2 = [4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The score of player1 is 2 + 3 = 5.</p> <p>The score of player2 is 4 + 1 = 5.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [1,1,1,10,10,10,10], player2 = [10,10,10,10,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The score of player1 is 1 + 1 + 1 + 10 + 2*10 + 2*10 + 2*10 = 73.</p> <p>The score of player2 is 10 + 2*10 + 2*10 + 2*10 + 2*1 + 2*1 + 1 = 75.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == player1.length == player2.length</code></li> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>0 &lt;= player1[i], player2[i] &lt;= 10</code></li> </ul>
Array; Simulation
Go
func isWinner(player1 []int, player2 []int) int { f := func(arr []int) int { s := 0 for i, x := range arr { k := 1 if (i > 0 && arr[i-1] == 10) || (i > 1 && arr[i-2] == 10) { k = 2 } s += k * x } return s } a, b := f(player1), f(player2) if a > b { return 1 } if b > a { return 2 } return 0 }
2,660
Determine the Winner of a Bowling Game
Easy
<p>You are given two <strong>0-indexed</strong> integer arrays <code><font face="monospace">player1</font></code> and <code>player2</code>, representing the number of pins that player 1 and player 2 hit in a bowling game, respectively.</p> <p>The bowling game consists of <code>n</code> turns, and the number of pins in each turn is exactly 10.</p> <p>Assume a player hits <code>x<sub>i</sub></code> pins in the i<sup>th</sup> turn. The value of the i<sup>th</sup> turn for the player is:</p> <ul> <li><code>2x<sub>i</sub></code> if the player hits 10 pins <b>in either (i - 1)<sup>th</sup> or (i - 2)<sup>th</sup> turn</b>.</li> <li>Otherwise, it is <code>x<sub>i</sub></code>.</li> </ul> <p>The <strong>score</strong> of the player is the sum of the values of their <code>n</code> turns.</p> <p>Return</p> <ul> <li>1 if the score of player 1 is more than the score of player 2,</li> <li>2 if the score of player 2 is more than the score of player 1, and</li> <li>0 in case of a draw.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [5,10,3,2], player2 = [6,5,7,3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The score of player 1 is 5 + 10 + 2*3 + 2*2 = 25.</p> <p>The score of player 2 is 6 + 5 + 7 + 3 = 21.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [3,5,7,6], player2 = [8,10,10,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The score of player 1 is 3 + 5 + 7 + 6 = 21.</p> <p>The score of player 2 is 8 + 10 + 2*10 + 2*2 = 42.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [2,3], player2 = [4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The score of player1 is 2 + 3 = 5.</p> <p>The score of player2 is 4 + 1 = 5.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [1,1,1,10,10,10,10], player2 = [10,10,10,10,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The score of player1 is 1 + 1 + 1 + 10 + 2*10 + 2*10 + 2*10 = 73.</p> <p>The score of player2 is 10 + 2*10 + 2*10 + 2*10 + 2*1 + 2*1 + 1 = 75.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == player1.length == player2.length</code></li> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>0 &lt;= player1[i], player2[i] &lt;= 10</code></li> </ul>
Array; Simulation
Java
class Solution { public int isWinner(int[] player1, int[] player2) { int a = f(player1), b = f(player2); return a > b ? 1 : b > a ? 2 : 0; } private int f(int[] arr) { int s = 0; for (int i = 0; i < arr.length; ++i) { int k = (i > 0 && arr[i - 1] == 10) || (i > 1 && arr[i - 2] == 10) ? 2 : 1; s += k * arr[i]; } return s; } }
2,660
Determine the Winner of a Bowling Game
Easy
<p>You are given two <strong>0-indexed</strong> integer arrays <code><font face="monospace">player1</font></code> and <code>player2</code>, representing the number of pins that player 1 and player 2 hit in a bowling game, respectively.</p> <p>The bowling game consists of <code>n</code> turns, and the number of pins in each turn is exactly 10.</p> <p>Assume a player hits <code>x<sub>i</sub></code> pins in the i<sup>th</sup> turn. The value of the i<sup>th</sup> turn for the player is:</p> <ul> <li><code>2x<sub>i</sub></code> if the player hits 10 pins <b>in either (i - 1)<sup>th</sup> or (i - 2)<sup>th</sup> turn</b>.</li> <li>Otherwise, it is <code>x<sub>i</sub></code>.</li> </ul> <p>The <strong>score</strong> of the player is the sum of the values of their <code>n</code> turns.</p> <p>Return</p> <ul> <li>1 if the score of player 1 is more than the score of player 2,</li> <li>2 if the score of player 2 is more than the score of player 1, and</li> <li>0 in case of a draw.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [5,10,3,2], player2 = [6,5,7,3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The score of player 1 is 5 + 10 + 2*3 + 2*2 = 25.</p> <p>The score of player 2 is 6 + 5 + 7 + 3 = 21.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [3,5,7,6], player2 = [8,10,10,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The score of player 1 is 3 + 5 + 7 + 6 = 21.</p> <p>The score of player 2 is 8 + 10 + 2*10 + 2*2 = 42.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [2,3], player2 = [4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The score of player1 is 2 + 3 = 5.</p> <p>The score of player2 is 4 + 1 = 5.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [1,1,1,10,10,10,10], player2 = [10,10,10,10,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The score of player1 is 1 + 1 + 1 + 10 + 2*10 + 2*10 + 2*10 = 73.</p> <p>The score of player2 is 10 + 2*10 + 2*10 + 2*10 + 2*1 + 2*1 + 1 = 75.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == player1.length == player2.length</code></li> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>0 &lt;= player1[i], player2[i] &lt;= 10</code></li> </ul>
Array; Simulation
Python
class Solution: def isWinner(self, player1: List[int], player2: List[int]) -> int: def f(arr: List[int]) -> int: s = 0 for i, x in enumerate(arr): k = 2 if (i and arr[i - 1] == 10) or (i > 1 and arr[i - 2] == 10) else 1 s += k * x return s a, b = f(player1), f(player2) return 1 if a > b else (2 if b > a else 0)
2,660
Determine the Winner of a Bowling Game
Easy
<p>You are given two <strong>0-indexed</strong> integer arrays <code><font face="monospace">player1</font></code> and <code>player2</code>, representing the number of pins that player 1 and player 2 hit in a bowling game, respectively.</p> <p>The bowling game consists of <code>n</code> turns, and the number of pins in each turn is exactly 10.</p> <p>Assume a player hits <code>x<sub>i</sub></code> pins in the i<sup>th</sup> turn. The value of the i<sup>th</sup> turn for the player is:</p> <ul> <li><code>2x<sub>i</sub></code> if the player hits 10 pins <b>in either (i - 1)<sup>th</sup> or (i - 2)<sup>th</sup> turn</b>.</li> <li>Otherwise, it is <code>x<sub>i</sub></code>.</li> </ul> <p>The <strong>score</strong> of the player is the sum of the values of their <code>n</code> turns.</p> <p>Return</p> <ul> <li>1 if the score of player 1 is more than the score of player 2,</li> <li>2 if the score of player 2 is more than the score of player 1, and</li> <li>0 in case of a draw.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [5,10,3,2], player2 = [6,5,7,3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The score of player 1 is 5 + 10 + 2*3 + 2*2 = 25.</p> <p>The score of player 2 is 6 + 5 + 7 + 3 = 21.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [3,5,7,6], player2 = [8,10,10,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The score of player 1 is 3 + 5 + 7 + 6 = 21.</p> <p>The score of player 2 is 8 + 10 + 2*10 + 2*2 = 42.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [2,3], player2 = [4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The score of player1 is 2 + 3 = 5.</p> <p>The score of player2 is 4 + 1 = 5.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [1,1,1,10,10,10,10], player2 = [10,10,10,10,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The score of player1 is 1 + 1 + 1 + 10 + 2*10 + 2*10 + 2*10 = 73.</p> <p>The score of player2 is 10 + 2*10 + 2*10 + 2*10 + 2*1 + 2*1 + 1 = 75.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == player1.length == player2.length</code></li> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>0 &lt;= player1[i], player2[i] &lt;= 10</code></li> </ul>
Array; Simulation
Rust
impl Solution { pub fn is_winner(player1: Vec<i32>, player2: Vec<i32>) -> i32 { let f = |arr: &Vec<i32>| -> i32 { let mut s = 0; for i in 0..arr.len() { let mut k = 1; if (i > 0 && arr[i - 1] == 10) || (i > 1 && arr[i - 2] == 10) { k = 2; } s += k * arr[i]; } s }; let a = f(&player1); let b = f(&player2); if a > b { 1 } else if a < b { 2 } else { 0 } } }
2,660
Determine the Winner of a Bowling Game
Easy
<p>You are given two <strong>0-indexed</strong> integer arrays <code><font face="monospace">player1</font></code> and <code>player2</code>, representing the number of pins that player 1 and player 2 hit in a bowling game, respectively.</p> <p>The bowling game consists of <code>n</code> turns, and the number of pins in each turn is exactly 10.</p> <p>Assume a player hits <code>x<sub>i</sub></code> pins in the i<sup>th</sup> turn. The value of the i<sup>th</sup> turn for the player is:</p> <ul> <li><code>2x<sub>i</sub></code> if the player hits 10 pins <b>in either (i - 1)<sup>th</sup> or (i - 2)<sup>th</sup> turn</b>.</li> <li>Otherwise, it is <code>x<sub>i</sub></code>.</li> </ul> <p>The <strong>score</strong> of the player is the sum of the values of their <code>n</code> turns.</p> <p>Return</p> <ul> <li>1 if the score of player 1 is more than the score of player 2,</li> <li>2 if the score of player 2 is more than the score of player 1, and</li> <li>0 in case of a draw.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [5,10,3,2], player2 = [6,5,7,3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The score of player 1 is 5 + 10 + 2*3 + 2*2 = 25.</p> <p>The score of player 2 is 6 + 5 + 7 + 3 = 21.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [3,5,7,6], player2 = [8,10,10,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The score of player 1 is 3 + 5 + 7 + 6 = 21.</p> <p>The score of player 2 is 8 + 10 + 2*10 + 2*2 = 42.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [2,3], player2 = [4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The score of player1 is 2 + 3 = 5.</p> <p>The score of player2 is 4 + 1 = 5.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">player1 = [1,1,1,10,10,10,10], player2 = [10,10,10,10,1,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>The score of player1 is 1 + 1 + 1 + 10 + 2*10 + 2*10 + 2*10 = 73.</p> <p>The score of player2 is 10 + 2*10 + 2*10 + 2*10 + 2*1 + 2*1 + 1 = 75.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == player1.length == player2.length</code></li> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>0 &lt;= player1[i], player2[i] &lt;= 10</code></li> </ul>
Array; Simulation
TypeScript
function isWinner(player1: number[], player2: number[]): number { const f = (arr: number[]): number => { let s = 0; for (let i = 0; i < arr.length; ++i) { s += arr[i]; if ((i && arr[i - 1] === 10) || (i > 1 && arr[i - 2] === 10)) { s += arr[i]; } } return s; }; const a = f(player1); const b = f(player2); return a > b ? 1 : a < b ? 2 : 0; }
2,661
First Completely Painted Row or Column
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>arr</code>, and an <code>m x n</code> integer <strong>matrix</strong> <code>mat</code>. <code>arr</code> and <code>mat</code> both contain <strong>all</strong> the integers in the range <code>[1, m * n]</code>.</p> <p>Go through each index <code>i</code> in <code>arr</code> starting from index <code>0</code> and paint the cell in <code>mat</code> containing the integer <code>arr[i]</code>.</p> <p>Return <em>the smallest index</em> <code>i</code> <em>at which either a row or a column will be completely painted in</em> <code>mat</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/image explanation for example 1" /><img alt="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/image explanation for example 1" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/grid1.jpg" style="width: 321px; height: 81px;" /> <pre> <strong>Input:</strong> arr = [1,3,4,2], mat = [[1,4],[2,3]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="image explanation for example 2" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/grid2.jpg" style="width: 601px; height: 121px;" /> <pre> <strong>Input:</strong> arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The second column becomes fully painted at arr[3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n = mat[i].length</code></li> <li><code>arr.length == m * n</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arr[i], mat[r][c] &lt;= m * n</code></li> <li>All the integers of <code>arr</code> are <strong>unique</strong>.</li> <li>All the integers of <code>mat</code> are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Matrix
C++
class Solution { public: int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) { int m = mat.size(), n = mat[0].size(); unordered_map<int, pair<int, int>> idx; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { idx[mat[i][j]] = {i, j}; } } vector<int> row(m), col(n); for (int k = 0;; ++k) { auto [i, j] = idx[arr[k]]; ++row[i]; ++col[j]; if (row[i] == n || col[j] == m) { return k; } } } };
2,661
First Completely Painted Row or Column
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>arr</code>, and an <code>m x n</code> integer <strong>matrix</strong> <code>mat</code>. <code>arr</code> and <code>mat</code> both contain <strong>all</strong> the integers in the range <code>[1, m * n]</code>.</p> <p>Go through each index <code>i</code> in <code>arr</code> starting from index <code>0</code> and paint the cell in <code>mat</code> containing the integer <code>arr[i]</code>.</p> <p>Return <em>the smallest index</em> <code>i</code> <em>at which either a row or a column will be completely painted in</em> <code>mat</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/image explanation for example 1" /><img alt="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/image explanation for example 1" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/grid1.jpg" style="width: 321px; height: 81px;" /> <pre> <strong>Input:</strong> arr = [1,3,4,2], mat = [[1,4],[2,3]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="image explanation for example 2" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/grid2.jpg" style="width: 601px; height: 121px;" /> <pre> <strong>Input:</strong> arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The second column becomes fully painted at arr[3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n = mat[i].length</code></li> <li><code>arr.length == m * n</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arr[i], mat[r][c] &lt;= m * n</code></li> <li>All the integers of <code>arr</code> are <strong>unique</strong>.</li> <li>All the integers of <code>mat</code> are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Matrix
Go
func firstCompleteIndex(arr []int, mat [][]int) int { m, n := len(mat), len(mat[0]) idx := map[int][2]int{} for i := range mat { for j := range mat[i] { idx[mat[i][j]] = [2]int{i, j} } } row := make([]int, m) col := make([]int, n) for k := 0; ; k++ { x := idx[arr[k]] i, j := x[0], x[1] row[i]++ col[j]++ if row[i] == n || col[j] == m { return k } } }
2,661
First Completely Painted Row or Column
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>arr</code>, and an <code>m x n</code> integer <strong>matrix</strong> <code>mat</code>. <code>arr</code> and <code>mat</code> both contain <strong>all</strong> the integers in the range <code>[1, m * n]</code>.</p> <p>Go through each index <code>i</code> in <code>arr</code> starting from index <code>0</code> and paint the cell in <code>mat</code> containing the integer <code>arr[i]</code>.</p> <p>Return <em>the smallest index</em> <code>i</code> <em>at which either a row or a column will be completely painted in</em> <code>mat</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/image explanation for example 1" /><img alt="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/image explanation for example 1" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/grid1.jpg" style="width: 321px; height: 81px;" /> <pre> <strong>Input:</strong> arr = [1,3,4,2], mat = [[1,4],[2,3]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="image explanation for example 2" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/grid2.jpg" style="width: 601px; height: 121px;" /> <pre> <strong>Input:</strong> arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The second column becomes fully painted at arr[3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n = mat[i].length</code></li> <li><code>arr.length == m * n</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arr[i], mat[r][c] &lt;= m * n</code></li> <li>All the integers of <code>arr</code> are <strong>unique</strong>.</li> <li>All the integers of <code>mat</code> are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Matrix
Java
class Solution { public int firstCompleteIndex(int[] arr, int[][] mat) { int m = mat.length, n = mat[0].length; Map<Integer, int[]> idx = new HashMap<>(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { idx.put(mat[i][j], new int[] {i, j}); } } int[] row = new int[m]; int[] col = new int[n]; for (int k = 0;; ++k) { var x = idx.get(arr[k]); int i = x[0], j = x[1]; ++row[i]; ++col[j]; if (row[i] == n || col[j] == m) { return k; } } } }
2,661
First Completely Painted Row or Column
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>arr</code>, and an <code>m x n</code> integer <strong>matrix</strong> <code>mat</code>. <code>arr</code> and <code>mat</code> both contain <strong>all</strong> the integers in the range <code>[1, m * n]</code>.</p> <p>Go through each index <code>i</code> in <code>arr</code> starting from index <code>0</code> and paint the cell in <code>mat</code> containing the integer <code>arr[i]</code>.</p> <p>Return <em>the smallest index</em> <code>i</code> <em>at which either a row or a column will be completely painted in</em> <code>mat</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/image explanation for example 1" /><img alt="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/image explanation for example 1" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/grid1.jpg" style="width: 321px; height: 81px;" /> <pre> <strong>Input:</strong> arr = [1,3,4,2], mat = [[1,4],[2,3]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="image explanation for example 2" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/grid2.jpg" style="width: 601px; height: 121px;" /> <pre> <strong>Input:</strong> arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The second column becomes fully painted at arr[3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n = mat[i].length</code></li> <li><code>arr.length == m * n</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arr[i], mat[r][c] &lt;= m * n</code></li> <li>All the integers of <code>arr</code> are <strong>unique</strong>.</li> <li>All the integers of <code>mat</code> are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Matrix
Python
class Solution: def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int: m, n = len(mat), len(mat[0]) idx = {} for i in range(m): for j in range(n): idx[mat[i][j]] = (i, j) row = [0] * m col = [0] * n for k in range(len(arr)): i, j = idx[arr[k]] row[i] += 1 col[j] += 1 if row[i] == n or col[j] == m: return k
2,661
First Completely Painted Row or Column
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>arr</code>, and an <code>m x n</code> integer <strong>matrix</strong> <code>mat</code>. <code>arr</code> and <code>mat</code> both contain <strong>all</strong> the integers in the range <code>[1, m * n]</code>.</p> <p>Go through each index <code>i</code> in <code>arr</code> starting from index <code>0</code> and paint the cell in <code>mat</code> containing the integer <code>arr[i]</code>.</p> <p>Return <em>the smallest index</em> <code>i</code> <em>at which either a row or a column will be completely painted in</em> <code>mat</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/image explanation for example 1" /><img alt="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/image explanation for example 1" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/grid1.jpg" style="width: 321px; height: 81px;" /> <pre> <strong>Input:</strong> arr = [1,3,4,2], mat = [[1,4],[2,3]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="image explanation for example 2" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/grid2.jpg" style="width: 601px; height: 121px;" /> <pre> <strong>Input:</strong> arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The second column becomes fully painted at arr[3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n = mat[i].length</code></li> <li><code>arr.length == m * n</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arr[i], mat[r][c] &lt;= m * n</code></li> <li>All the integers of <code>arr</code> are <strong>unique</strong>.</li> <li>All the integers of <code>mat</code> are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Matrix
Rust
use std::collections::HashMap; impl Solution { pub fn first_complete_index(arr: Vec<i32>, mat: Vec<Vec<i32>>) -> i32 { let m = mat.len(); let n = mat[0].len(); let mut idx = HashMap::new(); for i in 0..m { for j in 0..n { idx.insert(mat[i][j], [i, j]); } } let mut row = vec![0; m]; let mut col = vec![0; n]; for k in 0..arr.len() { let x = idx.get(&arr[k]).unwrap(); let i = x[0]; let j = x[1]; row[i] += 1; col[j] += 1; if row[i] == n || col[j] == m { return k as i32; } } -1 } }
2,661
First Completely Painted Row or Column
Medium
<p>You are given a <strong>0-indexed</strong> integer array <code>arr</code>, and an <code>m x n</code> integer <strong>matrix</strong> <code>mat</code>. <code>arr</code> and <code>mat</code> both contain <strong>all</strong> the integers in the range <code>[1, m * n]</code>.</p> <p>Go through each index <code>i</code> in <code>arr</code> starting from index <code>0</code> and paint the cell in <code>mat</code> containing the integer <code>arr[i]</code>.</p> <p>Return <em>the smallest index</em> <code>i</code> <em>at which either a row or a column will be completely painted in</em> <code>mat</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/image explanation for example 1" /><img alt="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/image explanation for example 1" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/grid1.jpg" style="width: 321px; height: 81px;" /> <pre> <strong>Input:</strong> arr = [1,3,4,2], mat = [[1,4],[2,3]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2]. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="image explanation for example 2" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2661.First%20Completely%20Painted%20Row%20or%20Column/images/grid2.jpg" style="width: 601px; height: 121px;" /> <pre> <strong>Input:</strong> arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The second column becomes fully painted at arr[3]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == mat.length</code></li> <li><code>n = mat[i].length</code></li> <li><code>arr.length == m * n</code></li> <li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= arr[i], mat[r][c] &lt;= m * n</code></li> <li>All the integers of <code>arr</code> are <strong>unique</strong>.</li> <li>All the integers of <code>mat</code> are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Matrix
TypeScript
function firstCompleteIndex(arr: number[], mat: number[][]): number { const m = mat.length; const n = mat[0].length; const idx: Map<number, number[]> = new Map(); for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { idx.set(mat[i][j], [i, j]); } } const row: number[] = Array(m).fill(0); const col: number[] = Array(n).fill(0); for (let k = 0; ; ++k) { const [i, j] = idx.get(arr[k])!; ++row[i]; ++col[j]; if (row[i] === n || col[j] === m) { return k; } } }
2,662
Minimum Cost of a Path With Special Roads
Medium
<p>You are given an array <code>start</code> where <code>start = [startX, startY]</code> represents your initial position <code>(startX, startY)</code> in a 2D space. You are also given the array <code>target</code> where <code>target = [targetX, targetY]</code> represents your target position <code>(targetX, targetY)</code>.</p> <p>The <strong>cost</strong> of going from a position <code>(x1, y1)</code> to any other position in the space <code>(x2, y2)</code> is <code>|x2 - x1| + |y2 - y1|</code>.</p> <p>There are also some <strong>special roads</strong>. You are given a 2D array <code>specialRoads</code> where <code>specialRoads[i] = [x1<sub>i</sub>, y1<sub>i</sub>, x2<sub>i</sub>, y2<sub>i</sub>, cost<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> special road goes in <strong>one direction</strong> from <code>(x1<sub>i</sub>, y1<sub>i</sub>)</code> to <code>(x2<sub>i</sub>, y2<sub>i</sub>)</code> with a cost equal to <code>cost<sub>i</sub></code>. You can use each special road any number of times.</p> <p>Return the <strong>minimum</strong> cost required to go from <code>(startX, startY)</code> to <code>(targetX, targetY)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [1,1], target = [4,5], specialRoads = [[1,2,3,3,2],[3,4,4,5,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ol> <li>(1,1) to (1,2) with a cost of |1 - 1| + |2 - 1| = 1.</li> <li>(1,2) to (3,3). Use <code><span class="example-io">specialRoads[0]</span></code><span class="example-io"> with</span><span class="example-io"> the cost 2.</span></li> <li><span class="example-io">(3,3) to (3,4) with a cost of |3 - 3| + |4 - 3| = 1.</span></li> <li><span class="example-io">(3,4) to (4,5). Use </span><code><span class="example-io">specialRoads[1]</span></code><span class="example-io"> with the cost</span><span class="example-io"> 1.</span></li> </ol> <p><span class="example-io">So the total cost is 1 + 2 + 1 + 1 = 5.</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [3,2], target = [5,7], specialRoads = [[5,7,3,2,1],[3,2,3,4,4],[3,3,5,5,5],[3,4,5,6,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>It is optimal not to use any special edges and go directly from the starting to the ending position with a cost |5 - 3| + |7 - 2| = 7.</p> <p>Note that the <span class="example-io"><code>specialRoads[0]</code> is directed from (5,7) to (3,2).</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [1,1], target = [10,4], specialRoads = [[4,2,1,1,3],[1,2,7,4,4],[10,3,6,1,2],[6,1,1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ol> <li>(1,1) to (1,2) with a cost of |1 - 1| + |2 - 1| = 1.</li> <li>(1,2) to (7,4). Use <code><span class="example-io">specialRoads[1]</span></code><span class="example-io"> with the cost</span><span class="example-io"> 4.</span></li> <li>(7,4) to (10,4) with a cost of |10 - 7| + |4 - 4| = 3.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>start.length == target.length == 2</code></li> <li><code>1 &lt;= startX &lt;= targetX &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= startY &lt;= targetY &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= specialRoads.length &lt;= 200</code></li> <li><code>specialRoads[i].length == 5</code></li> <li><code>startX &lt;= x1<sub>i</sub>, x2<sub>i</sub> &lt;= targetX</code></li> <li><code>startY &lt;= y1<sub>i</sub>, y2<sub>i</sub> &lt;= targetY</code></li> <li><code>1 &lt;= cost<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Graph; Array; Shortest Path; Heap (Priority Queue)
C++
class Solution { public: int minimumCost(vector<int>& start, vector<int>& target, vector<vector<int>>& specialRoads) { auto dist = [](int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); }; int ans = 1 << 30; int n = 1e6; priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> pq; pq.push({0, start[0], start[1]}); unordered_set<long long> vis; while (!pq.empty()) { auto [d, x, y] = pq.top(); pq.pop(); long long k = 1LL * x * n + y; if (vis.count(k)) { continue; } vis.insert(k); ans = min(ans, d + dist(x, y, target[0], target[1])); for (auto& r : specialRoads) { int x1 = r[0], y1 = r[1], x2 = r[2], y2 = r[3], cost = r[4]; pq.push({d + dist(x, y, x1, y1) + cost, x2, y2}); } } return ans; } };
2,662
Minimum Cost of a Path With Special Roads
Medium
<p>You are given an array <code>start</code> where <code>start = [startX, startY]</code> represents your initial position <code>(startX, startY)</code> in a 2D space. You are also given the array <code>target</code> where <code>target = [targetX, targetY]</code> represents your target position <code>(targetX, targetY)</code>.</p> <p>The <strong>cost</strong> of going from a position <code>(x1, y1)</code> to any other position in the space <code>(x2, y2)</code> is <code>|x2 - x1| + |y2 - y1|</code>.</p> <p>There are also some <strong>special roads</strong>. You are given a 2D array <code>specialRoads</code> where <code>specialRoads[i] = [x1<sub>i</sub>, y1<sub>i</sub>, x2<sub>i</sub>, y2<sub>i</sub>, cost<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> special road goes in <strong>one direction</strong> from <code>(x1<sub>i</sub>, y1<sub>i</sub>)</code> to <code>(x2<sub>i</sub>, y2<sub>i</sub>)</code> with a cost equal to <code>cost<sub>i</sub></code>. You can use each special road any number of times.</p> <p>Return the <strong>minimum</strong> cost required to go from <code>(startX, startY)</code> to <code>(targetX, targetY)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [1,1], target = [4,5], specialRoads = [[1,2,3,3,2],[3,4,4,5,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ol> <li>(1,1) to (1,2) with a cost of |1 - 1| + |2 - 1| = 1.</li> <li>(1,2) to (3,3). Use <code><span class="example-io">specialRoads[0]</span></code><span class="example-io"> with</span><span class="example-io"> the cost 2.</span></li> <li><span class="example-io">(3,3) to (3,4) with a cost of |3 - 3| + |4 - 3| = 1.</span></li> <li><span class="example-io">(3,4) to (4,5). Use </span><code><span class="example-io">specialRoads[1]</span></code><span class="example-io"> with the cost</span><span class="example-io"> 1.</span></li> </ol> <p><span class="example-io">So the total cost is 1 + 2 + 1 + 1 = 5.</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [3,2], target = [5,7], specialRoads = [[5,7,3,2,1],[3,2,3,4,4],[3,3,5,5,5],[3,4,5,6,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>It is optimal not to use any special edges and go directly from the starting to the ending position with a cost |5 - 3| + |7 - 2| = 7.</p> <p>Note that the <span class="example-io"><code>specialRoads[0]</code> is directed from (5,7) to (3,2).</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [1,1], target = [10,4], specialRoads = [[4,2,1,1,3],[1,2,7,4,4],[10,3,6,1,2],[6,1,1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ol> <li>(1,1) to (1,2) with a cost of |1 - 1| + |2 - 1| = 1.</li> <li>(1,2) to (7,4). Use <code><span class="example-io">specialRoads[1]</span></code><span class="example-io"> with the cost</span><span class="example-io"> 4.</span></li> <li>(7,4) to (10,4) with a cost of |10 - 7| + |4 - 4| = 3.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>start.length == target.length == 2</code></li> <li><code>1 &lt;= startX &lt;= targetX &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= startY &lt;= targetY &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= specialRoads.length &lt;= 200</code></li> <li><code>specialRoads[i].length == 5</code></li> <li><code>startX &lt;= x1<sub>i</sub>, x2<sub>i</sub> &lt;= targetX</code></li> <li><code>startY &lt;= y1<sub>i</sub>, y2<sub>i</sub> &lt;= targetY</code></li> <li><code>1 &lt;= cost<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Graph; Array; Shortest Path; Heap (Priority Queue)
Go
func minimumCost(start []int, target []int, specialRoads [][]int) int { ans := 1 << 30 const n int = 1e6 pq := hp{{0, start[0], start[1]}} vis := map[int]bool{} for len(pq) > 0 { p := pq[0] heap.Pop(&pq) d, x, y := p.d, p.x, p.y if vis[x*n+y] { continue } vis[x*n+y] = true ans = min(ans, d+dist(x, y, target[0], target[1])) for _, r := range specialRoads { x1, y1, x2, y2, cost := r[0], r[1], r[2], r[3], r[4] heap.Push(&pq, tuple{d + dist(x, y, x1, y1) + cost, x2, y2}) } } return ans } func dist(x1, y1, x2, y2 int) int { return abs(x1-x2) + abs(y1-y2) } func abs(x int) int { if x < 0 { return -x } return x } type tuple struct { d, x, y int } type hp []tuple func (h hp) Len() int { return len(h) } func (h hp) Less(i, j int) bool { return h[i].d < h[j].d } func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
2,662
Minimum Cost of a Path With Special Roads
Medium
<p>You are given an array <code>start</code> where <code>start = [startX, startY]</code> represents your initial position <code>(startX, startY)</code> in a 2D space. You are also given the array <code>target</code> where <code>target = [targetX, targetY]</code> represents your target position <code>(targetX, targetY)</code>.</p> <p>The <strong>cost</strong> of going from a position <code>(x1, y1)</code> to any other position in the space <code>(x2, y2)</code> is <code>|x2 - x1| + |y2 - y1|</code>.</p> <p>There are also some <strong>special roads</strong>. You are given a 2D array <code>specialRoads</code> where <code>specialRoads[i] = [x1<sub>i</sub>, y1<sub>i</sub>, x2<sub>i</sub>, y2<sub>i</sub>, cost<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> special road goes in <strong>one direction</strong> from <code>(x1<sub>i</sub>, y1<sub>i</sub>)</code> to <code>(x2<sub>i</sub>, y2<sub>i</sub>)</code> with a cost equal to <code>cost<sub>i</sub></code>. You can use each special road any number of times.</p> <p>Return the <strong>minimum</strong> cost required to go from <code>(startX, startY)</code> to <code>(targetX, targetY)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [1,1], target = [4,5], specialRoads = [[1,2,3,3,2],[3,4,4,5,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ol> <li>(1,1) to (1,2) with a cost of |1 - 1| + |2 - 1| = 1.</li> <li>(1,2) to (3,3). Use <code><span class="example-io">specialRoads[0]</span></code><span class="example-io"> with</span><span class="example-io"> the cost 2.</span></li> <li><span class="example-io">(3,3) to (3,4) with a cost of |3 - 3| + |4 - 3| = 1.</span></li> <li><span class="example-io">(3,4) to (4,5). Use </span><code><span class="example-io">specialRoads[1]</span></code><span class="example-io"> with the cost</span><span class="example-io"> 1.</span></li> </ol> <p><span class="example-io">So the total cost is 1 + 2 + 1 + 1 = 5.</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [3,2], target = [5,7], specialRoads = [[5,7,3,2,1],[3,2,3,4,4],[3,3,5,5,5],[3,4,5,6,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>It is optimal not to use any special edges and go directly from the starting to the ending position with a cost |5 - 3| + |7 - 2| = 7.</p> <p>Note that the <span class="example-io"><code>specialRoads[0]</code> is directed from (5,7) to (3,2).</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [1,1], target = [10,4], specialRoads = [[4,2,1,1,3],[1,2,7,4,4],[10,3,6,1,2],[6,1,1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ol> <li>(1,1) to (1,2) with a cost of |1 - 1| + |2 - 1| = 1.</li> <li>(1,2) to (7,4). Use <code><span class="example-io">specialRoads[1]</span></code><span class="example-io"> with the cost</span><span class="example-io"> 4.</span></li> <li>(7,4) to (10,4) with a cost of |10 - 7| + |4 - 4| = 3.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>start.length == target.length == 2</code></li> <li><code>1 &lt;= startX &lt;= targetX &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= startY &lt;= targetY &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= specialRoads.length &lt;= 200</code></li> <li><code>specialRoads[i].length == 5</code></li> <li><code>startX &lt;= x1<sub>i</sub>, x2<sub>i</sub> &lt;= targetX</code></li> <li><code>startY &lt;= y1<sub>i</sub>, y2<sub>i</sub> &lt;= targetY</code></li> <li><code>1 &lt;= cost<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Graph; Array; Shortest Path; Heap (Priority Queue)
Java
class Solution { public int minimumCost(int[] start, int[] target, int[][] specialRoads) { int ans = 1 << 30; int n = 1000000; PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> a[0] - b[0]); Set<Long> vis = new HashSet<>(); q.offer(new int[] {0, start[0], start[1]}); while (!q.isEmpty()) { var p = q.poll(); int x = p[1], y = p[2]; long k = 1L * x * n + y; if (vis.contains(k)) { continue; } vis.add(k); int d = p[0]; ans = Math.min(ans, d + dist(x, y, target[0], target[1])); for (var r : specialRoads) { int x1 = r[0], y1 = r[1], x2 = r[2], y2 = r[3], cost = r[4]; q.offer(new int[] {d + dist(x, y, x1, y1) + cost, x2, y2}); } } return ans; } private int dist(int x1, int y1, int x2, int y2) { return Math.abs(x1 - x2) + Math.abs(y1 - y2); } }
2,662
Minimum Cost of a Path With Special Roads
Medium
<p>You are given an array <code>start</code> where <code>start = [startX, startY]</code> represents your initial position <code>(startX, startY)</code> in a 2D space. You are also given the array <code>target</code> where <code>target = [targetX, targetY]</code> represents your target position <code>(targetX, targetY)</code>.</p> <p>The <strong>cost</strong> of going from a position <code>(x1, y1)</code> to any other position in the space <code>(x2, y2)</code> is <code>|x2 - x1| + |y2 - y1|</code>.</p> <p>There are also some <strong>special roads</strong>. You are given a 2D array <code>specialRoads</code> where <code>specialRoads[i] = [x1<sub>i</sub>, y1<sub>i</sub>, x2<sub>i</sub>, y2<sub>i</sub>, cost<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> special road goes in <strong>one direction</strong> from <code>(x1<sub>i</sub>, y1<sub>i</sub>)</code> to <code>(x2<sub>i</sub>, y2<sub>i</sub>)</code> with a cost equal to <code>cost<sub>i</sub></code>. You can use each special road any number of times.</p> <p>Return the <strong>minimum</strong> cost required to go from <code>(startX, startY)</code> to <code>(targetX, targetY)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [1,1], target = [4,5], specialRoads = [[1,2,3,3,2],[3,4,4,5,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ol> <li>(1,1) to (1,2) with a cost of |1 - 1| + |2 - 1| = 1.</li> <li>(1,2) to (3,3). Use <code><span class="example-io">specialRoads[0]</span></code><span class="example-io"> with</span><span class="example-io"> the cost 2.</span></li> <li><span class="example-io">(3,3) to (3,4) with a cost of |3 - 3| + |4 - 3| = 1.</span></li> <li><span class="example-io">(3,4) to (4,5). Use </span><code><span class="example-io">specialRoads[1]</span></code><span class="example-io"> with the cost</span><span class="example-io"> 1.</span></li> </ol> <p><span class="example-io">So the total cost is 1 + 2 + 1 + 1 = 5.</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [3,2], target = [5,7], specialRoads = [[5,7,3,2,1],[3,2,3,4,4],[3,3,5,5,5],[3,4,5,6,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>It is optimal not to use any special edges and go directly from the starting to the ending position with a cost |5 - 3| + |7 - 2| = 7.</p> <p>Note that the <span class="example-io"><code>specialRoads[0]</code> is directed from (5,7) to (3,2).</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [1,1], target = [10,4], specialRoads = [[4,2,1,1,3],[1,2,7,4,4],[10,3,6,1,2],[6,1,1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ol> <li>(1,1) to (1,2) with a cost of |1 - 1| + |2 - 1| = 1.</li> <li>(1,2) to (7,4). Use <code><span class="example-io">specialRoads[1]</span></code><span class="example-io"> with the cost</span><span class="example-io"> 4.</span></li> <li>(7,4) to (10,4) with a cost of |10 - 7| + |4 - 4| = 3.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>start.length == target.length == 2</code></li> <li><code>1 &lt;= startX &lt;= targetX &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= startY &lt;= targetY &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= specialRoads.length &lt;= 200</code></li> <li><code>specialRoads[i].length == 5</code></li> <li><code>startX &lt;= x1<sub>i</sub>, x2<sub>i</sub> &lt;= targetX</code></li> <li><code>startY &lt;= y1<sub>i</sub>, y2<sub>i</sub> &lt;= targetY</code></li> <li><code>1 &lt;= cost<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Graph; Array; Shortest Path; Heap (Priority Queue)
Python
class Solution: def minimumCost( self, start: List[int], target: List[int], specialRoads: List[List[int]] ) -> int: def dist(x1: int, y1: int, x2: int, y2: int) -> int: return abs(x1 - x2) + abs(y1 - y2) q = [(0, start[0], start[1])] vis = set() ans = inf while q: d, x, y = heappop(q) if (x, y) in vis: continue vis.add((x, y)) ans = min(ans, d + dist(x, y, *target)) for x1, y1, x2, y2, cost in specialRoads: heappush(q, (d + dist(x, y, x1, y1) + cost, x2, y2)) return ans
2,662
Minimum Cost of a Path With Special Roads
Medium
<p>You are given an array <code>start</code> where <code>start = [startX, startY]</code> represents your initial position <code>(startX, startY)</code> in a 2D space. You are also given the array <code>target</code> where <code>target = [targetX, targetY]</code> represents your target position <code>(targetX, targetY)</code>.</p> <p>The <strong>cost</strong> of going from a position <code>(x1, y1)</code> to any other position in the space <code>(x2, y2)</code> is <code>|x2 - x1| + |y2 - y1|</code>.</p> <p>There are also some <strong>special roads</strong>. You are given a 2D array <code>specialRoads</code> where <code>specialRoads[i] = [x1<sub>i</sub>, y1<sub>i</sub>, x2<sub>i</sub>, y2<sub>i</sub>, cost<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> special road goes in <strong>one direction</strong> from <code>(x1<sub>i</sub>, y1<sub>i</sub>)</code> to <code>(x2<sub>i</sub>, y2<sub>i</sub>)</code> with a cost equal to <code>cost<sub>i</sub></code>. You can use each special road any number of times.</p> <p>Return the <strong>minimum</strong> cost required to go from <code>(startX, startY)</code> to <code>(targetX, targetY)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [1,1], target = [4,5], specialRoads = [[1,2,3,3,2],[3,4,4,5,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ol> <li>(1,1) to (1,2) with a cost of |1 - 1| + |2 - 1| = 1.</li> <li>(1,2) to (3,3). Use <code><span class="example-io">specialRoads[0]</span></code><span class="example-io"> with</span><span class="example-io"> the cost 2.</span></li> <li><span class="example-io">(3,3) to (3,4) with a cost of |3 - 3| + |4 - 3| = 1.</span></li> <li><span class="example-io">(3,4) to (4,5). Use </span><code><span class="example-io">specialRoads[1]</span></code><span class="example-io"> with the cost</span><span class="example-io"> 1.</span></li> </ol> <p><span class="example-io">So the total cost is 1 + 2 + 1 + 1 = 5.</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [3,2], target = [5,7], specialRoads = [[5,7,3,2,1],[3,2,3,4,4],[3,3,5,5,5],[3,4,5,6,6]]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>It is optimal not to use any special edges and go directly from the starting to the ending position with a cost |5 - 3| + |7 - 2| = 7.</p> <p>Note that the <span class="example-io"><code>specialRoads[0]</code> is directed from (5,7) to (3,2).</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">start = [1,1], target = [10,4], specialRoads = [[4,2,1,1,3],[1,2,7,4,4],[10,3,6,1,2],[6,1,1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <ol> <li>(1,1) to (1,2) with a cost of |1 - 1| + |2 - 1| = 1.</li> <li>(1,2) to (7,4). Use <code><span class="example-io">specialRoads[1]</span></code><span class="example-io"> with the cost</span><span class="example-io"> 4.</span></li> <li>(7,4) to (10,4) with a cost of |10 - 7| + |4 - 4| = 3.</li> </ol> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>start.length == target.length == 2</code></li> <li><code>1 &lt;= startX &lt;= targetX &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= startY &lt;= targetY &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= specialRoads.length &lt;= 200</code></li> <li><code>specialRoads[i].length == 5</code></li> <li><code>startX &lt;= x1<sub>i</sub>, x2<sub>i</sub> &lt;= targetX</code></li> <li><code>startY &lt;= y1<sub>i</sub>, y2<sub>i</sub> &lt;= targetY</code></li> <li><code>1 &lt;= cost<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Graph; Array; Shortest Path; Heap (Priority Queue)
TypeScript
function minimumCost(start: number[], target: number[], specialRoads: number[][]): number { const dist = (x1: number, y1: number, x2: number, y2: number): number => { return Math.abs(x1 - x2) + Math.abs(y1 - y2); }; const q = new Heap<[number, number, number]>((a, b) => a[0] - b[0]); q.push([0, start[0], start[1]]); const n = 1000000; const vis: Set<number> = new Set(); let ans = 1 << 30; while (q.size()) { const [d, x, y] = q.pop(); const k = x * n + y; if (vis.has(k)) { continue; } vis.add(k); ans = Math.min(ans, d + dist(x, y, target[0], target[1])); for (const [x1, y1, x2, y2, cost] of specialRoads) { q.push([d + dist(x, y, x1, y1) + cost, x2, y2]); } } return ans; } type Compare<T> = (lhs: T, rhs: T) => number; class Heap<T = number> { data: Array<T | null>; lt: (i: number, j: number) => boolean; constructor(); constructor(data: T[]); constructor(compare: Compare<T>); constructor(data: T[], compare: Compare<T>); constructor(data: T[] | Compare<T>, compare?: (lhs: T, rhs: T) => number); constructor( data: T[] | Compare<T> = [], compare: Compare<T> = (lhs: T, rhs: T) => (lhs < rhs ? -1 : lhs > rhs ? 1 : 0), ) { if (typeof data === 'function') { compare = data; data = []; } this.data = [null, ...data]; this.lt = (i, j) => compare(this.data[i]!, this.data[j]!) < 0; for (let i = this.size(); i > 0; i--) this.heapify(i); } size(): number { return this.data.length - 1; } push(v: T): void { this.data.push(v); let i = this.size(); while (i >> 1 !== 0 && this.lt(i, i >> 1)) this.swap(i, (i >>= 1)); } pop(): T { this.swap(1, this.size()); const top = this.data.pop(); this.heapify(1); return top!; } top(): T { return this.data[1]!; } heapify(i: number): void { while (true) { let min = i; const [l, r, n] = [i * 2, i * 2 + 1, this.data.length]; if (l < n && this.lt(l, min)) min = l; if (r < n && this.lt(r, min)) min = r; if (min !== i) { this.swap(i, min); i = min; } else break; } } clear(): void { this.data = [null]; } private swap(i: number, j: number): void { const d = this.data; [d[i], d[j]] = [d[j], d[i]]; } }
2,663
Lexicographically Smallest Beautiful String
Hard
<p>A string is <strong>beautiful</strong> if:</p> <ul> <li>It consists of the first <code>k</code> letters of the English lowercase alphabet.</li> <li>It does not contain any substring of length <code>2</code> or more which is a palindrome.</li> </ul> <p>You are given a beautiful string <code>s</code> of length <code>n</code> and a positive integer <code>k</code>.</p> <p>Return <em>the lexicographically smallest string of length </em><code>n</code><em>, which is larger than </em><code>s</code><em> and is <strong>beautiful</strong></em>. If there is no such string, return an empty string.</p> <p>A string <code>a</code> is lexicographically larger than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, <code>a</code> has a character strictly larger than the corresponding character in <code>b</code>.</p> <ul> <li>For example, <code>&quot;abcd&quot;</code> is lexicographically larger than <code>&quot;abcc&quot;</code> because the first position they differ is at the fourth character, and <code>d</code> is greater than <code>c</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcz&quot;, k = 26 <strong>Output:</strong> &quot;abda&quot; <strong>Explanation:</strong> The string &quot;abda&quot; is beautiful and lexicographically larger than the string &quot;abcz&quot;. It can be proven that there is no string that is lexicographically larger than the string &quot;abcz&quot;, beautiful, and lexicographically smaller than the string &quot;abda&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;dc&quot;, k = 4 <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> It can be proven that there is no string that is lexicographically larger than the string &quot;dc&quot; and is beautiful. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>4 &lt;= k &lt;= 26</code></li> <li><code>s</code> is a beautiful string.</li> </ul>
Greedy; String
C++
class Solution { public: string smallestBeautifulString(string s, int k) { int n = s.size(); for (int i = n - 1; i >= 0; --i) { int p = s[i] - 'a' + 1; for (int j = p; j < k; ++j) { char c = (char) ('a' + j); if ((i > 0 && s[i - 1] == c) || (i > 1 && s[i - 2] == c)) { continue; } s[i] = c; for (int l = i + 1; l < n; ++l) { for (int m = 0; m < k; ++m) { c = (char) ('a' + m); if ((l > 0 && s[l - 1] == c) || (l > 1 && s[l - 2] == c)) { continue; } s[l] = c; break; } } return s; } } return ""; } };
2,663
Lexicographically Smallest Beautiful String
Hard
<p>A string is <strong>beautiful</strong> if:</p> <ul> <li>It consists of the first <code>k</code> letters of the English lowercase alphabet.</li> <li>It does not contain any substring of length <code>2</code> or more which is a palindrome.</li> </ul> <p>You are given a beautiful string <code>s</code> of length <code>n</code> and a positive integer <code>k</code>.</p> <p>Return <em>the lexicographically smallest string of length </em><code>n</code><em>, which is larger than </em><code>s</code><em> and is <strong>beautiful</strong></em>. If there is no such string, return an empty string.</p> <p>A string <code>a</code> is lexicographically larger than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, <code>a</code> has a character strictly larger than the corresponding character in <code>b</code>.</p> <ul> <li>For example, <code>&quot;abcd&quot;</code> is lexicographically larger than <code>&quot;abcc&quot;</code> because the first position they differ is at the fourth character, and <code>d</code> is greater than <code>c</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcz&quot;, k = 26 <strong>Output:</strong> &quot;abda&quot; <strong>Explanation:</strong> The string &quot;abda&quot; is beautiful and lexicographically larger than the string &quot;abcz&quot;. It can be proven that there is no string that is lexicographically larger than the string &quot;abcz&quot;, beautiful, and lexicographically smaller than the string &quot;abda&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;dc&quot;, k = 4 <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> It can be proven that there is no string that is lexicographically larger than the string &quot;dc&quot; and is beautiful. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>4 &lt;= k &lt;= 26</code></li> <li><code>s</code> is a beautiful string.</li> </ul>
Greedy; String
Go
func smallestBeautifulString(s string, k int) string { cs := []byte(s) n := len(cs) for i := n - 1; i >= 0; i-- { p := int(cs[i] - 'a' + 1) for j := p; j < k; j++ { c := byte('a' + j) if (i > 0 && cs[i-1] == c) || (i > 1 && cs[i-2] == c) { continue } cs[i] = c for l := i + 1; l < n; l++ { for m := 0; m < k; m++ { c = byte('a' + m) if (l > 0 && cs[l-1] == c) || (l > 1 && cs[l-2] == c) { continue } cs[l] = c break } } return string(cs) } } return "" }
2,663
Lexicographically Smallest Beautiful String
Hard
<p>A string is <strong>beautiful</strong> if:</p> <ul> <li>It consists of the first <code>k</code> letters of the English lowercase alphabet.</li> <li>It does not contain any substring of length <code>2</code> or more which is a palindrome.</li> </ul> <p>You are given a beautiful string <code>s</code> of length <code>n</code> and a positive integer <code>k</code>.</p> <p>Return <em>the lexicographically smallest string of length </em><code>n</code><em>, which is larger than </em><code>s</code><em> and is <strong>beautiful</strong></em>. If there is no such string, return an empty string.</p> <p>A string <code>a</code> is lexicographically larger than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, <code>a</code> has a character strictly larger than the corresponding character in <code>b</code>.</p> <ul> <li>For example, <code>&quot;abcd&quot;</code> is lexicographically larger than <code>&quot;abcc&quot;</code> because the first position they differ is at the fourth character, and <code>d</code> is greater than <code>c</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcz&quot;, k = 26 <strong>Output:</strong> &quot;abda&quot; <strong>Explanation:</strong> The string &quot;abda&quot; is beautiful and lexicographically larger than the string &quot;abcz&quot;. It can be proven that there is no string that is lexicographically larger than the string &quot;abcz&quot;, beautiful, and lexicographically smaller than the string &quot;abda&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;dc&quot;, k = 4 <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> It can be proven that there is no string that is lexicographically larger than the string &quot;dc&quot; and is beautiful. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>4 &lt;= k &lt;= 26</code></li> <li><code>s</code> is a beautiful string.</li> </ul>
Greedy; String
Java
class Solution { public String smallestBeautifulString(String s, int k) { int n = s.length(); char[] cs = s.toCharArray(); for (int i = n - 1; i >= 0; --i) { int p = cs[i] - 'a' + 1; for (int j = p; j < k; ++j) { char c = (char) ('a' + j); if ((i > 0 && cs[i - 1] == c) || (i > 1 && cs[i - 2] == c)) { continue; } cs[i] = c; for (int l = i + 1; l < n; ++l) { for (int m = 0; m < k; ++m) { c = (char) ('a' + m); if ((l > 0 && cs[l - 1] == c) || (l > 1 && cs[l - 2] == c)) { continue; } cs[l] = c; break; } } return String.valueOf(cs); } } return ""; } }
2,663
Lexicographically Smallest Beautiful String
Hard
<p>A string is <strong>beautiful</strong> if:</p> <ul> <li>It consists of the first <code>k</code> letters of the English lowercase alphabet.</li> <li>It does not contain any substring of length <code>2</code> or more which is a palindrome.</li> </ul> <p>You are given a beautiful string <code>s</code> of length <code>n</code> and a positive integer <code>k</code>.</p> <p>Return <em>the lexicographically smallest string of length </em><code>n</code><em>, which is larger than </em><code>s</code><em> and is <strong>beautiful</strong></em>. If there is no such string, return an empty string.</p> <p>A string <code>a</code> is lexicographically larger than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, <code>a</code> has a character strictly larger than the corresponding character in <code>b</code>.</p> <ul> <li>For example, <code>&quot;abcd&quot;</code> is lexicographically larger than <code>&quot;abcc&quot;</code> because the first position they differ is at the fourth character, and <code>d</code> is greater than <code>c</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcz&quot;, k = 26 <strong>Output:</strong> &quot;abda&quot; <strong>Explanation:</strong> The string &quot;abda&quot; is beautiful and lexicographically larger than the string &quot;abcz&quot;. It can be proven that there is no string that is lexicographically larger than the string &quot;abcz&quot;, beautiful, and lexicographically smaller than the string &quot;abda&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;dc&quot;, k = 4 <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> It can be proven that there is no string that is lexicographically larger than the string &quot;dc&quot; and is beautiful. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>4 &lt;= k &lt;= 26</code></li> <li><code>s</code> is a beautiful string.</li> </ul>
Greedy; String
Python
class Solution: def smallestBeautifulString(self, s: str, k: int) -> str: n = len(s) cs = list(s) for i in range(n - 1, -1, -1): p = ord(cs[i]) - ord('a') + 1 for j in range(p, k): c = chr(ord('a') + j) if (i > 0 and cs[i - 1] == c) or (i > 1 and cs[i - 2] == c): continue cs[i] = c for l in range(i + 1, n): for m in range(k): c = chr(ord('a') + m) if (l > 0 and cs[l - 1] == c) or (l > 1 and cs[l - 2] == c): continue cs[l] = c break return ''.join(cs) return ''
2,663
Lexicographically Smallest Beautiful String
Hard
<p>A string is <strong>beautiful</strong> if:</p> <ul> <li>It consists of the first <code>k</code> letters of the English lowercase alphabet.</li> <li>It does not contain any substring of length <code>2</code> or more which is a palindrome.</li> </ul> <p>You are given a beautiful string <code>s</code> of length <code>n</code> and a positive integer <code>k</code>.</p> <p>Return <em>the lexicographically smallest string of length </em><code>n</code><em>, which is larger than </em><code>s</code><em> and is <strong>beautiful</strong></em>. If there is no such string, return an empty string.</p> <p>A string <code>a</code> is lexicographically larger than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, <code>a</code> has a character strictly larger than the corresponding character in <code>b</code>.</p> <ul> <li>For example, <code>&quot;abcd&quot;</code> is lexicographically larger than <code>&quot;abcc&quot;</code> because the first position they differ is at the fourth character, and <code>d</code> is greater than <code>c</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcz&quot;, k = 26 <strong>Output:</strong> &quot;abda&quot; <strong>Explanation:</strong> The string &quot;abda&quot; is beautiful and lexicographically larger than the string &quot;abcz&quot;. It can be proven that there is no string that is lexicographically larger than the string &quot;abcz&quot;, beautiful, and lexicographically smaller than the string &quot;abda&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;dc&quot;, k = 4 <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> It can be proven that there is no string that is lexicographically larger than the string &quot;dc&quot; and is beautiful. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>4 &lt;= k &lt;= 26</code></li> <li><code>s</code> is a beautiful string.</li> </ul>
Greedy; String
TypeScript
function smallestBeautifulString(s: string, k: number): string { const cs: string[] = s.split(''); const n = cs.length; for (let i = n - 1; i >= 0; --i) { const p = cs[i].charCodeAt(0) - 97 + 1; for (let j = p; j < k; ++j) { let c = String.fromCharCode(j + 97); if ((i > 0 && cs[i - 1] === c) || (i > 1 && cs[i - 2] === c)) { continue; } cs[i] = c; for (let l = i + 1; l < n; ++l) { for (let m = 0; m < k; ++m) { c = String.fromCharCode(m + 97); if ((l > 0 && cs[l - 1] === c) || (l > 1 && cs[l - 2] === c)) { continue; } cs[l] = c; break; } } return cs.join(''); } } return ''; }
2,664
The Knight’s Tour
Medium
<p>Given two positive integers <code>m</code> and <code>n</code> which are the height and width of a <strong>0-indexed</strong> 2D-array <code>board</code>, a pair of positive integers <code>(r, c)</code> which is the starting position of the knight on the board.</p> <p>Your task is to find an order of movements for the knight, in a manner that every cell of the&nbsp;<code>board</code> gets visited <strong>exactly</strong> once (the starting cell is considered visited and you <strong>shouldn&#39;t</strong> visit it again).</p> <p>Return <em>the array</em> <code>board</code> <em>in which the cells&#39; values show the order of visiting the cell starting from 0 (the initial place of the knight).</em></p> <p>Note that a <strong>knight</strong> can <strong>move</strong> from cell <code>(r1, c1)</code> to cell <code>(r2, c2)</code> if <code>0 &lt;= r2 &lt;= m - 1</code> and <code>0 &lt;= c2 &lt;= n - 1</code> and <code>min(abs(r1 - r2), abs(c1 - c2)) = 1</code> and <code>max(abs(r1 - r2), abs(c1 - c2)) = 2</code>.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 1, r = 0, c = 0 <strong>Output:</strong> [[0]] <strong>Explanation:</strong> There is only 1 cell and the knight is initially on it so there is only a 0 inside the 1x1 grid. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 4, r = 0, c = 0 <strong>Output:</strong> [[0,3,6,9],[11,8,1,4],[2,5,10,7]] <strong>Explanation:</strong> By the following order of movements we can visit the entire board. (0,0)-&gt;(1,2)-&gt;(2,0)-&gt;(0,1)-&gt;(1,3)-&gt;(2,1)-&gt;(0,2)-&gt;(2,3)-&gt;(1,1)-&gt;(0,3)-&gt;(2,2)-&gt;(1,0)</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m,&nbsp;n &lt;= 5</code></li> <li><code>0 &lt;= r &lt;= m - 1</code></li> <li><code>0 &lt;= c &lt;= n - 1</code></li> <li>The inputs will be generated such that there exists at least one&nbsp;possible order of movements with the given condition</li> </ul>
Array; Backtracking; Matrix
C++
class Solution { public: vector<vector<int>> tourOfKnight(int m, int n, int r, int c) { vector<vector<int>> g(m, vector<int>(n, -1)); g[r][c] = 0; int dirs[9] = {-2, -1, 2, 1, -2, 1, 2, -1, -2}; bool ok = false; function<void(int, int)> dfs = [&](int i, int j) { if (g[i][j] == m * n - 1) { ok = true; return; } for (int k = 0; k < 8; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && g[x][y] == -1) { g[x][y] = g[i][j] + 1; dfs(x, y); if (ok) { return; } g[x][y] = -1; } } }; dfs(r, c); return g; } };
2,664
The Knight’s Tour
Medium
<p>Given two positive integers <code>m</code> and <code>n</code> which are the height and width of a <strong>0-indexed</strong> 2D-array <code>board</code>, a pair of positive integers <code>(r, c)</code> which is the starting position of the knight on the board.</p> <p>Your task is to find an order of movements for the knight, in a manner that every cell of the&nbsp;<code>board</code> gets visited <strong>exactly</strong> once (the starting cell is considered visited and you <strong>shouldn&#39;t</strong> visit it again).</p> <p>Return <em>the array</em> <code>board</code> <em>in which the cells&#39; values show the order of visiting the cell starting from 0 (the initial place of the knight).</em></p> <p>Note that a <strong>knight</strong> can <strong>move</strong> from cell <code>(r1, c1)</code> to cell <code>(r2, c2)</code> if <code>0 &lt;= r2 &lt;= m - 1</code> and <code>0 &lt;= c2 &lt;= n - 1</code> and <code>min(abs(r1 - r2), abs(c1 - c2)) = 1</code> and <code>max(abs(r1 - r2), abs(c1 - c2)) = 2</code>.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 1, r = 0, c = 0 <strong>Output:</strong> [[0]] <strong>Explanation:</strong> There is only 1 cell and the knight is initially on it so there is only a 0 inside the 1x1 grid. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 4, r = 0, c = 0 <strong>Output:</strong> [[0,3,6,9],[11,8,1,4],[2,5,10,7]] <strong>Explanation:</strong> By the following order of movements we can visit the entire board. (0,0)-&gt;(1,2)-&gt;(2,0)-&gt;(0,1)-&gt;(1,3)-&gt;(2,1)-&gt;(0,2)-&gt;(2,3)-&gt;(1,1)-&gt;(0,3)-&gt;(2,2)-&gt;(1,0)</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m,&nbsp;n &lt;= 5</code></li> <li><code>0 &lt;= r &lt;= m - 1</code></li> <li><code>0 &lt;= c &lt;= n - 1</code></li> <li>The inputs will be generated such that there exists at least one&nbsp;possible order of movements with the given condition</li> </ul>
Array; Backtracking; Matrix
Go
func tourOfKnight(m int, n int, r int, c int) [][]int { g := make([][]int, m) for i := range g { g[i] = make([]int, n) for j := range g[i] { g[i][j] = -1 } } g[r][c] = 0 ok := false var dfs func(i, j int) dfs = func(i, j int) { if g[i][j] == m*n-1 { ok = true return } dirs := []int{-2, -1, 2, 1, -2, 1, 2, -1, -2} for k := 0; k < 8; k++ { x, y := i+dirs[k], j+dirs[k+1] if x >= 0 && x < m && y >= 0 && y < n && g[x][y] == -1 { g[x][y] = g[i][j] + 1 dfs(x, y) if ok { return } g[x][y] = -1 } } } dfs(r, c) return g }
2,664
The Knight’s Tour
Medium
<p>Given two positive integers <code>m</code> and <code>n</code> which are the height and width of a <strong>0-indexed</strong> 2D-array <code>board</code>, a pair of positive integers <code>(r, c)</code> which is the starting position of the knight on the board.</p> <p>Your task is to find an order of movements for the knight, in a manner that every cell of the&nbsp;<code>board</code> gets visited <strong>exactly</strong> once (the starting cell is considered visited and you <strong>shouldn&#39;t</strong> visit it again).</p> <p>Return <em>the array</em> <code>board</code> <em>in which the cells&#39; values show the order of visiting the cell starting from 0 (the initial place of the knight).</em></p> <p>Note that a <strong>knight</strong> can <strong>move</strong> from cell <code>(r1, c1)</code> to cell <code>(r2, c2)</code> if <code>0 &lt;= r2 &lt;= m - 1</code> and <code>0 &lt;= c2 &lt;= n - 1</code> and <code>min(abs(r1 - r2), abs(c1 - c2)) = 1</code> and <code>max(abs(r1 - r2), abs(c1 - c2)) = 2</code>.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 1, r = 0, c = 0 <strong>Output:</strong> [[0]] <strong>Explanation:</strong> There is only 1 cell and the knight is initially on it so there is only a 0 inside the 1x1 grid. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 4, r = 0, c = 0 <strong>Output:</strong> [[0,3,6,9],[11,8,1,4],[2,5,10,7]] <strong>Explanation:</strong> By the following order of movements we can visit the entire board. (0,0)-&gt;(1,2)-&gt;(2,0)-&gt;(0,1)-&gt;(1,3)-&gt;(2,1)-&gt;(0,2)-&gt;(2,3)-&gt;(1,1)-&gt;(0,3)-&gt;(2,2)-&gt;(1,0)</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m,&nbsp;n &lt;= 5</code></li> <li><code>0 &lt;= r &lt;= m - 1</code></li> <li><code>0 &lt;= c &lt;= n - 1</code></li> <li>The inputs will be generated such that there exists at least one&nbsp;possible order of movements with the given condition</li> </ul>
Array; Backtracking; Matrix
Java
class Solution { private int[][] g; private int m; private int n; private boolean ok; public int[][] tourOfKnight(int m, int n, int r, int c) { this.m = m; this.n = n; this.g = new int[m][n]; for (var row : g) { Arrays.fill(row, -1); } g[r][c] = 0; dfs(r, c); return g; } private void dfs(int i, int j) { if (g[i][j] == m * n - 1) { ok = true; return; } int[] dirs = {-2, -1, 2, 1, -2, 1, 2, -1, -2}; for (int k = 0; k < 8; ++k) { int x = i + dirs[k], y = j + dirs[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && g[x][y] == -1) { g[x][y] = g[i][j] + 1; dfs(x, y); if (ok) { return; } g[x][y] = -1; } } } }
2,664
The Knight’s Tour
Medium
<p>Given two positive integers <code>m</code> and <code>n</code> which are the height and width of a <strong>0-indexed</strong> 2D-array <code>board</code>, a pair of positive integers <code>(r, c)</code> which is the starting position of the knight on the board.</p> <p>Your task is to find an order of movements for the knight, in a manner that every cell of the&nbsp;<code>board</code> gets visited <strong>exactly</strong> once (the starting cell is considered visited and you <strong>shouldn&#39;t</strong> visit it again).</p> <p>Return <em>the array</em> <code>board</code> <em>in which the cells&#39; values show the order of visiting the cell starting from 0 (the initial place of the knight).</em></p> <p>Note that a <strong>knight</strong> can <strong>move</strong> from cell <code>(r1, c1)</code> to cell <code>(r2, c2)</code> if <code>0 &lt;= r2 &lt;= m - 1</code> and <code>0 &lt;= c2 &lt;= n - 1</code> and <code>min(abs(r1 - r2), abs(c1 - c2)) = 1</code> and <code>max(abs(r1 - r2), abs(c1 - c2)) = 2</code>.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 1, r = 0, c = 0 <strong>Output:</strong> [[0]] <strong>Explanation:</strong> There is only 1 cell and the knight is initially on it so there is only a 0 inside the 1x1 grid. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 4, r = 0, c = 0 <strong>Output:</strong> [[0,3,6,9],[11,8,1,4],[2,5,10,7]] <strong>Explanation:</strong> By the following order of movements we can visit the entire board. (0,0)-&gt;(1,2)-&gt;(2,0)-&gt;(0,1)-&gt;(1,3)-&gt;(2,1)-&gt;(0,2)-&gt;(2,3)-&gt;(1,1)-&gt;(0,3)-&gt;(2,2)-&gt;(1,0)</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m,&nbsp;n &lt;= 5</code></li> <li><code>0 &lt;= r &lt;= m - 1</code></li> <li><code>0 &lt;= c &lt;= n - 1</code></li> <li>The inputs will be generated such that there exists at least one&nbsp;possible order of movements with the given condition</li> </ul>
Array; Backtracking; Matrix
Python
class Solution: def tourOfKnight(self, m: int, n: int, r: int, c: int) -> List[List[int]]: def dfs(i: int, j: int): nonlocal ok if g[i][j] == m * n - 1: ok = True return for a, b in pairwise((-2, -1, 2, 1, -2, 1, 2, -1, -2)): x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and g[x][y] == -1: g[x][y] = g[i][j] + 1 dfs(x, y) if ok: return g[x][y] = -1 g = [[-1] * n for _ in range(m)] g[r][c] = 0 ok = False dfs(r, c) return g
2,664
The Knight’s Tour
Medium
<p>Given two positive integers <code>m</code> and <code>n</code> which are the height and width of a <strong>0-indexed</strong> 2D-array <code>board</code>, a pair of positive integers <code>(r, c)</code> which is the starting position of the knight on the board.</p> <p>Your task is to find an order of movements for the knight, in a manner that every cell of the&nbsp;<code>board</code> gets visited <strong>exactly</strong> once (the starting cell is considered visited and you <strong>shouldn&#39;t</strong> visit it again).</p> <p>Return <em>the array</em> <code>board</code> <em>in which the cells&#39; values show the order of visiting the cell starting from 0 (the initial place of the knight).</em></p> <p>Note that a <strong>knight</strong> can <strong>move</strong> from cell <code>(r1, c1)</code> to cell <code>(r2, c2)</code> if <code>0 &lt;= r2 &lt;= m - 1</code> and <code>0 &lt;= c2 &lt;= n - 1</code> and <code>min(abs(r1 - r2), abs(c1 - c2)) = 1</code> and <code>max(abs(r1 - r2), abs(c1 - c2)) = 2</code>.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 1, r = 0, c = 0 <strong>Output:</strong> [[0]] <strong>Explanation:</strong> There is only 1 cell and the knight is initially on it so there is only a 0 inside the 1x1 grid. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 4, r = 0, c = 0 <strong>Output:</strong> [[0,3,6,9],[11,8,1,4],[2,5,10,7]] <strong>Explanation:</strong> By the following order of movements we can visit the entire board. (0,0)-&gt;(1,2)-&gt;(2,0)-&gt;(0,1)-&gt;(1,3)-&gt;(2,1)-&gt;(0,2)-&gt;(2,3)-&gt;(1,1)-&gt;(0,3)-&gt;(2,2)-&gt;(1,0)</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m,&nbsp;n &lt;= 5</code></li> <li><code>0 &lt;= r &lt;= m - 1</code></li> <li><code>0 &lt;= c &lt;= n - 1</code></li> <li>The inputs will be generated such that there exists at least one&nbsp;possible order of movements with the given condition</li> </ul>
Array; Backtracking; Matrix
Rust
impl Solution { pub fn tour_of_knight(m: i32, n: i32, r: i32, c: i32) -> Vec<Vec<i32>> { let mut g: Vec<Vec<i32>> = vec![vec![-1; n as usize]; m as usize]; g[r as usize][c as usize] = 0; let dirs: [i32; 9] = [-2, -1, 2, 1, -2, 1, 2, -1, -2]; let mut ok = false; fn dfs( i: usize, j: usize, g: &mut Vec<Vec<i32>>, m: i32, n: i32, dirs: &[i32; 9], ok: &mut bool, ) { if g[i][j] == m * n - 1 { *ok = true; return; } for k in 0..8 { let x = ((i as i32) + dirs[k]) as usize; let y = ((j as i32) + dirs[k + 1]) as usize; if x < (m as usize) && y < (n as usize) && g[x][y] == -1 { g[x][y] = g[i][j] + 1; dfs(x, y, g, m, n, dirs, ok); if *ok { return; } g[x][y] = -1; } } } dfs(r as usize, c as usize, &mut g, m, n, &dirs, &mut ok); g } }
2,664
The Knight’s Tour
Medium
<p>Given two positive integers <code>m</code> and <code>n</code> which are the height and width of a <strong>0-indexed</strong> 2D-array <code>board</code>, a pair of positive integers <code>(r, c)</code> which is the starting position of the knight on the board.</p> <p>Your task is to find an order of movements for the knight, in a manner that every cell of the&nbsp;<code>board</code> gets visited <strong>exactly</strong> once (the starting cell is considered visited and you <strong>shouldn&#39;t</strong> visit it again).</p> <p>Return <em>the array</em> <code>board</code> <em>in which the cells&#39; values show the order of visiting the cell starting from 0 (the initial place of the knight).</em></p> <p>Note that a <strong>knight</strong> can <strong>move</strong> from cell <code>(r1, c1)</code> to cell <code>(r2, c2)</code> if <code>0 &lt;= r2 &lt;= m - 1</code> and <code>0 &lt;= c2 &lt;= n - 1</code> and <code>min(abs(r1 - r2), abs(c1 - c2)) = 1</code> and <code>max(abs(r1 - r2), abs(c1 - c2)) = 2</code>.</p> <p>&nbsp;</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 1, r = 0, c = 0 <strong>Output:</strong> [[0]] <strong>Explanation:</strong> There is only 1 cell and the knight is initially on it so there is only a 0 inside the 1x1 grid. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 4, r = 0, c = 0 <strong>Output:</strong> [[0,3,6,9],[11,8,1,4],[2,5,10,7]] <strong>Explanation:</strong> By the following order of movements we can visit the entire board. (0,0)-&gt;(1,2)-&gt;(2,0)-&gt;(0,1)-&gt;(1,3)-&gt;(2,1)-&gt;(0,2)-&gt;(2,3)-&gt;(1,1)-&gt;(0,3)-&gt;(2,2)-&gt;(1,0)</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m,&nbsp;n &lt;= 5</code></li> <li><code>0 &lt;= r &lt;= m - 1</code></li> <li><code>0 &lt;= c &lt;= n - 1</code></li> <li>The inputs will be generated such that there exists at least one&nbsp;possible order of movements with the given condition</li> </ul>
Array; Backtracking; Matrix
TypeScript
function tourOfKnight(m: number, n: number, r: number, c: number): number[][] { const g: number[][] = Array.from({ length: m }, () => Array(n).fill(-1)); const dirs = [-2, -1, 2, 1, -2, 1, 2, -1, -2]; let ok = false; const dfs = (i: number, j: number) => { if (g[i][j] === m * n - 1) { ok = true; return; } for (let k = 0; k < 8; ++k) { const [x, y] = [i + dirs[k], j + dirs[k + 1]]; if (x >= 0 && x < m && y >= 0 && y < n && g[x][y] === -1) { g[x][y] = g[i][j] + 1; dfs(x, y); if (ok) { return; } g[x][y] = -1; } } }; g[r][c] = 0; dfs(r, c); return g; }
2,665
Counter II
Easy
<p>Write a function&nbsp;<code>createCounter</code>. It should accept an initial integer&nbsp;<code>init</code>. It should return an object with three functions.</p> <p>The three functions are:</p> <ul> <li><code>increment()</code>&nbsp;increases&nbsp;the current value by 1 and then returns it.</li> <li><code>decrement()</code>&nbsp;reduces the current value by 1 and then returns it.</li> <li><code>reset()</code>&nbsp;sets the current value to&nbsp;<code>init</code>&nbsp;and then returns it.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> init = 5, calls = [&quot;increment&quot;,&quot;reset&quot;,&quot;decrement&quot;] <strong>Output:</strong> [6,5,4] <strong>Explanation:</strong> const counter = createCounter(5); counter.increment(); // 6 counter.reset(); // 5 counter.decrement(); // 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> init = 0, calls = [&quot;increment&quot;,&quot;increment&quot;,&quot;decrement&quot;,&quot;reset&quot;,&quot;reset&quot;] <strong>Output:</strong> [1,2,1,0,0] <strong>Explanation:</strong> const counter = createCounter(0); counter.increment(); // 1 counter.increment(); // 2 counter.decrement(); // 1 counter.reset(); // 0 counter.reset(); // 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-1000 &lt;= init &lt;= 1000</code></li> <li><code>0 &lt;= calls.length &lt;= 1000</code></li> <li><code>calls[i]</code> is one of &quot;increment&quot;, &quot;decrement&quot; and&nbsp;&quot;reset&quot;</li> </ul>
JavaScript
TypeScript
type ReturnObj = { increment: () => number; decrement: () => number; reset: () => number; }; function createCounter(init: number): ReturnObj { let val = init; return { increment() { return ++val; }, decrement() { return --val; }, reset() { return (val = init); }, }; } /** * const counter = createCounter(5) * counter.increment(); // 6 * counter.reset(); // 5 * counter.decrement(); // 4 */
2,666
Allow One Function Call
Easy
<p>Given a function <code>fn</code>, return a new function that is identical to the original function except that it ensures&nbsp;<code>fn</code>&nbsp;is&nbsp;called at most once.</p> <ul> <li>The first time the returned function is called, it should return the same result as&nbsp;<code>fn</code>.</li> <li>Every subsequent time it is called, it should return&nbsp;<code>undefined</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> fn = (a,b,c) =&gt; (a + b + c), calls = [[1,2,3],[2,3,6]] <strong>Output:</strong> [{&quot;calls&quot;:1,&quot;value&quot;:6}] <strong>Explanation:</strong> const onceFn = once(fn); onceFn(1, 2, 3); // 6 onceFn(2, 3, 6); // undefined, fn was not called </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> fn = (a,b,c) =&gt; (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]] <strong>Output:</strong> [{&quot;calls&quot;:1,&quot;value&quot;:140}] <strong>Explanation:</strong> const onceFn = once(fn); onceFn(5, 7, 4); // 140 onceFn(2, 3, 6); // undefined, fn was not called onceFn(4, 6, 8); // undefined, fn was not called </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>calls</code> is a valid JSON array</li> <li><code>1 &lt;= calls.length &lt;= 10</code></li> <li><code>1 &lt;= calls[i].length &lt;= 100</code></li> <li><code>2 &lt;= JSON.stringify(calls).length &lt;= 1000</code></li> </ul>
JavaScript
JavaScript
/** * @param {Function} fn * @return {Function} */ var once = function (fn) { let called = false; return function (...args) { if (!called) { called = true; return fn(...args); } }; }; /** * let fn = (a,b,c) => (a + b + c) * let onceFn = once(fn) * * onceFn(1,2,3); // 6 * onceFn(2,3,6); // returns undefined without calling fn */
2,666
Allow One Function Call
Easy
<p>Given a function <code>fn</code>, return a new function that is identical to the original function except that it ensures&nbsp;<code>fn</code>&nbsp;is&nbsp;called at most once.</p> <ul> <li>The first time the returned function is called, it should return the same result as&nbsp;<code>fn</code>.</li> <li>Every subsequent time it is called, it should return&nbsp;<code>undefined</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> fn = (a,b,c) =&gt; (a + b + c), calls = [[1,2,3],[2,3,6]] <strong>Output:</strong> [{&quot;calls&quot;:1,&quot;value&quot;:6}] <strong>Explanation:</strong> const onceFn = once(fn); onceFn(1, 2, 3); // 6 onceFn(2, 3, 6); // undefined, fn was not called </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> fn = (a,b,c) =&gt; (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]] <strong>Output:</strong> [{&quot;calls&quot;:1,&quot;value&quot;:140}] <strong>Explanation:</strong> const onceFn = once(fn); onceFn(5, 7, 4); // 140 onceFn(2, 3, 6); // undefined, fn was not called onceFn(4, 6, 8); // undefined, fn was not called </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>calls</code> is a valid JSON array</li> <li><code>1 &lt;= calls.length &lt;= 10</code></li> <li><code>1 &lt;= calls[i].length &lt;= 100</code></li> <li><code>2 &lt;= JSON.stringify(calls).length &lt;= 1000</code></li> </ul>
JavaScript
TypeScript
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }; type OnceFn = (...args: JSONValue[]) => JSONValue | undefined; function once(fn: Function): OnceFn { let called = false; return function (...args) { if (!called) { called = true; return fn(...args); } }; } /** * let fn = (a,b,c) => (a + b + c) * let onceFn = once(fn) * * onceFn(1,2,3); // 6 * onceFn(2,3,6); // returns undefined without calling fn */
2,667
Create Hello World Function
Easy
Write a function&nbsp;<code>createHelloWorld</code>.&nbsp;It should return a new function that always returns&nbsp;<code>&quot;Hello World&quot;</code>. <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> args = [] <strong>Output:</strong> &quot;Hello World&quot; <strong>Explanation:</strong> const f = createHelloWorld(); f(); // &quot;Hello World&quot; The function returned by createHelloWorld should always return &quot;Hello World&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> args = [{},null,42] <strong>Output:</strong> &quot;Hello World&quot; <strong>Explanation:</strong> const f = createHelloWorld(); f({}, null, 42); // &quot;Hello World&quot; Any arguments could be passed to the function but it should still always return &quot;Hello World&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= args.length &lt;= 10</code></li> </ul>
JavaScript
TypeScript
function createHelloWorld() { return function (...args): string { return 'Hello World'; }; } /** * const f = createHelloWorld(); * f(); // "Hello World" */
2,668
Find Latest Salaries
Easy
<p>Table: <code><font face="monospace">Salary</font></code></p> <pre> +---------------+---------+ | Column Name | Type | +---------------+---------+ | emp_id | int | | firstname | varchar | | lastname | varchar | | salary | varchar | | department_id | varchar | +---------------+---------+ (emp_id, salary) is the primary key (combination of columns with unique values) for this table. Each row contains employees details and their yearly salaries, however, some of the records are old and contain outdated salary information. </pre> <p>Write a solution to find the current salary of each employee assuming that salaries increase each year. Output their <code>emp_id</code>, <code>firstname</code>, <code>lastname</code>, <code>salary</code>, and <code>department_id</code>.</p> <p>Return the result table ordered&nbsp;by <code>emp_id</code> in <strong>ascending</strong> order<em>.</em></p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input: </strong><code>Salary</code> table: +--------+-----------+----------+--------+---------------+ | emp_id | firstname | lastname | salary | department_id | +--------+-----------+----------+--------+---------------+ | 1 | Todd | Wilson | 110000 | D1006 | | 1 | Todd | Wilson | 106119 | D1006 | | 2 | Justin | Simon | 128922 | D1005 | | 2 | Justin | Simon | 130000 | D1005 | | 3 | Kelly | Rosario | 42689 | D1002 | | 4 | Patricia | Powell | 162825 | D1004 | | 4 | Patricia | Powell | 170000 | D1004 | | 5 | Sherry | Golden | 44101 | D1002 | | 6 | Natasha | Swanson | 79632 | D1005 | | 6 | Natasha | Swanson | 90000 | D1005 | +--------+-----------+----------+--------+---------------+ <strong>Output: </strong>+--------+-----------+----------+--------+---------------+ | emp_id | firstname | lastname | salary | department_id | +--------+-----------+----------+--------+---------------+ | 1 | Todd | Wilson | 110000 | D1006 | | 2 | Justin | Simon | 130000 | D1005 | | 3 | Kelly | Rosario | 42689 | D1002 | | 4 | Patricia | Powell | 170000 | D1004 | | 5 | Sherry | Golden | 44101 | D1002 | | 6 | Natasha | Swanson | 90000 | D1005 | +--------+-----------+----------+--------+---------------+<strong> </strong> <strong>Explanation:</strong> - emp_id 1 has two records with a salary of&nbsp;110000, 106119 out of these 110000 is an updated salary (Assuming salary is increasing each year) - emp_id 2 has two records with a salary of&nbsp;128922, 130000&nbsp;out of these 130000 is an updated salary. - emp_id 3 has only one salary record so that is already an updated salary. - emp_id 4&nbsp;has two records with a salary of&nbsp;162825, 170000&nbsp;out of these 170000 is an updated salary. - emp_id 5&nbsp;has only one salary record so that is already an updated salary. - emp_id 6&nbsp;has two records with a salary of 79632, 90000 out&nbsp;of these 90000 is an updated salary. </pre>
Database
SQL
# Write your MySQL query statement below SELECT emp_id, firstname, lastname, MAX(salary) AS salary, department_id FROM Salary GROUP BY emp_id ORDER BY emp_id;
2,669
Count Artist Occurrences On Spotify Ranking List
Easy
<p>Table: <code><font face="monospace">Spotify</font></code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | track_name | varchar | | artist | varchar | +-------------+---------+ <code>id</code> is the primary key (column with unique values) for this table. Each row contains an id, track_name, and artist. </pre> <p>Write a solution to find how many times each artist appeared on the Spotify ranking list.</p> <p>Return the result table having the artist&#39;s name along with the corresponding number of occurrences&nbsp;ordered by occurrence count in&nbsp;<strong>descending </strong>order. If the occurrences are equal, then it&rsquo;s ordered by the artist&rsquo;s name in <strong>ascending</strong> order.</p> <p>The result format is in the following example​​​​​.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input: </strong>Spotify table: +---------+--------------------+------------+ | id | track_name | artist | +---------+--------------------+------------+ | 303651 | Heart Won&#39;t Forget | Sia | | 1046089 | Shape of you | Ed Sheeran | | 33445 | I&#39;m the one | DJ Khalid | | 811266 | Young Dumb &amp; Broke | DJ Khalid | | 505727 | Happier | Ed Sheeran | +---------+--------------------+------------+ <strong>Output: </strong>+------------+-------------+ | artist | occurrences | +------------+-------------+ | DJ Khalid | 2 | | Ed Sheeran | 2 | | Sia | 1 | +------------+-------------+ <strong>Explanation: </strong>The count of occurrences is listed in descending order under the column name &quot;occurrences&quot;. If the number of occurrences is the same, the artist&#39;s names are sorted in ascending order. </pre>
Database
SQL
# Write your MySQL query statement below SELECT artist, COUNT(1) AS occurrences FROM Spotify GROUP BY artist ORDER BY occurrences DESC, artist;
2,670
Find the Distinct Difference Array
Easy
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of length <code>n</code>.</p> <p>The <strong>distinct difference</strong> array of <code>nums</code> is an array <code>diff</code> of length <code>n</code> such that <code>diff[i]</code> is equal to the number of distinct elements in the suffix <code>nums[i + 1, ..., n - 1]</code> <strong>subtracted from</strong> the number of distinct elements in the prefix <code>nums[0, ..., i]</code>.</p> <p>Return <em>the <strong>distinct difference</strong> array of </em><code>nums</code>.</p> <p>Note that <code>nums[i, ..., j]</code> denotes the subarray of <code>nums</code> starting at index <code>i</code> and ending at index <code>j</code> inclusive. Particularly, if <code>i &gt; j</code> then <code>nums[i, ..., j]</code> denotes an empty subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> [-3,-1,1,3,5] <strong>Explanation:</strong> For index i = 0, there is 1 element in the prefix and 4 distinct elements in the suffix. Thus, diff[0] = 1 - 4 = -3. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 3 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 3 - 2 = 1. For index i = 3, there are 4 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 4 - 1 = 3. For index i = 4, there are 5 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 5 - 0 = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,3,4,2] <strong>Output:</strong> [-2,-1,0,2,3] <strong>Explanation:</strong> For index i = 0, there is 1 element in the prefix and 3 distinct elements in the suffix. Thus, diff[0] = 1 - 3 = -2. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 2 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 2 - 2 = 0. For index i = 3, there are 3 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 3 - 1 = 2. For index i = 4, there are 3 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 3 - 0 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length&nbsp;&lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Hash Table
C++
class Solution { public: vector<int> distinctDifferenceArray(vector<int>& nums) { int n = nums.size(); vector<int> suf(n + 1); unordered_set<int> s; for (int i = n - 1; i >= 0; --i) { s.insert(nums[i]); suf[i] = s.size(); } s.clear(); vector<int> ans(n); for (int i = 0; i < n; ++i) { s.insert(nums[i]); ans[i] = s.size() - suf[i + 1]; } return ans; } };
2,670
Find the Distinct Difference Array
Easy
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of length <code>n</code>.</p> <p>The <strong>distinct difference</strong> array of <code>nums</code> is an array <code>diff</code> of length <code>n</code> such that <code>diff[i]</code> is equal to the number of distinct elements in the suffix <code>nums[i + 1, ..., n - 1]</code> <strong>subtracted from</strong> the number of distinct elements in the prefix <code>nums[0, ..., i]</code>.</p> <p>Return <em>the <strong>distinct difference</strong> array of </em><code>nums</code>.</p> <p>Note that <code>nums[i, ..., j]</code> denotes the subarray of <code>nums</code> starting at index <code>i</code> and ending at index <code>j</code> inclusive. Particularly, if <code>i &gt; j</code> then <code>nums[i, ..., j]</code> denotes an empty subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> [-3,-1,1,3,5] <strong>Explanation:</strong> For index i = 0, there is 1 element in the prefix and 4 distinct elements in the suffix. Thus, diff[0] = 1 - 4 = -3. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 3 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 3 - 2 = 1. For index i = 3, there are 4 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 4 - 1 = 3. For index i = 4, there are 5 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 5 - 0 = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,3,4,2] <strong>Output:</strong> [-2,-1,0,2,3] <strong>Explanation:</strong> For index i = 0, there is 1 element in the prefix and 3 distinct elements in the suffix. Thus, diff[0] = 1 - 3 = -2. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 2 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 2 - 2 = 0. For index i = 3, there are 3 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 3 - 1 = 2. For index i = 4, there are 3 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 3 - 0 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length&nbsp;&lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Hash Table
Go
func distinctDifferenceArray(nums []int) []int { n := len(nums) suf := make([]int, n+1) s := map[int]bool{} for i := n - 1; i >= 0; i-- { s[nums[i]] = true suf[i] = len(s) } ans := make([]int, n) s = map[int]bool{} for i, x := range nums { s[x] = true ans[i] = len(s) - suf[i+1] } return ans }
2,670
Find the Distinct Difference Array
Easy
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of length <code>n</code>.</p> <p>The <strong>distinct difference</strong> array of <code>nums</code> is an array <code>diff</code> of length <code>n</code> such that <code>diff[i]</code> is equal to the number of distinct elements in the suffix <code>nums[i + 1, ..., n - 1]</code> <strong>subtracted from</strong> the number of distinct elements in the prefix <code>nums[0, ..., i]</code>.</p> <p>Return <em>the <strong>distinct difference</strong> array of </em><code>nums</code>.</p> <p>Note that <code>nums[i, ..., j]</code> denotes the subarray of <code>nums</code> starting at index <code>i</code> and ending at index <code>j</code> inclusive. Particularly, if <code>i &gt; j</code> then <code>nums[i, ..., j]</code> denotes an empty subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> [-3,-1,1,3,5] <strong>Explanation:</strong> For index i = 0, there is 1 element in the prefix and 4 distinct elements in the suffix. Thus, diff[0] = 1 - 4 = -3. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 3 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 3 - 2 = 1. For index i = 3, there are 4 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 4 - 1 = 3. For index i = 4, there are 5 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 5 - 0 = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,3,4,2] <strong>Output:</strong> [-2,-1,0,2,3] <strong>Explanation:</strong> For index i = 0, there is 1 element in the prefix and 3 distinct elements in the suffix. Thus, diff[0] = 1 - 3 = -2. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 2 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 2 - 2 = 0. For index i = 3, there are 3 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 3 - 1 = 2. For index i = 4, there are 3 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 3 - 0 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length&nbsp;&lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Hash Table
Java
class Solution { public int[] distinctDifferenceArray(int[] nums) { int n = nums.length; int[] suf = new int[n + 1]; Set<Integer> s = new HashSet<>(); for (int i = n - 1; i >= 0; --i) { s.add(nums[i]); suf[i] = s.size(); } s.clear(); int[] ans = new int[n]; for (int i = 0; i < n; ++i) { s.add(nums[i]); ans[i] = s.size() - suf[i + 1]; } return ans; } }
2,670
Find the Distinct Difference Array
Easy
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of length <code>n</code>.</p> <p>The <strong>distinct difference</strong> array of <code>nums</code> is an array <code>diff</code> of length <code>n</code> such that <code>diff[i]</code> is equal to the number of distinct elements in the suffix <code>nums[i + 1, ..., n - 1]</code> <strong>subtracted from</strong> the number of distinct elements in the prefix <code>nums[0, ..., i]</code>.</p> <p>Return <em>the <strong>distinct difference</strong> array of </em><code>nums</code>.</p> <p>Note that <code>nums[i, ..., j]</code> denotes the subarray of <code>nums</code> starting at index <code>i</code> and ending at index <code>j</code> inclusive. Particularly, if <code>i &gt; j</code> then <code>nums[i, ..., j]</code> denotes an empty subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> [-3,-1,1,3,5] <strong>Explanation:</strong> For index i = 0, there is 1 element in the prefix and 4 distinct elements in the suffix. Thus, diff[0] = 1 - 4 = -3. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 3 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 3 - 2 = 1. For index i = 3, there are 4 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 4 - 1 = 3. For index i = 4, there are 5 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 5 - 0 = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,3,4,2] <strong>Output:</strong> [-2,-1,0,2,3] <strong>Explanation:</strong> For index i = 0, there is 1 element in the prefix and 3 distinct elements in the suffix. Thus, diff[0] = 1 - 3 = -2. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 2 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 2 - 2 = 0. For index i = 3, there are 3 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 3 - 1 = 2. For index i = 4, there are 3 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 3 - 0 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length&nbsp;&lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Hash Table
Python
class Solution: def distinctDifferenceArray(self, nums: List[int]) -> List[int]: n = len(nums) suf = [0] * (n + 1) s = set() for i in range(n - 1, -1, -1): s.add(nums[i]) suf[i] = len(s) s.clear() ans = [0] * n for i, x in enumerate(nums): s.add(x) ans[i] = len(s) - suf[i + 1] return ans
2,670
Find the Distinct Difference Array
Easy
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of length <code>n</code>.</p> <p>The <strong>distinct difference</strong> array of <code>nums</code> is an array <code>diff</code> of length <code>n</code> such that <code>diff[i]</code> is equal to the number of distinct elements in the suffix <code>nums[i + 1, ..., n - 1]</code> <strong>subtracted from</strong> the number of distinct elements in the prefix <code>nums[0, ..., i]</code>.</p> <p>Return <em>the <strong>distinct difference</strong> array of </em><code>nums</code>.</p> <p>Note that <code>nums[i, ..., j]</code> denotes the subarray of <code>nums</code> starting at index <code>i</code> and ending at index <code>j</code> inclusive. Particularly, if <code>i &gt; j</code> then <code>nums[i, ..., j]</code> denotes an empty subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> [-3,-1,1,3,5] <strong>Explanation:</strong> For index i = 0, there is 1 element in the prefix and 4 distinct elements in the suffix. Thus, diff[0] = 1 - 4 = -3. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 3 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 3 - 2 = 1. For index i = 3, there are 4 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 4 - 1 = 3. For index i = 4, there are 5 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 5 - 0 = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,3,4,2] <strong>Output:</strong> [-2,-1,0,2,3] <strong>Explanation:</strong> For index i = 0, there is 1 element in the prefix and 3 distinct elements in the suffix. Thus, diff[0] = 1 - 3 = -2. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 2 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 2 - 2 = 0. For index i = 3, there are 3 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 3 - 1 = 2. For index i = 4, there are 3 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 3 - 0 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length&nbsp;&lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Hash Table
Rust
use std::collections::HashSet; impl Solution { pub fn distinct_difference_array(nums: Vec<i32>) -> Vec<i32> { let n = nums.len(); let mut suf = vec![0; n + 1]; let mut s = HashSet::new(); for i in (0..n).rev() { s.insert(nums[i]); suf[i] = s.len(); } let mut ans = Vec::new(); s.clear(); for i in 0..n { s.insert(nums[i]); ans.push((s.len() - suf[i + 1]) as i32); } ans } }
2,670
Find the Distinct Difference Array
Easy
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> of length <code>n</code>.</p> <p>The <strong>distinct difference</strong> array of <code>nums</code> is an array <code>diff</code> of length <code>n</code> such that <code>diff[i]</code> is equal to the number of distinct elements in the suffix <code>nums[i + 1, ..., n - 1]</code> <strong>subtracted from</strong> the number of distinct elements in the prefix <code>nums[0, ..., i]</code>.</p> <p>Return <em>the <strong>distinct difference</strong> array of </em><code>nums</code>.</p> <p>Note that <code>nums[i, ..., j]</code> denotes the subarray of <code>nums</code> starting at index <code>i</code> and ending at index <code>j</code> inclusive. Particularly, if <code>i &gt; j</code> then <code>nums[i, ..., j]</code> denotes an empty subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4,5] <strong>Output:</strong> [-3,-1,1,3,5] <strong>Explanation:</strong> For index i = 0, there is 1 element in the prefix and 4 distinct elements in the suffix. Thus, diff[0] = 1 - 4 = -3. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 3 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 3 - 2 = 1. For index i = 3, there are 4 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 4 - 1 = 3. For index i = 4, there are 5 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 5 - 0 = 5. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,3,4,2] <strong>Output:</strong> [-2,-1,0,2,3] <strong>Explanation:</strong> For index i = 0, there is 1 element in the prefix and 3 distinct elements in the suffix. Thus, diff[0] = 1 - 3 = -2. For index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1. For index i = 2, there are 2 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 2 - 2 = 0. For index i = 3, there are 3 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 3 - 1 = 2. For index i = 4, there are 3 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 3 - 0 = 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == nums.length&nbsp;&lt;= 50</code></li> <li><code>1 &lt;= nums[i] &lt;= 50</code></li> </ul>
Array; Hash Table
TypeScript
function distinctDifferenceArray(nums: number[]): number[] { const n = nums.length; const suf: number[] = Array(n + 1).fill(0); const s: Set<number> = new Set(); for (let i = n - 1; i >= 0; --i) { s.add(nums[i]); suf[i] = s.size; } s.clear(); const ans: number[] = Array(n).fill(0); for (let i = 0; i < n; ++i) { s.add(nums[i]); ans[i] = s.size - suf[i + 1]; } return ans; }
2,671
Frequency Tracker
Medium
<p>Design a data structure that keeps track of the values in it and answers some queries regarding their frequencies.</p> <p>Implement the <code>FrequencyTracker</code> class.</p> <ul> <li><code>FrequencyTracker()</code>: Initializes the <code>FrequencyTracker</code> object with an empty array initially.</li> <li><code>void add(int number)</code>: Adds <code>number</code> to the data structure.</li> <li><code>void deleteOne(int number)</code>: Deletes <strong>one</strong> occurrence of <code>number</code> from the data structure. The data structure <strong>may not contain</strong> <code>number</code>, and in this case nothing is deleted.</li> <li><code>bool hasFrequency(int frequency)</code>: Returns <code>true</code> if there is a number in the data structure that occurs <code>frequency</code> number of times, otherwise, it returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;add&quot;, &quot;add&quot;, &quot;hasFrequency&quot;] [[], [3], [3], [2]] <strong>Output</strong> [null, null, null, true] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.add(3); // The data structure now contains [3, 3] frequencyTracker.hasFrequency(2); // Returns true, because 3 occurs twice </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;add&quot;, &quot;deleteOne&quot;, &quot;hasFrequency&quot;] [[], [1], [1], [1]] <strong>Output</strong> [null, null, null, false] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(1); // The data structure now contains [1] frequencyTracker.deleteOne(1); // The data structure becomes empty [] frequencyTracker.hasFrequency(1); // Returns false, because the data structure is empty </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;hasFrequency&quot;, &quot;add&quot;, &quot;hasFrequency&quot;] [[], [2], [3], [1]] <strong>Output</strong> [null, false, null, true] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.hasFrequency(2); // Returns false, because the data structure is empty frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.hasFrequency(1); // Returns true, because 3 occurs once </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= number &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= frequency &lt;= 10<sup>5</sup></code></li> <li>At most, <code>2 *&nbsp;10<sup>5</sup></code>&nbsp;calls will be made to <code>add</code>, <code>deleteOne</code>, and <code>hasFrequency</code>&nbsp;in <strong>total</strong>.</li> </ul>
Design; Hash Table
C++
class FrequencyTracker { public: FrequencyTracker() { } void add(int number) { freq[cnt[number]]--; cnt[number]++; freq[cnt[number]]++; } void deleteOne(int number) { if (cnt[number]) { freq[cnt[number]]--; cnt[number]--; freq[cnt[number]]++; } } bool hasFrequency(int frequency) { return freq[frequency] > 0; } private: unordered_map<int, int> cnt; unordered_map<int, int> freq; }; /** * Your FrequencyTracker object will be instantiated and called as such: * FrequencyTracker* obj = new FrequencyTracker(); * obj->add(number); * obj->deleteOne(number); * bool param_3 = obj->hasFrequency(frequency); */
2,671
Frequency Tracker
Medium
<p>Design a data structure that keeps track of the values in it and answers some queries regarding their frequencies.</p> <p>Implement the <code>FrequencyTracker</code> class.</p> <ul> <li><code>FrequencyTracker()</code>: Initializes the <code>FrequencyTracker</code> object with an empty array initially.</li> <li><code>void add(int number)</code>: Adds <code>number</code> to the data structure.</li> <li><code>void deleteOne(int number)</code>: Deletes <strong>one</strong> occurrence of <code>number</code> from the data structure. The data structure <strong>may not contain</strong> <code>number</code>, and in this case nothing is deleted.</li> <li><code>bool hasFrequency(int frequency)</code>: Returns <code>true</code> if there is a number in the data structure that occurs <code>frequency</code> number of times, otherwise, it returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;add&quot;, &quot;add&quot;, &quot;hasFrequency&quot;] [[], [3], [3], [2]] <strong>Output</strong> [null, null, null, true] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.add(3); // The data structure now contains [3, 3] frequencyTracker.hasFrequency(2); // Returns true, because 3 occurs twice </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;add&quot;, &quot;deleteOne&quot;, &quot;hasFrequency&quot;] [[], [1], [1], [1]] <strong>Output</strong> [null, null, null, false] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(1); // The data structure now contains [1] frequencyTracker.deleteOne(1); // The data structure becomes empty [] frequencyTracker.hasFrequency(1); // Returns false, because the data structure is empty </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;hasFrequency&quot;, &quot;add&quot;, &quot;hasFrequency&quot;] [[], [2], [3], [1]] <strong>Output</strong> [null, false, null, true] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.hasFrequency(2); // Returns false, because the data structure is empty frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.hasFrequency(1); // Returns true, because 3 occurs once </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= number &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= frequency &lt;= 10<sup>5</sup></code></li> <li>At most, <code>2 *&nbsp;10<sup>5</sup></code>&nbsp;calls will be made to <code>add</code>, <code>deleteOne</code>, and <code>hasFrequency</code>&nbsp;in <strong>total</strong>.</li> </ul>
Design; Hash Table
Go
type FrequencyTracker struct { cnt map[int]int freq map[int]int } func Constructor() FrequencyTracker { return FrequencyTracker{map[int]int{}, map[int]int{}} } func (this *FrequencyTracker) Add(number int) { this.freq[this.cnt[number]]-- this.cnt[number]++ this.freq[this.cnt[number]]++ } func (this *FrequencyTracker) DeleteOne(number int) { if this.cnt[number] > 0 { this.freq[this.cnt[number]]-- this.cnt[number]-- this.freq[this.cnt[number]]++ } } func (this *FrequencyTracker) HasFrequency(frequency int) bool { return this.freq[frequency] > 0 } /** * Your FrequencyTracker object will be instantiated and called as such: * obj := Constructor(); * obj.Add(number); * obj.DeleteOne(number); * param_3 := obj.HasFrequency(frequency); */
2,671
Frequency Tracker
Medium
<p>Design a data structure that keeps track of the values in it and answers some queries regarding their frequencies.</p> <p>Implement the <code>FrequencyTracker</code> class.</p> <ul> <li><code>FrequencyTracker()</code>: Initializes the <code>FrequencyTracker</code> object with an empty array initially.</li> <li><code>void add(int number)</code>: Adds <code>number</code> to the data structure.</li> <li><code>void deleteOne(int number)</code>: Deletes <strong>one</strong> occurrence of <code>number</code> from the data structure. The data structure <strong>may not contain</strong> <code>number</code>, and in this case nothing is deleted.</li> <li><code>bool hasFrequency(int frequency)</code>: Returns <code>true</code> if there is a number in the data structure that occurs <code>frequency</code> number of times, otherwise, it returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;add&quot;, &quot;add&quot;, &quot;hasFrequency&quot;] [[], [3], [3], [2]] <strong>Output</strong> [null, null, null, true] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.add(3); // The data structure now contains [3, 3] frequencyTracker.hasFrequency(2); // Returns true, because 3 occurs twice </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;add&quot;, &quot;deleteOne&quot;, &quot;hasFrequency&quot;] [[], [1], [1], [1]] <strong>Output</strong> [null, null, null, false] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(1); // The data structure now contains [1] frequencyTracker.deleteOne(1); // The data structure becomes empty [] frequencyTracker.hasFrequency(1); // Returns false, because the data structure is empty </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;hasFrequency&quot;, &quot;add&quot;, &quot;hasFrequency&quot;] [[], [2], [3], [1]] <strong>Output</strong> [null, false, null, true] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.hasFrequency(2); // Returns false, because the data structure is empty frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.hasFrequency(1); // Returns true, because 3 occurs once </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= number &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= frequency &lt;= 10<sup>5</sup></code></li> <li>At most, <code>2 *&nbsp;10<sup>5</sup></code>&nbsp;calls will be made to <code>add</code>, <code>deleteOne</code>, and <code>hasFrequency</code>&nbsp;in <strong>total</strong>.</li> </ul>
Design; Hash Table
Java
class FrequencyTracker { private Map<Integer, Integer> cnt = new HashMap<>(); private Map<Integer, Integer> freq = new HashMap<>(); public FrequencyTracker() { } public void add(int number) { freq.merge(cnt.getOrDefault(number, 0), -1, Integer::sum); cnt.merge(number, 1, Integer::sum); freq.merge(cnt.get(number), 1, Integer::sum); } public void deleteOne(int number) { if (cnt.getOrDefault(number, 0) > 0) { freq.merge(cnt.get(number), -1, Integer::sum); cnt.merge(number, -1, Integer::sum); freq.merge(cnt.get(number), 1, Integer::sum); } } public boolean hasFrequency(int frequency) { return freq.getOrDefault(frequency, 0) > 0; } } /** * Your FrequencyTracker object will be instantiated and called as such: * FrequencyTracker obj = new FrequencyTracker(); * obj.add(number); * obj.deleteOne(number); * boolean param_3 = obj.hasFrequency(frequency); */
2,671
Frequency Tracker
Medium
<p>Design a data structure that keeps track of the values in it and answers some queries regarding their frequencies.</p> <p>Implement the <code>FrequencyTracker</code> class.</p> <ul> <li><code>FrequencyTracker()</code>: Initializes the <code>FrequencyTracker</code> object with an empty array initially.</li> <li><code>void add(int number)</code>: Adds <code>number</code> to the data structure.</li> <li><code>void deleteOne(int number)</code>: Deletes <strong>one</strong> occurrence of <code>number</code> from the data structure. The data structure <strong>may not contain</strong> <code>number</code>, and in this case nothing is deleted.</li> <li><code>bool hasFrequency(int frequency)</code>: Returns <code>true</code> if there is a number in the data structure that occurs <code>frequency</code> number of times, otherwise, it returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;add&quot;, &quot;add&quot;, &quot;hasFrequency&quot;] [[], [3], [3], [2]] <strong>Output</strong> [null, null, null, true] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.add(3); // The data structure now contains [3, 3] frequencyTracker.hasFrequency(2); // Returns true, because 3 occurs twice </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;add&quot;, &quot;deleteOne&quot;, &quot;hasFrequency&quot;] [[], [1], [1], [1]] <strong>Output</strong> [null, null, null, false] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(1); // The data structure now contains [1] frequencyTracker.deleteOne(1); // The data structure becomes empty [] frequencyTracker.hasFrequency(1); // Returns false, because the data structure is empty </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;hasFrequency&quot;, &quot;add&quot;, &quot;hasFrequency&quot;] [[], [2], [3], [1]] <strong>Output</strong> [null, false, null, true] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.hasFrequency(2); // Returns false, because the data structure is empty frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.hasFrequency(1); // Returns true, because 3 occurs once </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= number &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= frequency &lt;= 10<sup>5</sup></code></li> <li>At most, <code>2 *&nbsp;10<sup>5</sup></code>&nbsp;calls will be made to <code>add</code>, <code>deleteOne</code>, and <code>hasFrequency</code>&nbsp;in <strong>total</strong>.</li> </ul>
Design; Hash Table
Python
class FrequencyTracker: def __init__(self): self.cnt = defaultdict(int) self.freq = defaultdict(int) def add(self, number: int) -> None: self.freq[self.cnt[number]] -= 1 self.cnt[number] += 1 self.freq[self.cnt[number]] += 1 def deleteOne(self, number: int) -> None: if self.cnt[number]: self.freq[self.cnt[number]] -= 1 self.cnt[number] -= 1 self.freq[self.cnt[number]] += 1 def hasFrequency(self, frequency: int) -> bool: return self.freq[frequency] > 0 # Your FrequencyTracker object will be instantiated and called as such: # obj = FrequencyTracker() # obj.add(number) # obj.deleteOne(number) # param_3 = obj.hasFrequency(frequency)
2,671
Frequency Tracker
Medium
<p>Design a data structure that keeps track of the values in it and answers some queries regarding their frequencies.</p> <p>Implement the <code>FrequencyTracker</code> class.</p> <ul> <li><code>FrequencyTracker()</code>: Initializes the <code>FrequencyTracker</code> object with an empty array initially.</li> <li><code>void add(int number)</code>: Adds <code>number</code> to the data structure.</li> <li><code>void deleteOne(int number)</code>: Deletes <strong>one</strong> occurrence of <code>number</code> from the data structure. The data structure <strong>may not contain</strong> <code>number</code>, and in this case nothing is deleted.</li> <li><code>bool hasFrequency(int frequency)</code>: Returns <code>true</code> if there is a number in the data structure that occurs <code>frequency</code> number of times, otherwise, it returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;add&quot;, &quot;add&quot;, &quot;hasFrequency&quot;] [[], [3], [3], [2]] <strong>Output</strong> [null, null, null, true] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.add(3); // The data structure now contains [3, 3] frequencyTracker.hasFrequency(2); // Returns true, because 3 occurs twice </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;add&quot;, &quot;deleteOne&quot;, &quot;hasFrequency&quot;] [[], [1], [1], [1]] <strong>Output</strong> [null, null, null, false] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(1); // The data structure now contains [1] frequencyTracker.deleteOne(1); // The data structure becomes empty [] frequencyTracker.hasFrequency(1); // Returns false, because the data structure is empty </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;hasFrequency&quot;, &quot;add&quot;, &quot;hasFrequency&quot;] [[], [2], [3], [1]] <strong>Output</strong> [null, false, null, true] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.hasFrequency(2); // Returns false, because the data structure is empty frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.hasFrequency(1); // Returns true, because 3 occurs once </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= number &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= frequency &lt;= 10<sup>5</sup></code></li> <li>At most, <code>2 *&nbsp;10<sup>5</sup></code>&nbsp;calls will be made to <code>add</code>, <code>deleteOne</code>, and <code>hasFrequency</code>&nbsp;in <strong>total</strong>.</li> </ul>
Design; Hash Table
Rust
use std::collections::HashMap; struct FrequencyTracker { cnt: HashMap<i32, i32>, freq: HashMap<i32, i32>, } /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl FrequencyTracker { fn new() -> Self { FrequencyTracker { cnt: HashMap::new(), freq: HashMap::new(), } } fn add(&mut self, number: i32) { let count = self.cnt.entry(number).or_insert(0); let prev_freq = self.freq.entry(*count).or_insert(0); *prev_freq -= 1; *count += 1; let new_freq = self.freq.entry(*count).or_insert(0); *new_freq += 1; } fn delete_one(&mut self, number: i32) { if let Some(count) = self.cnt.get_mut(&number) { if *count > 0 { if let Some(prev_freq) = self.freq.get_mut(count) { *prev_freq -= 1; } *count -= 1; if let Some(new_freq) = self.freq.get_mut(count) { *new_freq += 1; } } } } fn has_frequency(&self, frequency: i32) -> bool { self.freq.get(&frequency).map_or(false, |&freq| freq > 0) } }
2,671
Frequency Tracker
Medium
<p>Design a data structure that keeps track of the values in it and answers some queries regarding their frequencies.</p> <p>Implement the <code>FrequencyTracker</code> class.</p> <ul> <li><code>FrequencyTracker()</code>: Initializes the <code>FrequencyTracker</code> object with an empty array initially.</li> <li><code>void add(int number)</code>: Adds <code>number</code> to the data structure.</li> <li><code>void deleteOne(int number)</code>: Deletes <strong>one</strong> occurrence of <code>number</code> from the data structure. The data structure <strong>may not contain</strong> <code>number</code>, and in this case nothing is deleted.</li> <li><code>bool hasFrequency(int frequency)</code>: Returns <code>true</code> if there is a number in the data structure that occurs <code>frequency</code> number of times, otherwise, it returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;add&quot;, &quot;add&quot;, &quot;hasFrequency&quot;] [[], [3], [3], [2]] <strong>Output</strong> [null, null, null, true] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.add(3); // The data structure now contains [3, 3] frequencyTracker.hasFrequency(2); // Returns true, because 3 occurs twice </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;add&quot;, &quot;deleteOne&quot;, &quot;hasFrequency&quot;] [[], [1], [1], [1]] <strong>Output</strong> [null, null, null, false] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.add(1); // The data structure now contains [1] frequencyTracker.deleteOne(1); // The data structure becomes empty [] frequencyTracker.hasFrequency(1); // Returns false, because the data structure is empty </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input</strong> [&quot;FrequencyTracker&quot;, &quot;hasFrequency&quot;, &quot;add&quot;, &quot;hasFrequency&quot;] [[], [2], [3], [1]] <strong>Output</strong> [null, false, null, true] <strong>Explanation</strong> FrequencyTracker frequencyTracker = new FrequencyTracker(); frequencyTracker.hasFrequency(2); // Returns false, because the data structure is empty frequencyTracker.add(3); // The data structure now contains [3] frequencyTracker.hasFrequency(1); // Returns true, because 3 occurs once </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= number &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= frequency &lt;= 10<sup>5</sup></code></li> <li>At most, <code>2 *&nbsp;10<sup>5</sup></code>&nbsp;calls will be made to <code>add</code>, <code>deleteOne</code>, and <code>hasFrequency</code>&nbsp;in <strong>total</strong>.</li> </ul>
Design; Hash Table
TypeScript
class FrequencyTracker { private cnt: Map<number, number>; private freq: Map<number, number>; constructor() { this.cnt = new Map(); this.freq = new Map(); } add(number: number): void { const f = this.cnt.get(number) || 0; this.freq.set(f, (this.freq.get(f) || 0) - 1); this.cnt.set(number, f + 1); this.freq.set(f + 1, (this.freq.get(f + 1) || 0) + 1); } deleteOne(number: number): void { const f = this.cnt.get(number) || 0; if (f > 0) { this.freq.set(f, (this.freq.get(f) || 0) - 1); this.cnt.set(number, f - 1); this.freq.set(f - 1, (this.freq.get(f - 1) || 0) + 1); } } hasFrequency(frequency: number): boolean { return (this.freq.get(frequency) || 0) > 0; } } /** * Your FrequencyTracker object will be instantiated and called as such: * var obj = new FrequencyTracker() * obj.add(number) * obj.deleteOne(number) * var param_3 = obj.hasFrequency(frequency) */
2,672
Number of Adjacent Elements With the Same Color
Medium
<p>You are given an integer <code>n</code> representing an array <code>colors</code> of length <code>n</code> where all elements are set to 0&#39;s meaning <strong>uncolored</strong>. You are also given a 2D integer array <code>queries</code> where <code>queries[i] = [index<sub>i</sub>, color<sub>i</sub>]</code>. For the <code>i<sup>th</sup></code> <strong>query</strong>:</p> <ul> <li>Set <code>colors[index<sub>i</sub>]</code> to <code>color<sub>i</sub></code>.</li> <li>Count the number of adjacent pairs in <code>colors</code> which have the same color (regardless of <code>color<sub>i</sub></code>).</li> </ul> <p>Return an array <code>answer</code> of the same length as <code>queries</code> where <code>answer[i]</code> is the answer to the <code>i<sup>th</sup></code> query.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1,1,0,2]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially array colors = [0,0,0,0], where 0 denotes uncolored elements of the array.</li> <li>After the 1<sup>st</sup> query colors = [2,0,0,0]. The count of adjacent pairs with the same color is 0.</li> <li>After the 2<sup>nd</sup> query colors = [2,2,0,0]. The count of adjacent pairs with the same color is 1.</li> <li>After the 3<sup>rd</sup> query colors = [2,2,0,1]. The count of adjacent pairs with the same color is 1.</li> <li>After the 4<sup>th</sup> query colors = [2,1,0,1]. The count of adjacent pairs with the same color is 0.</li> <li>After the 5<sup>th</sup> query colors = [2,1,1,1]. The count of adjacent pairs with the same color is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1, queries = [[0,100000]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <p>After the 1<sup>st</sup> query colors = [100000]. The count of adjacent pairs with the same color is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length&nbsp;== 2</code></li> <li><code>0 &lt;= index<sub>i</sub>&nbsp;&lt;= n - 1</code></li> <li><code>1 &lt;=&nbsp; color<sub>i</sub>&nbsp;&lt;= 10<sup>5</sup></code></li> </ul>
Array
C++
class Solution { public: vector<int> colorTheArray(int n, vector<vector<int>>& queries) { vector<int> nums(n); vector<int> ans; int x = 0; for (auto& q : queries) { int i = q[0], c = q[1]; if (i > 0 && nums[i] > 0 && nums[i - 1] == nums[i]) { --x; } if (i < n - 1 && nums[i] > 0 && nums[i + 1] == nums[i]) { --x; } if (i > 0 && nums[i - 1] == c) { ++x; } if (i < n - 1 && nums[i + 1] == c) { ++x; } ans.push_back(x); nums[i] = c; } return ans; } };
2,672
Number of Adjacent Elements With the Same Color
Medium
<p>You are given an integer <code>n</code> representing an array <code>colors</code> of length <code>n</code> where all elements are set to 0&#39;s meaning <strong>uncolored</strong>. You are also given a 2D integer array <code>queries</code> where <code>queries[i] = [index<sub>i</sub>, color<sub>i</sub>]</code>. For the <code>i<sup>th</sup></code> <strong>query</strong>:</p> <ul> <li>Set <code>colors[index<sub>i</sub>]</code> to <code>color<sub>i</sub></code>.</li> <li>Count the number of adjacent pairs in <code>colors</code> which have the same color (regardless of <code>color<sub>i</sub></code>).</li> </ul> <p>Return an array <code>answer</code> of the same length as <code>queries</code> where <code>answer[i]</code> is the answer to the <code>i<sup>th</sup></code> query.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1,1,0,2]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially array colors = [0,0,0,0], where 0 denotes uncolored elements of the array.</li> <li>After the 1<sup>st</sup> query colors = [2,0,0,0]. The count of adjacent pairs with the same color is 0.</li> <li>After the 2<sup>nd</sup> query colors = [2,2,0,0]. The count of adjacent pairs with the same color is 1.</li> <li>After the 3<sup>rd</sup> query colors = [2,2,0,1]. The count of adjacent pairs with the same color is 1.</li> <li>After the 4<sup>th</sup> query colors = [2,1,0,1]. The count of adjacent pairs with the same color is 0.</li> <li>After the 5<sup>th</sup> query colors = [2,1,1,1]. The count of adjacent pairs with the same color is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1, queries = [[0,100000]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <p>After the 1<sup>st</sup> query colors = [100000]. The count of adjacent pairs with the same color is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length&nbsp;== 2</code></li> <li><code>0 &lt;= index<sub>i</sub>&nbsp;&lt;= n - 1</code></li> <li><code>1 &lt;=&nbsp; color<sub>i</sub>&nbsp;&lt;= 10<sup>5</sup></code></li> </ul>
Array
Go
func colorTheArray(n int, queries [][]int) (ans []int) { nums := make([]int, n) x := 0 for _, q := range queries { i, c := q[0], q[1] if i > 0 && nums[i] > 0 && nums[i-1] == nums[i] { x-- } if i < n-1 && nums[i] > 0 && nums[i+1] == nums[i] { x-- } if i > 0 && nums[i-1] == c { x++ } if i < n-1 && nums[i+1] == c { x++ } ans = append(ans, x) nums[i] = c } return }
2,672
Number of Adjacent Elements With the Same Color
Medium
<p>You are given an integer <code>n</code> representing an array <code>colors</code> of length <code>n</code> where all elements are set to 0&#39;s meaning <strong>uncolored</strong>. You are also given a 2D integer array <code>queries</code> where <code>queries[i] = [index<sub>i</sub>, color<sub>i</sub>]</code>. For the <code>i<sup>th</sup></code> <strong>query</strong>:</p> <ul> <li>Set <code>colors[index<sub>i</sub>]</code> to <code>color<sub>i</sub></code>.</li> <li>Count the number of adjacent pairs in <code>colors</code> which have the same color (regardless of <code>color<sub>i</sub></code>).</li> </ul> <p>Return an array <code>answer</code> of the same length as <code>queries</code> where <code>answer[i]</code> is the answer to the <code>i<sup>th</sup></code> query.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1,1,0,2]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially array colors = [0,0,0,0], where 0 denotes uncolored elements of the array.</li> <li>After the 1<sup>st</sup> query colors = [2,0,0,0]. The count of adjacent pairs with the same color is 0.</li> <li>After the 2<sup>nd</sup> query colors = [2,2,0,0]. The count of adjacent pairs with the same color is 1.</li> <li>After the 3<sup>rd</sup> query colors = [2,2,0,1]. The count of adjacent pairs with the same color is 1.</li> <li>After the 4<sup>th</sup> query colors = [2,1,0,1]. The count of adjacent pairs with the same color is 0.</li> <li>After the 5<sup>th</sup> query colors = [2,1,1,1]. The count of adjacent pairs with the same color is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1, queries = [[0,100000]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <p>After the 1<sup>st</sup> query colors = [100000]. The count of adjacent pairs with the same color is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length&nbsp;== 2</code></li> <li><code>0 &lt;= index<sub>i</sub>&nbsp;&lt;= n - 1</code></li> <li><code>1 &lt;=&nbsp; color<sub>i</sub>&nbsp;&lt;= 10<sup>5</sup></code></li> </ul>
Array
Java
class Solution { public int[] colorTheArray(int n, int[][] queries) { int m = queries.length; int[] nums = new int[n]; int[] ans = new int[m]; for (int k = 0, x = 0; k < m; ++k) { int i = queries[k][0], c = queries[k][1]; if (i > 0 && nums[i] > 0 && nums[i - 1] == nums[i]) { --x; } if (i < n - 1 && nums[i] > 0 && nums[i + 1] == nums[i]) { --x; } if (i > 0 && nums[i - 1] == c) { ++x; } if (i < n - 1 && nums[i + 1] == c) { ++x; } ans[k] = x; nums[i] = c; } return ans; } }
2,672
Number of Adjacent Elements With the Same Color
Medium
<p>You are given an integer <code>n</code> representing an array <code>colors</code> of length <code>n</code> where all elements are set to 0&#39;s meaning <strong>uncolored</strong>. You are also given a 2D integer array <code>queries</code> where <code>queries[i] = [index<sub>i</sub>, color<sub>i</sub>]</code>. For the <code>i<sup>th</sup></code> <strong>query</strong>:</p> <ul> <li>Set <code>colors[index<sub>i</sub>]</code> to <code>color<sub>i</sub></code>.</li> <li>Count the number of adjacent pairs in <code>colors</code> which have the same color (regardless of <code>color<sub>i</sub></code>).</li> </ul> <p>Return an array <code>answer</code> of the same length as <code>queries</code> where <code>answer[i]</code> is the answer to the <code>i<sup>th</sup></code> query.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1,1,0,2]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially array colors = [0,0,0,0], where 0 denotes uncolored elements of the array.</li> <li>After the 1<sup>st</sup> query colors = [2,0,0,0]. The count of adjacent pairs with the same color is 0.</li> <li>After the 2<sup>nd</sup> query colors = [2,2,0,0]. The count of adjacent pairs with the same color is 1.</li> <li>After the 3<sup>rd</sup> query colors = [2,2,0,1]. The count of adjacent pairs with the same color is 1.</li> <li>After the 4<sup>th</sup> query colors = [2,1,0,1]. The count of adjacent pairs with the same color is 0.</li> <li>After the 5<sup>th</sup> query colors = [2,1,1,1]. The count of adjacent pairs with the same color is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1, queries = [[0,100000]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <p>After the 1<sup>st</sup> query colors = [100000]. The count of adjacent pairs with the same color is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length&nbsp;== 2</code></li> <li><code>0 &lt;= index<sub>i</sub>&nbsp;&lt;= n - 1</code></li> <li><code>1 &lt;=&nbsp; color<sub>i</sub>&nbsp;&lt;= 10<sup>5</sup></code></li> </ul>
Array
Python
class Solution: def colorTheArray(self, n: int, queries: List[List[int]]) -> List[int]: nums = [0] * n ans = [0] * len(queries) x = 0 for k, (i, c) in enumerate(queries): if i > 0 and nums[i] and nums[i - 1] == nums[i]: x -= 1 if i < n - 1 and nums[i] and nums[i + 1] == nums[i]: x -= 1 if i > 0 and nums[i - 1] == c: x += 1 if i < n - 1 and nums[i + 1] == c: x += 1 ans[k] = x nums[i] = c return ans
2,672
Number of Adjacent Elements With the Same Color
Medium
<p>You are given an integer <code>n</code> representing an array <code>colors</code> of length <code>n</code> where all elements are set to 0&#39;s meaning <strong>uncolored</strong>. You are also given a 2D integer array <code>queries</code> where <code>queries[i] = [index<sub>i</sub>, color<sub>i</sub>]</code>. For the <code>i<sup>th</sup></code> <strong>query</strong>:</p> <ul> <li>Set <code>colors[index<sub>i</sub>]</code> to <code>color<sub>i</sub></code>.</li> <li>Count the number of adjacent pairs in <code>colors</code> which have the same color (regardless of <code>color<sub>i</sub></code>).</li> </ul> <p>Return an array <code>answer</code> of the same length as <code>queries</code> where <code>answer[i]</code> is the answer to the <code>i<sup>th</sup></code> query.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0,1,1,0,2]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Initially array colors = [0,0,0,0], where 0 denotes uncolored elements of the array.</li> <li>After the 1<sup>st</sup> query colors = [2,0,0,0]. The count of adjacent pairs with the same color is 0.</li> <li>After the 2<sup>nd</sup> query colors = [2,2,0,0]. The count of adjacent pairs with the same color is 1.</li> <li>After the 3<sup>rd</sup> query colors = [2,2,0,1]. The count of adjacent pairs with the same color is 1.</li> <li>After the 4<sup>th</sup> query colors = [2,1,0,1]. The count of adjacent pairs with the same color is 0.</li> <li>After the 5<sup>th</sup> query colors = [2,1,1,1]. The count of adjacent pairs with the same color is 2.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1, queries = [[0,100000]]</span></p> <p><strong>Output:</strong> <span class="example-io">[0]</span></p> <p><strong>Explanation:</strong></p> <p>After the 1<sup>st</sup> query colors = [100000]. The count of adjacent pairs with the same color is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li> <li><code>queries[i].length&nbsp;== 2</code></li> <li><code>0 &lt;= index<sub>i</sub>&nbsp;&lt;= n - 1</code></li> <li><code>1 &lt;=&nbsp; color<sub>i</sub>&nbsp;&lt;= 10<sup>5</sup></code></li> </ul>
Array
TypeScript
function colorTheArray(n: number, queries: number[][]): number[] { const nums: number[] = new Array(n).fill(0); const ans: number[] = []; let x = 0; for (const [i, c] of queries) { if (i > 0 && nums[i] > 0 && nums[i - 1] == nums[i]) { --x; } if (i < n - 1 && nums[i] > 0 && nums[i + 1] == nums[i]) { --x; } if (i > 0 && nums[i - 1] == c) { ++x; } if (i < n - 1 && nums[i + 1] == c) { ++x; } ans.push(x); nums[i] = c; } return ans; }
2,673
Make Costs of Paths Equal in a Binary Tree
Medium
<p>You are given an integer <code>n</code> representing the number of nodes in a <strong>perfect binary tree</strong> consisting of nodes numbered from <code>1</code> to <code>n</code>. The root of the tree is node <code>1</code> and each node <code>i</code> in the tree has two children where the left child is the node <code>2 * i</code> and the right child is <code>2 * i + 1</code>.</p> <p>Each node in the tree also has a <strong>cost</strong> represented by a given <strong>0-indexed</strong> integer array <code>cost</code> of size <code>n</code> where <code>cost[i]</code> is the cost of node <code>i + 1</code>. You are allowed to <strong>increment</strong> the cost of <strong>any</strong> node by <code>1</code> <strong>any</strong> number of times.</p> <p>Return <em>the <strong>minimum</strong> number of increments you need to make the cost of paths from the root to each <strong>leaf</strong> node equal</em>.</p> <p><strong>Note</strong>:</p> <ul> <li>A <strong>perfect binary tree </strong>is a tree where each node, except the leaf nodes, has exactly 2 children.</li> <li>The <strong>cost of a path</strong> is the sum of costs of nodes in the path.</li> </ul> <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/2673.Make%20Costs%20of%20Paths%20Equal%20in%20a%20Binary%20Tree/images/binaryytreeedrawio-4.png" /> <pre> <strong>Input:</strong> n = 7, cost = [1,5,2,2,3,3,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> We can do the following increments: - Increase the cost of node 4 one time. - Increase the cost of node 3 three times. - Increase the cost of node 7 two times. Each path from the root to a leaf will have a total cost of 9. The total increments we did is 1 + 3 + 2 = 6. It can be shown that this is the minimum answer we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2673.Make%20Costs%20of%20Paths%20Equal%20in%20a%20Binary%20Tree/images/binaryytreee2drawio.png" style="width: 205px; height: 151px;" /> <pre> <strong>Input:</strong> n = 3, cost = [5,3,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The two paths already have equal total costs, so no increments are needed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n + 1</code> is a power of <code>2</code></li> <li><code>cost.length == n</code></li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Tree; Array; Dynamic Programming; Binary Tree
C++
class Solution { public: int minIncrements(int n, vector<int>& cost) { int ans = 0; for (int i = n >> 1; i > 0; --i) { int l = i << 1, r = i << 1 | 1; ans += abs(cost[l - 1] - cost[r - 1]); cost[i - 1] += max(cost[l - 1], cost[r - 1]); } return ans; } };
2,673
Make Costs of Paths Equal in a Binary Tree
Medium
<p>You are given an integer <code>n</code> representing the number of nodes in a <strong>perfect binary tree</strong> consisting of nodes numbered from <code>1</code> to <code>n</code>. The root of the tree is node <code>1</code> and each node <code>i</code> in the tree has two children where the left child is the node <code>2 * i</code> and the right child is <code>2 * i + 1</code>.</p> <p>Each node in the tree also has a <strong>cost</strong> represented by a given <strong>0-indexed</strong> integer array <code>cost</code> of size <code>n</code> where <code>cost[i]</code> is the cost of node <code>i + 1</code>. You are allowed to <strong>increment</strong> the cost of <strong>any</strong> node by <code>1</code> <strong>any</strong> number of times.</p> <p>Return <em>the <strong>minimum</strong> number of increments you need to make the cost of paths from the root to each <strong>leaf</strong> node equal</em>.</p> <p><strong>Note</strong>:</p> <ul> <li>A <strong>perfect binary tree </strong>is a tree where each node, except the leaf nodes, has exactly 2 children.</li> <li>The <strong>cost of a path</strong> is the sum of costs of nodes in the path.</li> </ul> <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/2673.Make%20Costs%20of%20Paths%20Equal%20in%20a%20Binary%20Tree/images/binaryytreeedrawio-4.png" /> <pre> <strong>Input:</strong> n = 7, cost = [1,5,2,2,3,3,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> We can do the following increments: - Increase the cost of node 4 one time. - Increase the cost of node 3 three times. - Increase the cost of node 7 two times. Each path from the root to a leaf will have a total cost of 9. The total increments we did is 1 + 3 + 2 = 6. It can be shown that this is the minimum answer we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2673.Make%20Costs%20of%20Paths%20Equal%20in%20a%20Binary%20Tree/images/binaryytreee2drawio.png" style="width: 205px; height: 151px;" /> <pre> <strong>Input:</strong> n = 3, cost = [5,3,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The two paths already have equal total costs, so no increments are needed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n + 1</code> is a power of <code>2</code></li> <li><code>cost.length == n</code></li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Tree; Array; Dynamic Programming; Binary Tree
Go
func minIncrements(n int, cost []int) (ans int) { for i := n >> 1; i > 0; i-- { l, r := i<<1, i<<1|1 ans += abs(cost[l-1] - cost[r-1]) cost[i-1] += max(cost[l-1], cost[r-1]) } return } func abs(x int) int { if x < 0 { return -x } return x }
2,673
Make Costs of Paths Equal in a Binary Tree
Medium
<p>You are given an integer <code>n</code> representing the number of nodes in a <strong>perfect binary tree</strong> consisting of nodes numbered from <code>1</code> to <code>n</code>. The root of the tree is node <code>1</code> and each node <code>i</code> in the tree has two children where the left child is the node <code>2 * i</code> and the right child is <code>2 * i + 1</code>.</p> <p>Each node in the tree also has a <strong>cost</strong> represented by a given <strong>0-indexed</strong> integer array <code>cost</code> of size <code>n</code> where <code>cost[i]</code> is the cost of node <code>i + 1</code>. You are allowed to <strong>increment</strong> the cost of <strong>any</strong> node by <code>1</code> <strong>any</strong> number of times.</p> <p>Return <em>the <strong>minimum</strong> number of increments you need to make the cost of paths from the root to each <strong>leaf</strong> node equal</em>.</p> <p><strong>Note</strong>:</p> <ul> <li>A <strong>perfect binary tree </strong>is a tree where each node, except the leaf nodes, has exactly 2 children.</li> <li>The <strong>cost of a path</strong> is the sum of costs of nodes in the path.</li> </ul> <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/2673.Make%20Costs%20of%20Paths%20Equal%20in%20a%20Binary%20Tree/images/binaryytreeedrawio-4.png" /> <pre> <strong>Input:</strong> n = 7, cost = [1,5,2,2,3,3,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> We can do the following increments: - Increase the cost of node 4 one time. - Increase the cost of node 3 three times. - Increase the cost of node 7 two times. Each path from the root to a leaf will have a total cost of 9. The total increments we did is 1 + 3 + 2 = 6. It can be shown that this is the minimum answer we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2673.Make%20Costs%20of%20Paths%20Equal%20in%20a%20Binary%20Tree/images/binaryytreee2drawio.png" style="width: 205px; height: 151px;" /> <pre> <strong>Input:</strong> n = 3, cost = [5,3,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The two paths already have equal total costs, so no increments are needed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n + 1</code> is a power of <code>2</code></li> <li><code>cost.length == n</code></li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Tree; Array; Dynamic Programming; Binary Tree
Java
class Solution { public int minIncrements(int n, int[] cost) { int ans = 0; for (int i = n >> 1; i > 0; --i) { int l = i << 1, r = i << 1 | 1; ans += Math.abs(cost[l - 1] - cost[r - 1]); cost[i - 1] += Math.max(cost[l - 1], cost[r - 1]); } return ans; } }
2,673
Make Costs of Paths Equal in a Binary Tree
Medium
<p>You are given an integer <code>n</code> representing the number of nodes in a <strong>perfect binary tree</strong> consisting of nodes numbered from <code>1</code> to <code>n</code>. The root of the tree is node <code>1</code> and each node <code>i</code> in the tree has two children where the left child is the node <code>2 * i</code> and the right child is <code>2 * i + 1</code>.</p> <p>Each node in the tree also has a <strong>cost</strong> represented by a given <strong>0-indexed</strong> integer array <code>cost</code> of size <code>n</code> where <code>cost[i]</code> is the cost of node <code>i + 1</code>. You are allowed to <strong>increment</strong> the cost of <strong>any</strong> node by <code>1</code> <strong>any</strong> number of times.</p> <p>Return <em>the <strong>minimum</strong> number of increments you need to make the cost of paths from the root to each <strong>leaf</strong> node equal</em>.</p> <p><strong>Note</strong>:</p> <ul> <li>A <strong>perfect binary tree </strong>is a tree where each node, except the leaf nodes, has exactly 2 children.</li> <li>The <strong>cost of a path</strong> is the sum of costs of nodes in the path.</li> </ul> <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/2673.Make%20Costs%20of%20Paths%20Equal%20in%20a%20Binary%20Tree/images/binaryytreeedrawio-4.png" /> <pre> <strong>Input:</strong> n = 7, cost = [1,5,2,2,3,3,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> We can do the following increments: - Increase the cost of node 4 one time. - Increase the cost of node 3 three times. - Increase the cost of node 7 two times. Each path from the root to a leaf will have a total cost of 9. The total increments we did is 1 + 3 + 2 = 6. It can be shown that this is the minimum answer we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2673.Make%20Costs%20of%20Paths%20Equal%20in%20a%20Binary%20Tree/images/binaryytreee2drawio.png" style="width: 205px; height: 151px;" /> <pre> <strong>Input:</strong> n = 3, cost = [5,3,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The two paths already have equal total costs, so no increments are needed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n + 1</code> is a power of <code>2</code></li> <li><code>cost.length == n</code></li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Tree; Array; Dynamic Programming; Binary Tree
Python
class Solution: def minIncrements(self, n: int, cost: List[int]) -> int: ans = 0 for i in range(n >> 1, 0, -1): l, r = i << 1, i << 1 | 1 ans += abs(cost[l - 1] - cost[r - 1]) cost[i - 1] += max(cost[l - 1], cost[r - 1]) return ans
2,673
Make Costs of Paths Equal in a Binary Tree
Medium
<p>You are given an integer <code>n</code> representing the number of nodes in a <strong>perfect binary tree</strong> consisting of nodes numbered from <code>1</code> to <code>n</code>. The root of the tree is node <code>1</code> and each node <code>i</code> in the tree has two children where the left child is the node <code>2 * i</code> and the right child is <code>2 * i + 1</code>.</p> <p>Each node in the tree also has a <strong>cost</strong> represented by a given <strong>0-indexed</strong> integer array <code>cost</code> of size <code>n</code> where <code>cost[i]</code> is the cost of node <code>i + 1</code>. You are allowed to <strong>increment</strong> the cost of <strong>any</strong> node by <code>1</code> <strong>any</strong> number of times.</p> <p>Return <em>the <strong>minimum</strong> number of increments you need to make the cost of paths from the root to each <strong>leaf</strong> node equal</em>.</p> <p><strong>Note</strong>:</p> <ul> <li>A <strong>perfect binary tree </strong>is a tree where each node, except the leaf nodes, has exactly 2 children.</li> <li>The <strong>cost of a path</strong> is the sum of costs of nodes in the path.</li> </ul> <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/2673.Make%20Costs%20of%20Paths%20Equal%20in%20a%20Binary%20Tree/images/binaryytreeedrawio-4.png" /> <pre> <strong>Input:</strong> n = 7, cost = [1,5,2,2,3,3,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> We can do the following increments: - Increase the cost of node 4 one time. - Increase the cost of node 3 three times. - Increase the cost of node 7 two times. Each path from the root to a leaf will have a total cost of 9. The total increments we did is 1 + 3 + 2 = 6. It can be shown that this is the minimum answer we can achieve. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2673.Make%20Costs%20of%20Paths%20Equal%20in%20a%20Binary%20Tree/images/binaryytreee2drawio.png" style="width: 205px; height: 151px;" /> <pre> <strong>Input:</strong> n = 3, cost = [5,3,3] <strong>Output:</strong> 0 <strong>Explanation:</strong> The two paths already have equal total costs, so no increments are needed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>n + 1</code> is a power of <code>2</code></li> <li><code>cost.length == n</code></li> <li><code>1 &lt;= cost[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Tree; Array; Dynamic Programming; Binary Tree
TypeScript
function minIncrements(n: number, cost: number[]): number { let ans = 0; for (let i = n >> 1; i; --i) { const [l, r] = [i << 1, (i << 1) | 1]; ans += Math.abs(cost[l - 1] - cost[r - 1]); cost[i - 1] += Math.max(cost[l - 1], cost[r - 1]); } return ans; }
2,674
Split a Circular Linked List
Medium
<p>Given a <strong>circular linked list</strong> <code>list</code> of positive integers, your task is to split it into 2 <strong>circular linked lists</strong> so that the first one contains the <strong>first half</strong> of the nodes in <code>list</code> (exactly <code>ceil(list.length / 2)</code> nodes) in the same order they appeared in <code>list</code>, and the second one contains <strong>the rest</strong> of the nodes in <code>list</code> in the same order they appeared in <code>list</code>.</p> <p>Return <em>an array answer of length 2 in which the first element is a <strong>circular linked list</strong> representing the <strong>first half</strong> and the second element is a <strong>circular linked list</strong> representing the <strong>second half</strong>.</em></p> <div>A <strong>circular linked list</strong> is a normal linked list with the only difference being that the last node&#39;s next node, is the first node.</div> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,7] <strong>Output:</strong> [[1,5],[7]] <strong>Explanation:</strong> The initial list has 3 nodes so the first half would be the first 2 elements since ceil(3 / 2) = 2 and the rest which is 1 node is in the second half. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,1,5] <strong>Output:</strong> [[2,6],[1,5]] <strong>Explanation:</strong> The initial list has 4 nodes so the first half would be the first 2 elements since ceil(4 / 2) = 2 and the rest which is 2 nodes are in the second half. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in <code>list</code>&nbsp;is in the range <code>[2, 10<sup>5</sup>]</code></li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><font face="monospace"><code>LastNode.next = FirstNode</code></font> where <code>LastNode</code> is the last node of the list and <code>FirstNode</code> is the first one</li> </ul>
Linked List; Two Pointers
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: vector<ListNode*> splitCircularLinkedList(ListNode* list) { ListNode* a = list; ListNode* b = list; while (b->next != list && b->next->next != list) { a = a->next; b = b->next->next; } if (b->next != list) { b = b->next; } ListNode* list2 = a->next; b->next = list2; a->next = list; return {list, list2}; } };
2,674
Split a Circular Linked List
Medium
<p>Given a <strong>circular linked list</strong> <code>list</code> of positive integers, your task is to split it into 2 <strong>circular linked lists</strong> so that the first one contains the <strong>first half</strong> of the nodes in <code>list</code> (exactly <code>ceil(list.length / 2)</code> nodes) in the same order they appeared in <code>list</code>, and the second one contains <strong>the rest</strong> of the nodes in <code>list</code> in the same order they appeared in <code>list</code>.</p> <p>Return <em>an array answer of length 2 in which the first element is a <strong>circular linked list</strong> representing the <strong>first half</strong> and the second element is a <strong>circular linked list</strong> representing the <strong>second half</strong>.</em></p> <div>A <strong>circular linked list</strong> is a normal linked list with the only difference being that the last node&#39;s next node, is the first node.</div> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,7] <strong>Output:</strong> [[1,5],[7]] <strong>Explanation:</strong> The initial list has 3 nodes so the first half would be the first 2 elements since ceil(3 / 2) = 2 and the rest which is 1 node is in the second half. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,1,5] <strong>Output:</strong> [[2,6],[1,5]] <strong>Explanation:</strong> The initial list has 4 nodes so the first half would be the first 2 elements since ceil(4 / 2) = 2 and the rest which is 2 nodes are in the second half. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in <code>list</code>&nbsp;is in the range <code>[2, 10<sup>5</sup>]</code></li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><font face="monospace"><code>LastNode.next = FirstNode</code></font> where <code>LastNode</code> is the last node of the list and <code>FirstNode</code> is the first one</li> </ul>
Linked List; Two Pointers
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func splitCircularLinkedList(list *ListNode) []*ListNode { a, b := list, list for b.Next != list && b.Next.Next != list { a = a.Next b = b.Next.Next } if b.Next != list { b = b.Next } list2 := a.Next b.Next = list2 a.Next = list return []*ListNode{list, list2} }
2,674
Split a Circular Linked List
Medium
<p>Given a <strong>circular linked list</strong> <code>list</code> of positive integers, your task is to split it into 2 <strong>circular linked lists</strong> so that the first one contains the <strong>first half</strong> of the nodes in <code>list</code> (exactly <code>ceil(list.length / 2)</code> nodes) in the same order they appeared in <code>list</code>, and the second one contains <strong>the rest</strong> of the nodes in <code>list</code> in the same order they appeared in <code>list</code>.</p> <p>Return <em>an array answer of length 2 in which the first element is a <strong>circular linked list</strong> representing the <strong>first half</strong> and the second element is a <strong>circular linked list</strong> representing the <strong>second half</strong>.</em></p> <div>A <strong>circular linked list</strong> is a normal linked list with the only difference being that the last node&#39;s next node, is the first node.</div> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,7] <strong>Output:</strong> [[1,5],[7]] <strong>Explanation:</strong> The initial list has 3 nodes so the first half would be the first 2 elements since ceil(3 / 2) = 2 and the rest which is 1 node is in the second half. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,1,5] <strong>Output:</strong> [[2,6],[1,5]] <strong>Explanation:</strong> The initial list has 4 nodes so the first half would be the first 2 elements since ceil(4 / 2) = 2 and the rest which is 2 nodes are in the second half. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in <code>list</code>&nbsp;is in the range <code>[2, 10<sup>5</sup>]</code></li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><font face="monospace"><code>LastNode.next = FirstNode</code></font> where <code>LastNode</code> is the last node of the list and <code>FirstNode</code> is the first one</li> </ul>
Linked List; Two Pointers
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode[] splitCircularLinkedList(ListNode list) { ListNode a = list, b = list; while (b.next != list && b.next.next != list) { a = a.next; b = b.next.next; } if (b.next != list) { b = b.next; } ListNode list2 = a.next; b.next = list2; a.next = list; return new ListNode[] {list, list2}; } }
2,674
Split a Circular Linked List
Medium
<p>Given a <strong>circular linked list</strong> <code>list</code> of positive integers, your task is to split it into 2 <strong>circular linked lists</strong> so that the first one contains the <strong>first half</strong> of the nodes in <code>list</code> (exactly <code>ceil(list.length / 2)</code> nodes) in the same order they appeared in <code>list</code>, and the second one contains <strong>the rest</strong> of the nodes in <code>list</code> in the same order they appeared in <code>list</code>.</p> <p>Return <em>an array answer of length 2 in which the first element is a <strong>circular linked list</strong> representing the <strong>first half</strong> and the second element is a <strong>circular linked list</strong> representing the <strong>second half</strong>.</em></p> <div>A <strong>circular linked list</strong> is a normal linked list with the only difference being that the last node&#39;s next node, is the first node.</div> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,7] <strong>Output:</strong> [[1,5],[7]] <strong>Explanation:</strong> The initial list has 3 nodes so the first half would be the first 2 elements since ceil(3 / 2) = 2 and the rest which is 1 node is in the second half. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,1,5] <strong>Output:</strong> [[2,6],[1,5]] <strong>Explanation:</strong> The initial list has 4 nodes so the first half would be the first 2 elements since ceil(4 / 2) = 2 and the rest which is 2 nodes are in the second half. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in <code>list</code>&nbsp;is in the range <code>[2, 10<sup>5</sup>]</code></li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><font face="monospace"><code>LastNode.next = FirstNode</code></font> where <code>LastNode</code> is the last node of the list and <code>FirstNode</code> is the first one</li> </ul>
Linked List; Two Pointers
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def splitCircularLinkedList( self, list: Optional[ListNode] ) -> List[Optional[ListNode]]: a = b = list while b.next != list and b.next.next != list: a = a.next b = b.next.next if b.next != list: b = b.next list2 = a.next b.next = list2 a.next = list return [list, list2]
2,674
Split a Circular Linked List
Medium
<p>Given a <strong>circular linked list</strong> <code>list</code> of positive integers, your task is to split it into 2 <strong>circular linked lists</strong> so that the first one contains the <strong>first half</strong> of the nodes in <code>list</code> (exactly <code>ceil(list.length / 2)</code> nodes) in the same order they appeared in <code>list</code>, and the second one contains <strong>the rest</strong> of the nodes in <code>list</code> in the same order they appeared in <code>list</code>.</p> <p>Return <em>an array answer of length 2 in which the first element is a <strong>circular linked list</strong> representing the <strong>first half</strong> and the second element is a <strong>circular linked list</strong> representing the <strong>second half</strong>.</em></p> <div>A <strong>circular linked list</strong> is a normal linked list with the only difference being that the last node&#39;s next node, is the first node.</div> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,7] <strong>Output:</strong> [[1,5],[7]] <strong>Explanation:</strong> The initial list has 3 nodes so the first half would be the first 2 elements since ceil(3 / 2) = 2 and the rest which is 1 node is in the second half. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,6,1,5] <strong>Output:</strong> [[2,6],[1,5]] <strong>Explanation:</strong> The initial list has 4 nodes so the first half would be the first 2 elements since ceil(4 / 2) = 2 and the rest which is 2 nodes are in the second half. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in <code>list</code>&nbsp;is in the range <code>[2, 10<sup>5</sup>]</code></li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><font face="monospace"><code>LastNode.next = FirstNode</code></font> where <code>LastNode</code> is the last node of the list and <code>FirstNode</code> is the first one</li> </ul>
Linked List; Two Pointers
TypeScript
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function splitCircularLinkedList(list: ListNode | null): Array<ListNode | null> { let a = list; let b = list; while (b.next !== list && b.next.next !== list) { a = a.next; b = b.next.next; } if (b.next !== list) { b = b.next; } const list2 = a.next; b.next = list2; a.next = list; return [list, list2]; }
2,675
Array of Objects to Matrix
Hard
<p>Write a function that converts an array of objects&nbsp;<code>arr</code> into a matrix <code>m</code>.</p> <p><code>arr</code>&nbsp;is an array of objects or arrays. Each item in the array can be deeply nested with child arrays and child objects. It can also contain numbers, strings, booleans, and&nbsp;null values.</p> <p>The first row <code>m</code>&nbsp;should be the column names. If there is no nesting, the column names are the unique keys within the objects. If there is nesting, the column names&nbsp;are the respective paths in the object separated by <code>&quot;.&quot;</code>.</p> <p>Each of the remaining rows corresponds to an object in&nbsp;<code>arr</code>. Each value in the matrix corresponds to a value in an object. If a given object doesn&#39;t contain a value for a given column, the cell should contain an empty string&nbsp;<code>&quot;&quot;</code>.</p> <p>The columns in the matrix should be in <strong>lexographically ascending</strong> order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [ &nbsp; {&quot;b&quot;: 1, &quot;a&quot;: 2}, &nbsp; {&quot;b&quot;: 3, &quot;a&quot;: 4} ] <strong>Output:</strong> [ &nbsp; [&quot;a&quot;, &quot;b&quot;], &nbsp; [2, 1], &nbsp; [4, 3] ] <strong>Explanation:</strong> There are two unique column names in the two objects: &quot;a&quot; and &quot;b&quot;. &quot;a&quot; corresponds with [2, 4]. &quot;b&quot; coresponds with [1, 3]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [ &nbsp; {&quot;a&quot;: 1, &quot;b&quot;: 2}, &nbsp; {&quot;c&quot;: 3, &quot;d&quot;: 4}, &nbsp; {} ] <strong>Output:</strong> [ &nbsp; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;], &nbsp; [1, 2, &quot;&quot;, &quot;&quot;], &nbsp; [&quot;&quot;, &quot;&quot;, 3, 4], &nbsp; [&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;] ] <strong>Explanation:</strong> There are 4 unique column names: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;. The first object has values associated with &quot;a&quot; and &quot;b&quot;. The second object has values associated with &quot;c&quot; and &quot;d&quot;. The third object has no keys, so it is just a row of empty strings. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> arr = [ &nbsp; {&quot;a&quot;: {&quot;b&quot;: 1, &quot;c&quot;: 2}}, &nbsp; {&quot;a&quot;: {&quot;b&quot;: 3, &quot;d&quot;: 4}} ] <strong>Output:</strong> [ &nbsp; [&quot;a.b&quot;, &quot;a.c&quot;, &quot;a.d&quot;], &nbsp; [1, 2, &quot;&quot;], &nbsp; [3, &quot;&quot;, 4] ] <strong>Explanation:</strong> In this example, the objects are nested. The keys represent the full path to each value separated by periods. There are three paths: &quot;a.b&quot;, &quot;a.c&quot;, &quot;a.d&quot;. </pre> <p><strong class="example">Example 4:</strong></p> <pre> <strong>Input:</strong> arr = [ &nbsp; [{&quot;a&quot;: null}], &nbsp; [{&quot;b&quot;: true}], &nbsp; [{&quot;c&quot;: &quot;x&quot;}] ] <strong>Output:</strong> [ &nbsp; [&quot;0.a&quot;, &quot;0.b&quot;, &quot;0.c&quot;], &nbsp; [null, &quot;&quot;, &quot;&quot;], &nbsp; [&quot;&quot;, true, &quot;&quot;], &nbsp; [&quot;&quot;, &quot;&quot;, &quot;x&quot;] ] <strong>Explanation:</strong> Arrays are also considered objects with their keys being their indices. Each array has one element so the keys are &quot;0.a&quot;, &quot;0.b&quot;, and &quot;0.c&quot;. </pre> <p><strong class="example">Example 5:</strong></p> <pre> <strong>Input:</strong> arr = [ {}, &nbsp; {}, &nbsp; {}, ] <strong>Output:</strong> [ &nbsp; [], &nbsp; [], &nbsp; [], &nbsp; [] ] <strong>Explanation:</strong> There are no keys so every row is an empty array.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>arr</code> is a valid JSON array</li> <li><code>1 &lt;= arr.length &lt;= 1000</code></li> <li><code>unique keys &lt;= 1000</code></li> </ul>
JavaScript
TypeScript
function jsonToMatrix(arr: any[]): (string | number | boolean | null)[] { const dfs = (key: string, obj: any) => { if ( typeof obj === 'number' || typeof obj === 'string' || typeof obj === 'boolean' || obj === null ) { return { [key]: obj }; } const res: any[] = []; for (const [k, v] of Object.entries(obj)) { const newKey = key ? `${key}.${k}` : `${k}`; res.push(dfs(newKey, v)); } return res.flat(); }; const kv = arr.map(obj => dfs('', obj)); const keys = [ ...new Set( kv .flat() .map(obj => Object.keys(obj)) .flat(), ), ].sort(); const ans: any[] = [keys]; for (const row of kv) { const newRow: any[] = []; for (const key of keys) { const v = row.find(r => r.hasOwnProperty(key))?.[key]; newRow.push(v === undefined ? '' : v); } ans.push(newRow); } return ans; }
2,676
Throttle
Medium
<p>Given a function <code>fn</code> and&nbsp;a time in milliseconds <code>t</code>, return&nbsp;a <strong>throttled</strong> version of that function.</p> <p>A <strong>throttled</strong> function is first called without delay and then, for a time interval of <code>t</code> milliseconds, can&#39;t be executed but should store the latest function arguments provided to call <code>fn</code> with them after the end of the delay.</p> <p>For instance, <code>t = 50ms</code>, and the function was called at <code>30ms</code>, <code>40ms</code>, and <code>60ms</code>.</p> <p>At <code>30ms</code>, without delay, the&nbsp;<strong>throttled</strong> function <code>fn</code> should be called with the arguments, and calling the <strong>throttled</strong> function <code>fn</code> should be blocked for the following <code>t</code> milliseconds.</p> <p>At <code>40ms</code>, the function should just save arguments.</p> <p>At <code>60ms</code>, arguments should overwrite currently stored arguments from the second call because the second and third calls are made before <code>80ms</code>. Once the delay has passed, the <strong>throttled</strong> function <code>fn</code> should be called with the latest arguments provided during the delay period, and it should also create another delay period of <code>80ms + t</code>.</p> <p><img alt="Throttle Diagram" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/2600-2699/2676.Throttle/images/screen-shot-2023-04-08-at-120313-pm.png" style="width: 1156px; height: 372px;" />The above diagram&nbsp;shows how throttle&nbsp;will transform&nbsp;events. Each rectangle represents 100ms and the throttle&nbsp;time is 400ms. Each color represents a different set of inputs.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> t = 100, calls = [ {&quot;t&quot;:20,&quot;inputs&quot;:[1]} ] <strong>Output:</strong> [{&quot;t&quot;:20,&quot;inputs&quot;:[1]}] <strong>Explanation:</strong> The 1st call is always called without delay </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> t = 50, calls = [ {&quot;t&quot;:50,&quot;inputs&quot;:[1]}, {&quot;t&quot;:75,&quot;inputs&quot;:[2]} ] <strong>Output:</strong> [{&quot;t&quot;:50,&quot;inputs&quot;:[1]},{&quot;t&quot;:100,&quot;inputs&quot;:[2]}] <strong>Explanation:</strong> The 1st is called a function with arguments (1) without delay. The 2nd is called at 75ms, within the delay period because 50ms + 50ms = 100ms, so the next call can be reached at 100ms. Therefore, we save arguments from the 2nd call to use them at the callback of the 1st call. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> t = 70, calls = [ {&quot;t&quot;:50,&quot;inputs&quot;:[1]}, {&quot;t&quot;:75,&quot;inputs&quot;:[2]}, {&quot;t&quot;:90,&quot;inputs&quot;:[8]}, {&quot;t&quot;: 140, &quot;inputs&quot;:[5,7]}, {&quot;t&quot;: 300, &quot;inputs&quot;: [9,4]} ] <strong>Output:</strong> [{&quot;t&quot;:50,&quot;inputs&quot;:[1]},{&quot;t&quot;:120,&quot;inputs&quot;:[8]},{&quot;t&quot;:190,&quot;inputs&quot;:[5,7]},{&quot;t&quot;:300,&quot;inputs&quot;:[9,4]}] <strong>Explanation:</strong> The 1st is called a function with arguments (1) without delay. The 2nd is called at 75ms within the delay period because 50ms + 70ms = 120ms, so it should only save arguments.&nbsp; The 3rd is also called within the delay period, and because we need just the latest function arguments, we overwrite previous ones. After the delay period, we do a callback at 120ms with saved arguments. That callback makes another delay period of 120ms + 70ms = 190ms so that the next function can be called at 190ms. The 4th is called at 140ms in the delay period, so it should be called as a callback at 190ms. That will create another delay period of 190ms + 70ms = 260ms. The 5th is called at 300ms, but it is after 260ms, so it should be called immediately and should create another delay period of 300ms + 70ms = 370ms.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= t &lt;= 1000</code></li> <li><code>1 &lt;= calls.length &lt;= 10</code></li> <li><code>0 &lt;= calls[i].t &lt;= 1000</code></li> <li><code>0 &lt;= calls[i].inputs[j], calls[i].inputs.length &lt;= 10</code></li> </ul>
JavaScript
TypeScript
type F = (...args: any[]) => void; const throttle = (fn: F, t: number): F => { let pending = false; let nextArgs; const wrapper = (...args) => { nextArgs = args; if (!pending) { fn(...args); pending = true; nextArgs = undefined; setTimeout(() => { pending = false; if (nextArgs) wrapper(...nextArgs); }, t); } }; return wrapper; }; /** * const throttled = throttle(console.log, 100); * throttled("log"); // logged immediately. * throttled("log"); // logged at t=100ms. */
2,677
Chunk Array
Easy
<p>Given an array <code>arr</code> and a chunk size <code>size</code>, return a <strong>chunked</strong> array.</p> <p>A <strong>chunked</strong> array contains the original elements in <code>arr</code>, but consists of subarrays each of length <code>size</code>. The length of the last subarray may be less than <code>size</code> if <code>arr.length</code> is not evenly divisible by <code>size</code>.</p> <p>Please solve it without using lodash&#39;s <code>_.chunk</code> function.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [1,2,3,4,5], size = 1 <strong>Output:</strong> [[1],[2],[3],[4],[5]] <strong>Explanation:</strong> The arr has been split into subarrays each with 1 element. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [1,9,6,3,2], size = 3 <strong>Output:</strong> [[1,9,6],[3,2]] <strong>Explanation:</strong> The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> arr = [8,5,3,2,6], size = 6 <strong>Output:</strong> [[8,5,3,2,6]] <strong>Explanation:</strong> Size is greater than arr.length thus all elements are in the first subarray. </pre> <p><strong class="example">Example 4:</strong></p> <pre> <strong>Input:</strong> arr = [], size = 1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no elements to be chunked so an empty array is returned.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>arr</code> is a string representing the array.</li> <li><code>2 &lt;= arr.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= size &lt;= arr.length + 1</code></li> </ul>
JavaScript
JavaScript
/** * @param {Array} arr * @param {number} size * @return {Array[]} */ var chunk = function (arr, size) { const ans = []; for (let i = 0, n = arr.length; i < n; i += size) { ans.push(arr.slice(i, i + size)); } return ans; };
2,677
Chunk Array
Easy
<p>Given an array <code>arr</code> and a chunk size <code>size</code>, return a <strong>chunked</strong> array.</p> <p>A <strong>chunked</strong> array contains the original elements in <code>arr</code>, but consists of subarrays each of length <code>size</code>. The length of the last subarray may be less than <code>size</code> if <code>arr.length</code> is not evenly divisible by <code>size</code>.</p> <p>Please solve it without using lodash&#39;s <code>_.chunk</code> function.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> arr = [1,2,3,4,5], size = 1 <strong>Output:</strong> [[1],[2],[3],[4],[5]] <strong>Explanation:</strong> The arr has been split into subarrays each with 1 element. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> arr = [1,9,6,3,2], size = 3 <strong>Output:</strong> [[1,9,6],[3,2]] <strong>Explanation:</strong> The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> arr = [8,5,3,2,6], size = 6 <strong>Output:</strong> [[8,5,3,2,6]] <strong>Explanation:</strong> Size is greater than arr.length thus all elements are in the first subarray. </pre> <p><strong class="example">Example 4:</strong></p> <pre> <strong>Input:</strong> arr = [], size = 1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no elements to be chunked so an empty array is returned.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>arr</code> is a string representing the array.</li> <li><code>2 &lt;= arr.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= size &lt;= arr.length + 1</code></li> </ul>
JavaScript
TypeScript
function chunk(arr: any[], size: number): any[][] { const ans: any[][] = []; for (let i = 0, n = arr.length; i < n; i += size) { ans.push(arr.slice(i, i + size)); } return ans; }
2,678
Number of Senior Citizens
Easy
<p>You are given a <strong>0-indexed</strong> array of strings <code>details</code>. Each element of <code>details</code> provides information about a given passenger compressed into a string of length <code>15</code>. The system is such that:</p> <ul> <li>The first ten characters consist of the phone number of passengers.</li> <li>The next character denotes the gender of the person.</li> <li>The following two characters are used to indicate the age of the person.</li> <li>The last two characters determine the seat allotted to that person.</li> </ul> <p>Return <em>the number of passengers who are <strong>strictly </strong><strong>more than 60 years old</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> details = [&quot;7868190130M7522&quot;,&quot;5303914400F9211&quot;,&quot;9273338290F4010&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> details = [&quot;1313579440F2036&quot;,&quot;2921522980M5644&quot;] <strong>Output:</strong> 0 <strong>Explanation:</strong> None of the passengers are older than 60. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= details.length &lt;= 100</code></li> <li><code>details[i].length == 15</code></li> <li><code>details[i] consists of digits from &#39;0&#39; to &#39;9&#39;.</code></li> <li><code>details[i][10] is either &#39;M&#39; or &#39;F&#39; or &#39;O&#39;.</code></li> <li>The phone numbers and seat numbers of the passengers are distinct.</li> </ul>
Array; String
C++
class Solution { public: int countSeniors(vector<string>& details) { int ans = 0; for (auto& x : details) { int age = stoi(x.substr(11, 2)); ans += age > 60; } return ans; } };
2,678
Number of Senior Citizens
Easy
<p>You are given a <strong>0-indexed</strong> array of strings <code>details</code>. Each element of <code>details</code> provides information about a given passenger compressed into a string of length <code>15</code>. The system is such that:</p> <ul> <li>The first ten characters consist of the phone number of passengers.</li> <li>The next character denotes the gender of the person.</li> <li>The following two characters are used to indicate the age of the person.</li> <li>The last two characters determine the seat allotted to that person.</li> </ul> <p>Return <em>the number of passengers who are <strong>strictly </strong><strong>more than 60 years old</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> details = [&quot;7868190130M7522&quot;,&quot;5303914400F9211&quot;,&quot;9273338290F4010&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> details = [&quot;1313579440F2036&quot;,&quot;2921522980M5644&quot;] <strong>Output:</strong> 0 <strong>Explanation:</strong> None of the passengers are older than 60. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= details.length &lt;= 100</code></li> <li><code>details[i].length == 15</code></li> <li><code>details[i] consists of digits from &#39;0&#39; to &#39;9&#39;.</code></li> <li><code>details[i][10] is either &#39;M&#39; or &#39;F&#39; or &#39;O&#39;.</code></li> <li>The phone numbers and seat numbers of the passengers are distinct.</li> </ul>
Array; String
Go
func countSeniors(details []string) (ans int) { for _, x := range details { age, _ := strconv.Atoi(x[11:13]) if age > 60 { ans++ } } return }
2,678
Number of Senior Citizens
Easy
<p>You are given a <strong>0-indexed</strong> array of strings <code>details</code>. Each element of <code>details</code> provides information about a given passenger compressed into a string of length <code>15</code>. The system is such that:</p> <ul> <li>The first ten characters consist of the phone number of passengers.</li> <li>The next character denotes the gender of the person.</li> <li>The following two characters are used to indicate the age of the person.</li> <li>The last two characters determine the seat allotted to that person.</li> </ul> <p>Return <em>the number of passengers who are <strong>strictly </strong><strong>more than 60 years old</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> details = [&quot;7868190130M7522&quot;,&quot;5303914400F9211&quot;,&quot;9273338290F4010&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> details = [&quot;1313579440F2036&quot;,&quot;2921522980M5644&quot;] <strong>Output:</strong> 0 <strong>Explanation:</strong> None of the passengers are older than 60. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= details.length &lt;= 100</code></li> <li><code>details[i].length == 15</code></li> <li><code>details[i] consists of digits from &#39;0&#39; to &#39;9&#39;.</code></li> <li><code>details[i][10] is either &#39;M&#39; or &#39;F&#39; or &#39;O&#39;.</code></li> <li>The phone numbers and seat numbers of the passengers are distinct.</li> </ul>
Array; String
Java
class Solution { public int countSeniors(String[] details) { int ans = 0; for (var x : details) { int age = Integer.parseInt(x.substring(11, 13)); if (age > 60) { ++ans; } } return ans; } }
2,678
Number of Senior Citizens
Easy
<p>You are given a <strong>0-indexed</strong> array of strings <code>details</code>. Each element of <code>details</code> provides information about a given passenger compressed into a string of length <code>15</code>. The system is such that:</p> <ul> <li>The first ten characters consist of the phone number of passengers.</li> <li>The next character denotes the gender of the person.</li> <li>The following two characters are used to indicate the age of the person.</li> <li>The last two characters determine the seat allotted to that person.</li> </ul> <p>Return <em>the number of passengers who are <strong>strictly </strong><strong>more than 60 years old</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> details = [&quot;7868190130M7522&quot;,&quot;5303914400F9211&quot;,&quot;9273338290F4010&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> details = [&quot;1313579440F2036&quot;,&quot;2921522980M5644&quot;] <strong>Output:</strong> 0 <strong>Explanation:</strong> None of the passengers are older than 60. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= details.length &lt;= 100</code></li> <li><code>details[i].length == 15</code></li> <li><code>details[i] consists of digits from &#39;0&#39; to &#39;9&#39;.</code></li> <li><code>details[i][10] is either &#39;M&#39; or &#39;F&#39; or &#39;O&#39;.</code></li> <li>The phone numbers and seat numbers of the passengers are distinct.</li> </ul>
Array; String
Python
class Solution: def countSeniors(self, details: List[str]) -> int: return sum(int(x[11:13]) > 60 for x in details)
2,678
Number of Senior Citizens
Easy
<p>You are given a <strong>0-indexed</strong> array of strings <code>details</code>. Each element of <code>details</code> provides information about a given passenger compressed into a string of length <code>15</code>. The system is such that:</p> <ul> <li>The first ten characters consist of the phone number of passengers.</li> <li>The next character denotes the gender of the person.</li> <li>The following two characters are used to indicate the age of the person.</li> <li>The last two characters determine the seat allotted to that person.</li> </ul> <p>Return <em>the number of passengers who are <strong>strictly </strong><strong>more than 60 years old</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> details = [&quot;7868190130M7522&quot;,&quot;5303914400F9211&quot;,&quot;9273338290F4010&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> details = [&quot;1313579440F2036&quot;,&quot;2921522980M5644&quot;] <strong>Output:</strong> 0 <strong>Explanation:</strong> None of the passengers are older than 60. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= details.length &lt;= 100</code></li> <li><code>details[i].length == 15</code></li> <li><code>details[i] consists of digits from &#39;0&#39; to &#39;9&#39;.</code></li> <li><code>details[i][10] is either &#39;M&#39; or &#39;F&#39; or &#39;O&#39;.</code></li> <li>The phone numbers and seat numbers of the passengers are distinct.</li> </ul>
Array; String
Rust
impl Solution { pub fn count_seniors(details: Vec<String>) -> i32 { details .iter() .filter_map(|s| s[11..13].parse::<i32>().ok()) .filter(|&age| age > 60) .count() as i32 } }
2,678
Number of Senior Citizens
Easy
<p>You are given a <strong>0-indexed</strong> array of strings <code>details</code>. Each element of <code>details</code> provides information about a given passenger compressed into a string of length <code>15</code>. The system is such that:</p> <ul> <li>The first ten characters consist of the phone number of passengers.</li> <li>The next character denotes the gender of the person.</li> <li>The following two characters are used to indicate the age of the person.</li> <li>The last two characters determine the seat allotted to that person.</li> </ul> <p>Return <em>the number of passengers who are <strong>strictly </strong><strong>more than 60 years old</strong>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> details = [&quot;7868190130M7522&quot;,&quot;5303914400F9211&quot;,&quot;9273338290F4010&quot;] <strong>Output:</strong> 2 <strong>Explanation:</strong> The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> details = [&quot;1313579440F2036&quot;,&quot;2921522980M5644&quot;] <strong>Output:</strong> 0 <strong>Explanation:</strong> None of the passengers are older than 60. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= details.length &lt;= 100</code></li> <li><code>details[i].length == 15</code></li> <li><code>details[i] consists of digits from &#39;0&#39; to &#39;9&#39;.</code></li> <li><code>details[i][10] is either &#39;M&#39; or &#39;F&#39; or &#39;O&#39;.</code></li> <li>The phone numbers and seat numbers of the passengers are distinct.</li> </ul>
Array; String
TypeScript
function countSeniors(details: string[]): number { return details.filter(x => +x.slice(11, 13) > 60).length; }
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)
C++
class Solution { public: int matrixSum(vector<vector<int>>& nums) { for (auto& row : nums) { sort(row.begin(), row.end()); } int ans = 0; for (int j = 0; j < nums[0].size(); ++j) { int mx = 0; for (auto& row : nums) { mx = max(mx, row[j]); } ans += mx; } return ans; } };
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)
Go
func matrixSum(nums [][]int) (ans int) { for _, row := range nums { sort.Ints(row) } for i := 0; i < len(nums[0]); i++ { mx := 0 for _, row := range nums { mx = max(mx, row[i]) } ans += mx } return }
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)
Java
class Solution { public int matrixSum(int[][] nums) { for (var row : nums) { Arrays.sort(row); } int ans = 0; for (int j = 0; j < nums[0].length; ++j) { int mx = 0; for (var row : nums) { mx = Math.max(mx, row[j]); } ans += mx; } return ans; } }