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
439
Ternary Expression Parser
Medium
<p>Given a string <code>expression</code> representing arbitrarily nested ternary expressions, evaluate the expression, and return <em>the result of it</em>.</p> <p>You can always assume that the given expression is valid and only contains digits, <code>&#39;?&#39;</code>, <code>&#39;:&#39;</code>, <code>&#39;T&#39;</code>, and <code>&#39;F&#39;</code> where <code>&#39;T&#39;</code> is true and <code>&#39;F&#39;</code> is false. All the numbers in the expression are <strong>one-digit</strong> numbers (i.e., in the range <code>[0, 9]</code>).</p> <p>The conditional expressions group right-to-left (as usual in most languages), and the result of the expression will always evaluate to either a digit, <code>&#39;T&#39;</code> or <code>&#39;F&#39;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> expression = &quot;T?2:3&quot; <strong>Output:</strong> &quot;2&quot; <strong>Explanation:</strong> If true, then result is 2; otherwise result is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> expression = &quot;F?1:T?4:5&quot; <strong>Output:</strong> &quot;4&quot; <strong>Explanation:</strong> The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: &quot;(F ? 1 : (T ? 4 : 5))&quot; --&gt; &quot;(F ? 1 : 4)&quot; --&gt; &quot;4&quot; or &quot;(F ? 1 : (T ? 4 : 5))&quot; --&gt; &quot;(T ? 4 : 5)&quot; --&gt; &quot;4&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> expression = &quot;T?T?F:5:3&quot; <strong>Output:</strong> &quot;F&quot; <strong>Explanation:</strong> The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as: &quot;(T ? (T ? F : 5) : 3)&quot; --&gt; &quot;(T ? F : 3)&quot; --&gt; &quot;F&quot; &quot;(T ? (T ? F : 5) : 3)&quot; --&gt; &quot;(T ? F : 5)&quot; --&gt; &quot;F&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>5 &lt;= expression.length &lt;= 10<sup>4</sup></code></li> <li><code>expression</code> consists of digits, <code>&#39;T&#39;</code>, <code>&#39;F&#39;</code>, <code>&#39;?&#39;</code>, and <code>&#39;:&#39;</code>.</li> <li>It is <strong>guaranteed</strong> that <code>expression</code> is a valid ternary expression and that each number is a <strong>one-digit number</strong>.</li> </ul>
Stack; Recursion; String
Python
class Solution: def parseTernary(self, expression: str) -> str: stk = [] cond = False for c in expression[::-1]: if c == ':': continue if c == '?': cond = True else: if cond: if c == 'T': x = stk.pop() stk.pop() stk.append(x) else: stk.pop() cond = False else: stk.append(c) return stk[0]
440
K-th Smallest in Lexicographical Order
Hard
<p>Given two integers <code>n</code> and <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>lexicographically smallest integer in the range</em> <code>[1, n]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 13, k = 2 <strong>Output:</strong> 10 <strong>Explanation:</strong> The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, k = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Trie
C++
class Solution { public: int n; int findKthNumber(int n, int k) { this->n = n; --k; long long curr = 1; while (k) { int cnt = count(curr); if (k >= cnt) { k -= cnt; ++curr; } else { --k; curr *= 10; } } return (int) curr; } int count(long long curr) { long long next = curr + 1; int cnt = 0; while (curr <= n) { cnt += min(n - curr + 1, next - curr); next *= 10; curr *= 10; } return cnt; } };
440
K-th Smallest in Lexicographical Order
Hard
<p>Given two integers <code>n</code> and <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>lexicographically smallest integer in the range</em> <code>[1, n]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 13, k = 2 <strong>Output:</strong> 10 <strong>Explanation:</strong> The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, k = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Trie
Go
func findKthNumber(n int, k int) int { count := func(curr int) int { next := curr + 1 cnt := 0 for curr <= n { cnt += min(n-curr+1, next-curr) next *= 10 curr *= 10 } return cnt } curr := 1 k-- for k > 0 { cnt := count(curr) if k >= cnt { k -= cnt curr++ } else { k-- curr *= 10 } } return curr }
440
K-th Smallest in Lexicographical Order
Hard
<p>Given two integers <code>n</code> and <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>lexicographically smallest integer in the range</em> <code>[1, n]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 13, k = 2 <strong>Output:</strong> 10 <strong>Explanation:</strong> The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, k = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Trie
Java
class Solution { private int n; public int findKthNumber(int n, int k) { this.n = n; long curr = 1; --k; while (k > 0) { int cnt = count(curr); if (k >= cnt) { k -= cnt; ++curr; } else { --k; curr *= 10; } } return (int) curr; } public int count(long curr) { long next = curr + 1; long cnt = 0; while (curr <= n) { cnt += Math.min(n - curr + 1, next - curr); next *= 10; curr *= 10; } return (int) cnt; } }
440
K-th Smallest in Lexicographical Order
Hard
<p>Given two integers <code>n</code> and <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>lexicographically smallest integer in the range</em> <code>[1, n]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 13, k = 2 <strong>Output:</strong> 10 <strong>Explanation:</strong> The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, k = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Trie
Python
class Solution: def findKthNumber(self, n: int, k: int) -> int: def count(curr): next, cnt = curr + 1, 0 while curr <= n: cnt += min(n - curr + 1, next - curr) next, curr = next * 10, curr * 10 return cnt curr = 1 k -= 1 while k: cnt = count(curr) if k >= cnt: k -= cnt curr += 1 else: k -= 1 curr *= 10 return curr
440
K-th Smallest in Lexicographical Order
Hard
<p>Given two integers <code>n</code> and <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>lexicographically smallest integer in the range</em> <code>[1, n]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 13, k = 2 <strong>Output:</strong> 10 <strong>Explanation:</strong> The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, k = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Trie
Rust
impl Solution { pub fn find_kth_number(n: i32, k: i32) -> i32 { fn count(mut curr: i64, n: i32) -> i32 { let mut next = curr + 1; let mut total = 0; let n = n as i64; while curr <= n { total += std::cmp::min(n - curr + 1, next - curr); curr *= 10; next *= 10; } total as i32 } let mut curr = 1; let mut k = k - 1; while k > 0 { let cnt = count(curr as i64, n); if k >= cnt { k -= cnt; curr += 1; } else { k -= 1; curr *= 10; } } curr } }
440
K-th Smallest in Lexicographical Order
Hard
<p>Given two integers <code>n</code> and <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>lexicographically smallest integer in the range</em> <code>[1, n]</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 13, k = 2 <strong>Output:</strong> 10 <strong>Explanation:</strong> The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, k = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Trie
TypeScript
function findKthNumber(n: number, k: number): number { function count(curr: number): number { let next = curr + 1; let cnt = 0; while (curr <= n) { cnt += Math.min(n - curr + 1, next - curr); curr *= 10; next *= 10; } return cnt; } let curr = 1; k--; while (k > 0) { const cnt = count(curr); if (k >= cnt) { k -= cnt; curr += 1; } else { k -= 1; curr *= 10; } } return curr; }
441
Arranging Coins
Easy
<p>You have <code>n</code> coins and you want to build a staircase with these coins. The staircase consists of <code>k</code> rows where the <code>i<sup>th</sup></code> row has exactly <code>i</code> coins. The last row of the staircase <strong>may be</strong> incomplete.</p> <p>Given the integer <code>n</code>, return <em>the number of <strong>complete rows</strong> of the staircase you will build</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0441.Arranging%20Coins/images/arrangecoins1-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because the 3<sup>rd</sup> row is incomplete, we return 2. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0441.Arranging%20Coins/images/arrangecoins2-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> n = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> Because the 4<sup>th</sup> row is incomplete, we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
C++
using LL = long; class Solution { public: int arrangeCoins(int n) { LL left = 1, right = n; while (left < right) { LL mid = left + right + 1 >> 1; LL s = (1 + mid) * mid >> 1; if (n < s) right = mid - 1; else left = mid; } return left; } };
441
Arranging Coins
Easy
<p>You have <code>n</code> coins and you want to build a staircase with these coins. The staircase consists of <code>k</code> rows where the <code>i<sup>th</sup></code> row has exactly <code>i</code> coins. The last row of the staircase <strong>may be</strong> incomplete.</p> <p>Given the integer <code>n</code>, return <em>the number of <strong>complete rows</strong> of the staircase you will build</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0441.Arranging%20Coins/images/arrangecoins1-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because the 3<sup>rd</sup> row is incomplete, we return 2. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0441.Arranging%20Coins/images/arrangecoins2-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> n = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> Because the 4<sup>th</sup> row is incomplete, we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
Go
func arrangeCoins(n int) int { left, right := 1, n for left < right { mid := (left + right + 1) >> 1 if (1+mid)*mid/2 <= n { left = mid } else { right = mid - 1 } } return left }
441
Arranging Coins
Easy
<p>You have <code>n</code> coins and you want to build a staircase with these coins. The staircase consists of <code>k</code> rows where the <code>i<sup>th</sup></code> row has exactly <code>i</code> coins. The last row of the staircase <strong>may be</strong> incomplete.</p> <p>Given the integer <code>n</code>, return <em>the number of <strong>complete rows</strong> of the staircase you will build</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0441.Arranging%20Coins/images/arrangecoins1-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because the 3<sup>rd</sup> row is incomplete, we return 2. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0441.Arranging%20Coins/images/arrangecoins2-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> n = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> Because the 4<sup>th</sup> row is incomplete, we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
Java
class Solution { public int arrangeCoins(int n) { return (int) (Math.sqrt(2) * Math.sqrt(n + 0.125) - 0.5); } }
441
Arranging Coins
Easy
<p>You have <code>n</code> coins and you want to build a staircase with these coins. The staircase consists of <code>k</code> rows where the <code>i<sup>th</sup></code> row has exactly <code>i</code> coins. The last row of the staircase <strong>may be</strong> incomplete.</p> <p>Given the integer <code>n</code>, return <em>the number of <strong>complete rows</strong> of the staircase you will build</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0441.Arranging%20Coins/images/arrangecoins1-grid.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 2 <strong>Explanation:</strong> Because the 3<sup>rd</sup> row is incomplete, we return 2. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0441.Arranging%20Coins/images/arrangecoins2-grid.jpg" style="width: 333px; height: 333px;" /> <pre> <strong>Input:</strong> n = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> Because the 4<sup>th</sup> row is incomplete, we return 3. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; Binary Search
Python
class Solution: def arrangeCoins(self, n: int) -> int: return int(math.sqrt(2) * math.sqrt(n + 0.125) - 0.5)
442
Find All Duplicates in an Array
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> where all the integers of <code>nums</code> are in the range <code>[1, n]</code> and each integer appears <strong>at most</strong> <strong>twice</strong>, return <em>an array of all the integers that appears <strong>twice</strong></em>.</p> <p>You must write an algorithm that runs in <code>O(n)</code> time and uses only <em>constant</em> auxiliary space, excluding the space needed to store the output</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,3,2,7,8,2,3,1] <strong>Output:</strong> [2,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> [1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> <li>Each element in <code>nums</code> appears <strong>once</strong> or <strong>twice</strong>.</li> </ul>
Array; Hash Table
C++
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; ++i) { while (nums[i] != nums[nums[i] - 1]) { swap(nums[i], nums[nums[i] - 1]); } } vector<int> ans; for (int i = 0; i < n; ++i) { if (nums[i] != i + 1) { ans.push_back(nums[i]); } } return ans; } };
442
Find All Duplicates in an Array
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> where all the integers of <code>nums</code> are in the range <code>[1, n]</code> and each integer appears <strong>at most</strong> <strong>twice</strong>, return <em>an array of all the integers that appears <strong>twice</strong></em>.</p> <p>You must write an algorithm that runs in <code>O(n)</code> time and uses only <em>constant</em> auxiliary space, excluding the space needed to store the output</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,3,2,7,8,2,3,1] <strong>Output:</strong> [2,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> [1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> <li>Each element in <code>nums</code> appears <strong>once</strong> or <strong>twice</strong>.</li> </ul>
Array; Hash Table
Go
func findDuplicates(nums []int) []int { for i := range nums { for nums[i] != nums[nums[i]-1] { nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i] } } var ans []int for i, v := range nums { if v != i+1 { ans = append(ans, v) } } return ans }
442
Find All Duplicates in an Array
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> where all the integers of <code>nums</code> are in the range <code>[1, n]</code> and each integer appears <strong>at most</strong> <strong>twice</strong>, return <em>an array of all the integers that appears <strong>twice</strong></em>.</p> <p>You must write an algorithm that runs in <code>O(n)</code> time and uses only <em>constant</em> auxiliary space, excluding the space needed to store the output</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,3,2,7,8,2,3,1] <strong>Output:</strong> [2,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> [1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> <li>Each element in <code>nums</code> appears <strong>once</strong> or <strong>twice</strong>.</li> </ul>
Array; Hash Table
Java
class Solution { public List<Integer> findDuplicates(int[] nums) { int n = nums.length; for (int i = 0; i < n; ++i) { while (nums[i] != nums[nums[i] - 1]) { swap(nums, i, nums[i] - 1); } } List<Integer> ans = new ArrayList<>(); for (int i = 0; i < n; ++i) { if (nums[i] != i + 1) { ans.add(nums[i]); } } return ans; } void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } }
442
Find All Duplicates in an Array
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> where all the integers of <code>nums</code> are in the range <code>[1, n]</code> and each integer appears <strong>at most</strong> <strong>twice</strong>, return <em>an array of all the integers that appears <strong>twice</strong></em>.</p> <p>You must write an algorithm that runs in <code>O(n)</code> time and uses only <em>constant</em> auxiliary space, excluding the space needed to store the output</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,3,2,7,8,2,3,1] <strong>Output:</strong> [2,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> [1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> <li>Each element in <code>nums</code> appears <strong>once</strong> or <strong>twice</strong>.</li> </ul>
Array; Hash Table
Python
class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: for i in range(len(nums)): while nums[i] != nums[nums[i] - 1]: nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] return [v for i, v in enumerate(nums) if v != i + 1]
442
Find All Duplicates in an Array
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> where all the integers of <code>nums</code> are in the range <code>[1, n]</code> and each integer appears <strong>at most</strong> <strong>twice</strong>, return <em>an array of all the integers that appears <strong>twice</strong></em>.</p> <p>You must write an algorithm that runs in <code>O(n)</code> time and uses only <em>constant</em> auxiliary space, excluding the space needed to store the output</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,3,2,7,8,2,3,1] <strong>Output:</strong> [2,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1,2] <strong>Output:</strong> [1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> <li>Each element in <code>nums</code> appears <strong>once</strong> or <strong>twice</strong>.</li> </ul>
Array; Hash Table
TypeScript
function findDuplicates(nums: number[]): number[] { for (let i = 0; i < nums.length; i++) { while (nums[i] !== nums[nums[i] - 1]) { const temp = nums[i]; nums[i] = nums[temp - 1]; nums[temp - 1] = temp; } } const ans: number[] = []; for (let i = 0; i < nums.length; i++) { if (nums[i] !== i + 1) { ans.push(nums[i]); } } return ans; }
443
String Compression
Medium
<p>Given an array of characters <code>chars</code>, compress it using the following algorithm:</p> <p>Begin with an empty string <code>s</code>. For each group of <strong>consecutive repeating characters</strong> in <code>chars</code>:</p> <ul> <li>If the group&#39;s length is <code>1</code>, append the character to <code>s</code>.</li> <li>Otherwise, append the character followed by the group&#39;s length.</li> </ul> <p>The compressed string <code>s</code> <strong>should not be returned separately</strong>, but instead, be stored <strong>in the input character array <code>chars</code></strong>. Note that group lengths that are <code>10</code> or longer will be split into multiple characters in <code>chars</code>.</p> <p>After you are done <strong>modifying the input array,</strong> return <em>the new length of the array</em>.</p> <p>You must write an algorithm that uses only constant extra space.</p> <p><strong>Note: </strong>The characters in the array beyond the returned length do not matter and should be ignored.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;,&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;] <strong>Output:</strong> Return 6, and the first 6 characters of the input array should be: [&quot;a&quot;,&quot;2&quot;,&quot;b&quot;,&quot;2&quot;,&quot;c&quot;,&quot;3&quot;] <strong>Explanation:</strong> The groups are &quot;aa&quot;, &quot;bb&quot;, and &quot;ccc&quot;. This compresses to &quot;a2b2c3&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;] <strong>Output:</strong> Return 1, and the first character of the input array should be: [&quot;a&quot;] <strong>Explanation:</strong> The only group is &quot;a&quot;, which remains uncompressed since it&#39;s a single character. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;] <strong>Output:</strong> Return 4, and the first 4 characters of the input array should be: [&quot;a&quot;,&quot;b&quot;,&quot;1&quot;,&quot;2&quot;]. <strong>Explanation:</strong> The groups are &quot;a&quot; and &quot;bbbbbbbbbbbb&quot;. This compresses to &quot;ab12&quot;.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= chars.length &lt;= 2000</code></li> <li><code>chars[i]</code> is a lowercase English letter, uppercase English letter, digit, or symbol.</li> </ul>
Two Pointers; String
C++
class Solution { public: int compress(vector<char>& chars) { int k = 0, n = chars.size(); for (int i = 0, j = i + 1; i < n;) { while (j < n && chars[j] == chars[i]) ++j; chars[k++] = chars[i]; if (j - i > 1) { for (char c : to_string(j - i)) { chars[k++] = c; } } i = j; } return k; } };
443
String Compression
Medium
<p>Given an array of characters <code>chars</code>, compress it using the following algorithm:</p> <p>Begin with an empty string <code>s</code>. For each group of <strong>consecutive repeating characters</strong> in <code>chars</code>:</p> <ul> <li>If the group&#39;s length is <code>1</code>, append the character to <code>s</code>.</li> <li>Otherwise, append the character followed by the group&#39;s length.</li> </ul> <p>The compressed string <code>s</code> <strong>should not be returned separately</strong>, but instead, be stored <strong>in the input character array <code>chars</code></strong>. Note that group lengths that are <code>10</code> or longer will be split into multiple characters in <code>chars</code>.</p> <p>After you are done <strong>modifying the input array,</strong> return <em>the new length of the array</em>.</p> <p>You must write an algorithm that uses only constant extra space.</p> <p><strong>Note: </strong>The characters in the array beyond the returned length do not matter and should be ignored.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;,&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;] <strong>Output:</strong> Return 6, and the first 6 characters of the input array should be: [&quot;a&quot;,&quot;2&quot;,&quot;b&quot;,&quot;2&quot;,&quot;c&quot;,&quot;3&quot;] <strong>Explanation:</strong> The groups are &quot;aa&quot;, &quot;bb&quot;, and &quot;ccc&quot;. This compresses to &quot;a2b2c3&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;] <strong>Output:</strong> Return 1, and the first character of the input array should be: [&quot;a&quot;] <strong>Explanation:</strong> The only group is &quot;a&quot;, which remains uncompressed since it&#39;s a single character. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;] <strong>Output:</strong> Return 4, and the first 4 characters of the input array should be: [&quot;a&quot;,&quot;b&quot;,&quot;1&quot;,&quot;2&quot;]. <strong>Explanation:</strong> The groups are &quot;a&quot; and &quot;bbbbbbbbbbbb&quot;. This compresses to &quot;ab12&quot;.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= chars.length &lt;= 2000</code></li> <li><code>chars[i]</code> is a lowercase English letter, uppercase English letter, digit, or symbol.</li> </ul>
Two Pointers; String
Go
func compress(chars []byte) int { i, k, n := 0, 0, len(chars) for i < n { j := i + 1 for j < n && chars[j] == chars[i] { j++ } chars[k] = chars[i] k++ if j-i > 1 { cnt := strconv.Itoa(j - i) for _, c := range cnt { chars[k] = byte(c) k++ } } i = j } return k }
443
String Compression
Medium
<p>Given an array of characters <code>chars</code>, compress it using the following algorithm:</p> <p>Begin with an empty string <code>s</code>. For each group of <strong>consecutive repeating characters</strong> in <code>chars</code>:</p> <ul> <li>If the group&#39;s length is <code>1</code>, append the character to <code>s</code>.</li> <li>Otherwise, append the character followed by the group&#39;s length.</li> </ul> <p>The compressed string <code>s</code> <strong>should not be returned separately</strong>, but instead, be stored <strong>in the input character array <code>chars</code></strong>. Note that group lengths that are <code>10</code> or longer will be split into multiple characters in <code>chars</code>.</p> <p>After you are done <strong>modifying the input array,</strong> return <em>the new length of the array</em>.</p> <p>You must write an algorithm that uses only constant extra space.</p> <p><strong>Note: </strong>The characters in the array beyond the returned length do not matter and should be ignored.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;,&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;] <strong>Output:</strong> Return 6, and the first 6 characters of the input array should be: [&quot;a&quot;,&quot;2&quot;,&quot;b&quot;,&quot;2&quot;,&quot;c&quot;,&quot;3&quot;] <strong>Explanation:</strong> The groups are &quot;aa&quot;, &quot;bb&quot;, and &quot;ccc&quot;. This compresses to &quot;a2b2c3&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;] <strong>Output:</strong> Return 1, and the first character of the input array should be: [&quot;a&quot;] <strong>Explanation:</strong> The only group is &quot;a&quot;, which remains uncompressed since it&#39;s a single character. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;] <strong>Output:</strong> Return 4, and the first 4 characters of the input array should be: [&quot;a&quot;,&quot;b&quot;,&quot;1&quot;,&quot;2&quot;]. <strong>Explanation:</strong> The groups are &quot;a&quot; and &quot;bbbbbbbbbbbb&quot;. This compresses to &quot;ab12&quot;.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= chars.length &lt;= 2000</code></li> <li><code>chars[i]</code> is a lowercase English letter, uppercase English letter, digit, or symbol.</li> </ul>
Two Pointers; String
Java
class Solution { public int compress(char[] chars) { int k = 0, n = chars.length; for (int i = 0, j = i + 1; i < n;) { while (j < n && chars[j] == chars[i]) { ++j; } chars[k++] = chars[i]; if (j - i > 1) { String cnt = String.valueOf(j - i); for (char c : cnt.toCharArray()) { chars[k++] = c; } } i = j; } return k; } }
443
String Compression
Medium
<p>Given an array of characters <code>chars</code>, compress it using the following algorithm:</p> <p>Begin with an empty string <code>s</code>. For each group of <strong>consecutive repeating characters</strong> in <code>chars</code>:</p> <ul> <li>If the group&#39;s length is <code>1</code>, append the character to <code>s</code>.</li> <li>Otherwise, append the character followed by the group&#39;s length.</li> </ul> <p>The compressed string <code>s</code> <strong>should not be returned separately</strong>, but instead, be stored <strong>in the input character array <code>chars</code></strong>. Note that group lengths that are <code>10</code> or longer will be split into multiple characters in <code>chars</code>.</p> <p>After you are done <strong>modifying the input array,</strong> return <em>the new length of the array</em>.</p> <p>You must write an algorithm that uses only constant extra space.</p> <p><strong>Note: </strong>The characters in the array beyond the returned length do not matter and should be ignored.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;,&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;] <strong>Output:</strong> Return 6, and the first 6 characters of the input array should be: [&quot;a&quot;,&quot;2&quot;,&quot;b&quot;,&quot;2&quot;,&quot;c&quot;,&quot;3&quot;] <strong>Explanation:</strong> The groups are &quot;aa&quot;, &quot;bb&quot;, and &quot;ccc&quot;. This compresses to &quot;a2b2c3&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;] <strong>Output:</strong> Return 1, and the first character of the input array should be: [&quot;a&quot;] <strong>Explanation:</strong> The only group is &quot;a&quot;, which remains uncompressed since it&#39;s a single character. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;] <strong>Output:</strong> Return 4, and the first 4 characters of the input array should be: [&quot;a&quot;,&quot;b&quot;,&quot;1&quot;,&quot;2&quot;]. <strong>Explanation:</strong> The groups are &quot;a&quot; and &quot;bbbbbbbbbbbb&quot;. This compresses to &quot;ab12&quot;.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= chars.length &lt;= 2000</code></li> <li><code>chars[i]</code> is a lowercase English letter, uppercase English letter, digit, or symbol.</li> </ul>
Two Pointers; String
Python
class Solution: def compress(self, chars: List[str]) -> int: i, k, n = 0, 0, len(chars) while i < n: j = i + 1 while j < n and chars[j] == chars[i]: j += 1 chars[k] = chars[i] k += 1 if j - i > 1: cnt = str(j - i) for c in cnt: chars[k] = c k += 1 i = j return k
443
String Compression
Medium
<p>Given an array of characters <code>chars</code>, compress it using the following algorithm:</p> <p>Begin with an empty string <code>s</code>. For each group of <strong>consecutive repeating characters</strong> in <code>chars</code>:</p> <ul> <li>If the group&#39;s length is <code>1</code>, append the character to <code>s</code>.</li> <li>Otherwise, append the character followed by the group&#39;s length.</li> </ul> <p>The compressed string <code>s</code> <strong>should not be returned separately</strong>, but instead, be stored <strong>in the input character array <code>chars</code></strong>. Note that group lengths that are <code>10</code> or longer will be split into multiple characters in <code>chars</code>.</p> <p>After you are done <strong>modifying the input array,</strong> return <em>the new length of the array</em>.</p> <p>You must write an algorithm that uses only constant extra space.</p> <p><strong>Note: </strong>The characters in the array beyond the returned length do not matter and should be ignored.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;,&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;] <strong>Output:</strong> Return 6, and the first 6 characters of the input array should be: [&quot;a&quot;,&quot;2&quot;,&quot;b&quot;,&quot;2&quot;,&quot;c&quot;,&quot;3&quot;] <strong>Explanation:</strong> The groups are &quot;aa&quot;, &quot;bb&quot;, and &quot;ccc&quot;. This compresses to &quot;a2b2c3&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;] <strong>Output:</strong> Return 1, and the first character of the input array should be: [&quot;a&quot;] <strong>Explanation:</strong> The only group is &quot;a&quot;, which remains uncompressed since it&#39;s a single character. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> chars = [&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;] <strong>Output:</strong> Return 4, and the first 4 characters of the input array should be: [&quot;a&quot;,&quot;b&quot;,&quot;1&quot;,&quot;2&quot;]. <strong>Explanation:</strong> The groups are &quot;a&quot; and &quot;bbbbbbbbbbbb&quot;. This compresses to &quot;ab12&quot;.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= chars.length &lt;= 2000</code></li> <li><code>chars[i]</code> is a lowercase English letter, uppercase English letter, digit, or symbol.</li> </ul>
Two Pointers; String
Rust
impl Solution { pub fn compress(chars: &mut Vec<char>) -> i32 { let (mut i, mut k, n) = (0, 0, chars.len()); while i < n { let mut j = i + 1; while j < n && chars[j] == chars[i] { j += 1; } chars[k] = chars[i]; k += 1; if j - i > 1 { let cnt = (j - i).to_string(); for c in cnt.chars() { chars[k] = c; k += 1; } } i = j; } k as i32 } }
444
Sequence Reconstruction
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> where <code>nums</code> is a permutation of the integers in the range <code>[1, n]</code>. You are also given a 2D integer array <code>sequences</code> where <code>sequences[i]</code> is a subsequence of <code>nums</code>.</p> <p>Check if <code>nums</code> is the shortest possible and the only <strong>supersequence</strong>. The shortest <strong>supersequence</strong> is a sequence <strong>with the shortest length</strong> and has all <code>sequences[i]</code> as subsequences. There could be multiple valid <strong>supersequences</strong> for the given array <code>sequences</code>.</p> <ul> <li>For example, for <code>sequences = [[1,2],[1,3]]</code>, there are two shortest <strong>supersequences</strong>, <code>[1,2,3]</code> and <code>[1,3,2]</code>.</li> <li>While for <code>sequences = [[1,2],[1,3],[1,2,3]]</code>, the only shortest <strong>supersequence</strong> possible is <code>[1,2,3]</code>. <code>[1,2,3,4]</code> is a possible supersequence but not the shortest.</li> </ul> <p>Return <code>true</code><em> if </em><code>nums</code><em> is the only shortest <strong>supersequence</strong> for </em><code>sequences</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subsequence</strong> is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2],[1,3]] <strong>Output:</strong> false <strong>Explanation:</strong> There are two possible supersequences: [1,2,3] and [1,3,2]. The sequence [1,2] is a subsequence of both: [<strong><u>1</u></strong>,<strong><u>2</u></strong>,3] and [<strong><u>1</u></strong>,3,<strong><u>2</u></strong>]. The sequence [1,3] is a subsequence of both: [<strong><u>1</u></strong>,2,<strong><u>3</u></strong>] and [<strong><u>1</u></strong>,<strong><u>3</u></strong>,2]. Since nums is not the only shortest supersequence, we return false. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2]] <strong>Output:</strong> false <strong>Explanation:</strong> The shortest possible supersequence is [1,2]. The sequence [1,2] is a subsequence of it: [<strong><u>1</u></strong>,<strong><u>2</u></strong>]. Since nums is not the shortest supersequence, we return false. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2],[1,3],[2,3]] <strong>Output:</strong> true <strong>Explanation:</strong> The shortest possible supersequence is [1,2,3]. The sequence [1,2] is a subsequence of it: [<strong><u>1</u></strong>,<strong><u>2</u></strong>,3]. The sequence [1,3] is a subsequence of it: [<strong><u>1</u></strong>,2,<strong><u>3</u></strong>]. The sequence [2,3] is a subsequence of it: [1,<strong><u>2</u></strong>,<strong><u>3</u></strong>]. Since nums is the only shortest supersequence, we return true. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is a permutation of all the integers in the range <code>[1, n]</code>.</li> <li><code>1 &lt;= sequences.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sequences[i].length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sum(sequences[i].length) &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= sequences[i][j] &lt;= n</code></li> <li>All the arrays of <code>sequences</code> are <strong>unique</strong>.</li> <li><code>sequences[i]</code> is a subsequence of <code>nums</code>.</li> </ul>
Graph; Topological Sort; Array
C++
class Solution { public: bool sequenceReconstruction(vector<int>& nums, vector<vector<int>>& sequences) { int n = nums.size(); vector<int> indeg(n); vector<int> g[n]; for (auto& seq : sequences) { for (int i = 1; i < seq.size(); ++i) { int a = seq[i - 1] - 1, b = seq[i] - 1; g[a].push_back(b); ++indeg[b]; } } queue<int> q; for (int i = 0; i < n; ++i) { if (indeg[i] == 0) { q.push(i); } } while (q.size() == 1) { int i = q.front(); q.pop(); for (int j : g[i]) { if (--indeg[j] == 0) { q.push(j); } } } return q.empty(); } };
444
Sequence Reconstruction
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> where <code>nums</code> is a permutation of the integers in the range <code>[1, n]</code>. You are also given a 2D integer array <code>sequences</code> where <code>sequences[i]</code> is a subsequence of <code>nums</code>.</p> <p>Check if <code>nums</code> is the shortest possible and the only <strong>supersequence</strong>. The shortest <strong>supersequence</strong> is a sequence <strong>with the shortest length</strong> and has all <code>sequences[i]</code> as subsequences. There could be multiple valid <strong>supersequences</strong> for the given array <code>sequences</code>.</p> <ul> <li>For example, for <code>sequences = [[1,2],[1,3]]</code>, there are two shortest <strong>supersequences</strong>, <code>[1,2,3]</code> and <code>[1,3,2]</code>.</li> <li>While for <code>sequences = [[1,2],[1,3],[1,2,3]]</code>, the only shortest <strong>supersequence</strong> possible is <code>[1,2,3]</code>. <code>[1,2,3,4]</code> is a possible supersequence but not the shortest.</li> </ul> <p>Return <code>true</code><em> if </em><code>nums</code><em> is the only shortest <strong>supersequence</strong> for </em><code>sequences</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subsequence</strong> is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2],[1,3]] <strong>Output:</strong> false <strong>Explanation:</strong> There are two possible supersequences: [1,2,3] and [1,3,2]. The sequence [1,2] is a subsequence of both: [<strong><u>1</u></strong>,<strong><u>2</u></strong>,3] and [<strong><u>1</u></strong>,3,<strong><u>2</u></strong>]. The sequence [1,3] is a subsequence of both: [<strong><u>1</u></strong>,2,<strong><u>3</u></strong>] and [<strong><u>1</u></strong>,<strong><u>3</u></strong>,2]. Since nums is not the only shortest supersequence, we return false. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2]] <strong>Output:</strong> false <strong>Explanation:</strong> The shortest possible supersequence is [1,2]. The sequence [1,2] is a subsequence of it: [<strong><u>1</u></strong>,<strong><u>2</u></strong>]. Since nums is not the shortest supersequence, we return false. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2],[1,3],[2,3]] <strong>Output:</strong> true <strong>Explanation:</strong> The shortest possible supersequence is [1,2,3]. The sequence [1,2] is a subsequence of it: [<strong><u>1</u></strong>,<strong><u>2</u></strong>,3]. The sequence [1,3] is a subsequence of it: [<strong><u>1</u></strong>,2,<strong><u>3</u></strong>]. The sequence [2,3] is a subsequence of it: [1,<strong><u>2</u></strong>,<strong><u>3</u></strong>]. Since nums is the only shortest supersequence, we return true. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is a permutation of all the integers in the range <code>[1, n]</code>.</li> <li><code>1 &lt;= sequences.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sequences[i].length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sum(sequences[i].length) &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= sequences[i][j] &lt;= n</code></li> <li>All the arrays of <code>sequences</code> are <strong>unique</strong>.</li> <li><code>sequences[i]</code> is a subsequence of <code>nums</code>.</li> </ul>
Graph; Topological Sort; Array
Go
func sequenceReconstruction(nums []int, sequences [][]int) bool { n := len(nums) indeg := make([]int, n) g := make([][]int, n) for _, seq := range sequences { for i, b := range seq[1:] { a := seq[i] - 1 b -= 1 g[a] = append(g[a], b) indeg[b]++ } } q := []int{} for i, x := range indeg { if x == 0 { q = append(q, i) } } for len(q) == 1 { i := q[0] q = q[1:] for _, j := range g[i] { indeg[j]-- if indeg[j] == 0 { q = append(q, j) } } } return len(q) == 0 }
444
Sequence Reconstruction
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> where <code>nums</code> is a permutation of the integers in the range <code>[1, n]</code>. You are also given a 2D integer array <code>sequences</code> where <code>sequences[i]</code> is a subsequence of <code>nums</code>.</p> <p>Check if <code>nums</code> is the shortest possible and the only <strong>supersequence</strong>. The shortest <strong>supersequence</strong> is a sequence <strong>with the shortest length</strong> and has all <code>sequences[i]</code> as subsequences. There could be multiple valid <strong>supersequences</strong> for the given array <code>sequences</code>.</p> <ul> <li>For example, for <code>sequences = [[1,2],[1,3]]</code>, there are two shortest <strong>supersequences</strong>, <code>[1,2,3]</code> and <code>[1,3,2]</code>.</li> <li>While for <code>sequences = [[1,2],[1,3],[1,2,3]]</code>, the only shortest <strong>supersequence</strong> possible is <code>[1,2,3]</code>. <code>[1,2,3,4]</code> is a possible supersequence but not the shortest.</li> </ul> <p>Return <code>true</code><em> if </em><code>nums</code><em> is the only shortest <strong>supersequence</strong> for </em><code>sequences</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subsequence</strong> is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2],[1,3]] <strong>Output:</strong> false <strong>Explanation:</strong> There are two possible supersequences: [1,2,3] and [1,3,2]. The sequence [1,2] is a subsequence of both: [<strong><u>1</u></strong>,<strong><u>2</u></strong>,3] and [<strong><u>1</u></strong>,3,<strong><u>2</u></strong>]. The sequence [1,3] is a subsequence of both: [<strong><u>1</u></strong>,2,<strong><u>3</u></strong>] and [<strong><u>1</u></strong>,<strong><u>3</u></strong>,2]. Since nums is not the only shortest supersequence, we return false. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2]] <strong>Output:</strong> false <strong>Explanation:</strong> The shortest possible supersequence is [1,2]. The sequence [1,2] is a subsequence of it: [<strong><u>1</u></strong>,<strong><u>2</u></strong>]. Since nums is not the shortest supersequence, we return false. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2],[1,3],[2,3]] <strong>Output:</strong> true <strong>Explanation:</strong> The shortest possible supersequence is [1,2,3]. The sequence [1,2] is a subsequence of it: [<strong><u>1</u></strong>,<strong><u>2</u></strong>,3]. The sequence [1,3] is a subsequence of it: [<strong><u>1</u></strong>,2,<strong><u>3</u></strong>]. The sequence [2,3] is a subsequence of it: [1,<strong><u>2</u></strong>,<strong><u>3</u></strong>]. Since nums is the only shortest supersequence, we return true. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is a permutation of all the integers in the range <code>[1, n]</code>.</li> <li><code>1 &lt;= sequences.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sequences[i].length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sum(sequences[i].length) &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= sequences[i][j] &lt;= n</code></li> <li>All the arrays of <code>sequences</code> are <strong>unique</strong>.</li> <li><code>sequences[i]</code> is a subsequence of <code>nums</code>.</li> </ul>
Graph; Topological Sort; Array
Java
class Solution { public boolean sequenceReconstruction(int[] nums, List<List<Integer>> sequences) { int n = nums.length; int[] indeg = new int[n]; List<Integer>[] g = new List[n]; Arrays.setAll(g, k -> new ArrayList<>()); for (var seq : sequences) { for (int i = 1; i < seq.size(); ++i) { int a = seq.get(i - 1) - 1, b = seq.get(i) - 1; g[a].add(b); ++indeg[b]; } } Deque<Integer> q = new ArrayDeque<>(); for (int i = 0; i < n; ++i) { if (indeg[i] == 0) { q.offer(i); } } while (q.size() == 1) { int i = q.poll(); for (int j : g[i]) { if (--indeg[j] == 0) { q.offer(j); } } } return q.isEmpty(); } }
444
Sequence Reconstruction
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> where <code>nums</code> is a permutation of the integers in the range <code>[1, n]</code>. You are also given a 2D integer array <code>sequences</code> where <code>sequences[i]</code> is a subsequence of <code>nums</code>.</p> <p>Check if <code>nums</code> is the shortest possible and the only <strong>supersequence</strong>. The shortest <strong>supersequence</strong> is a sequence <strong>with the shortest length</strong> and has all <code>sequences[i]</code> as subsequences. There could be multiple valid <strong>supersequences</strong> for the given array <code>sequences</code>.</p> <ul> <li>For example, for <code>sequences = [[1,2],[1,3]]</code>, there are two shortest <strong>supersequences</strong>, <code>[1,2,3]</code> and <code>[1,3,2]</code>.</li> <li>While for <code>sequences = [[1,2],[1,3],[1,2,3]]</code>, the only shortest <strong>supersequence</strong> possible is <code>[1,2,3]</code>. <code>[1,2,3,4]</code> is a possible supersequence but not the shortest.</li> </ul> <p>Return <code>true</code><em> if </em><code>nums</code><em> is the only shortest <strong>supersequence</strong> for </em><code>sequences</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subsequence</strong> is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2],[1,3]] <strong>Output:</strong> false <strong>Explanation:</strong> There are two possible supersequences: [1,2,3] and [1,3,2]. The sequence [1,2] is a subsequence of both: [<strong><u>1</u></strong>,<strong><u>2</u></strong>,3] and [<strong><u>1</u></strong>,3,<strong><u>2</u></strong>]. The sequence [1,3] is a subsequence of both: [<strong><u>1</u></strong>,2,<strong><u>3</u></strong>] and [<strong><u>1</u></strong>,<strong><u>3</u></strong>,2]. Since nums is not the only shortest supersequence, we return false. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2]] <strong>Output:</strong> false <strong>Explanation:</strong> The shortest possible supersequence is [1,2]. The sequence [1,2] is a subsequence of it: [<strong><u>1</u></strong>,<strong><u>2</u></strong>]. Since nums is not the shortest supersequence, we return false. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2],[1,3],[2,3]] <strong>Output:</strong> true <strong>Explanation:</strong> The shortest possible supersequence is [1,2,3]. The sequence [1,2] is a subsequence of it: [<strong><u>1</u></strong>,<strong><u>2</u></strong>,3]. The sequence [1,3] is a subsequence of it: [<strong><u>1</u></strong>,2,<strong><u>3</u></strong>]. The sequence [2,3] is a subsequence of it: [1,<strong><u>2</u></strong>,<strong><u>3</u></strong>]. Since nums is the only shortest supersequence, we return true. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is a permutation of all the integers in the range <code>[1, n]</code>.</li> <li><code>1 &lt;= sequences.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sequences[i].length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sum(sequences[i].length) &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= sequences[i][j] &lt;= n</code></li> <li>All the arrays of <code>sequences</code> are <strong>unique</strong>.</li> <li><code>sequences[i]</code> is a subsequence of <code>nums</code>.</li> </ul>
Graph; Topological Sort; Array
Python
class Solution: def sequenceReconstruction( self, nums: List[int], sequences: List[List[int]] ) -> bool: n = len(nums) g = [[] for _ in range(n)] indeg = [0] * n for seq in sequences: for a, b in pairwise(seq): a, b = a - 1, b - 1 g[a].append(b) indeg[b] += 1 q = deque(i for i, x in enumerate(indeg) if x == 0) while len(q) == 1: i = q.popleft() for j in g[i]: indeg[j] -= 1 if indeg[j] == 0: q.append(j) return len(q) == 0
444
Sequence Reconstruction
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code> where <code>nums</code> is a permutation of the integers in the range <code>[1, n]</code>. You are also given a 2D integer array <code>sequences</code> where <code>sequences[i]</code> is a subsequence of <code>nums</code>.</p> <p>Check if <code>nums</code> is the shortest possible and the only <strong>supersequence</strong>. The shortest <strong>supersequence</strong> is a sequence <strong>with the shortest length</strong> and has all <code>sequences[i]</code> as subsequences. There could be multiple valid <strong>supersequences</strong> for the given array <code>sequences</code>.</p> <ul> <li>For example, for <code>sequences = [[1,2],[1,3]]</code>, there are two shortest <strong>supersequences</strong>, <code>[1,2,3]</code> and <code>[1,3,2]</code>.</li> <li>While for <code>sequences = [[1,2],[1,3],[1,2,3]]</code>, the only shortest <strong>supersequence</strong> possible is <code>[1,2,3]</code>. <code>[1,2,3,4]</code> is a possible supersequence but not the shortest.</li> </ul> <p>Return <code>true</code><em> if </em><code>nums</code><em> is the only shortest <strong>supersequence</strong> for </em><code>sequences</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subsequence</strong> is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2],[1,3]] <strong>Output:</strong> false <strong>Explanation:</strong> There are two possible supersequences: [1,2,3] and [1,3,2]. The sequence [1,2] is a subsequence of both: [<strong><u>1</u></strong>,<strong><u>2</u></strong>,3] and [<strong><u>1</u></strong>,3,<strong><u>2</u></strong>]. The sequence [1,3] is a subsequence of both: [<strong><u>1</u></strong>,2,<strong><u>3</u></strong>] and [<strong><u>1</u></strong>,<strong><u>3</u></strong>,2]. Since nums is not the only shortest supersequence, we return false. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2]] <strong>Output:</strong> false <strong>Explanation:</strong> The shortest possible supersequence is [1,2]. The sequence [1,2] is a subsequence of it: [<strong><u>1</u></strong>,<strong><u>2</u></strong>]. Since nums is not the shortest supersequence, we return false. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3], sequences = [[1,2],[1,3],[2,3]] <strong>Output:</strong> true <strong>Explanation:</strong> The shortest possible supersequence is [1,2,3]. The sequence [1,2] is a subsequence of it: [<strong><u>1</u></strong>,<strong><u>2</u></strong>,3]. The sequence [1,3] is a subsequence of it: [<strong><u>1</u></strong>,2,<strong><u>3</u></strong>]. The sequence [2,3] is a subsequence of it: [1,<strong><u>2</u></strong>,<strong><u>3</u></strong>]. Since nums is the only shortest supersequence, we return true. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> is a permutation of all the integers in the range <code>[1, n]</code>.</li> <li><code>1 &lt;= sequences.length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sequences[i].length &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= sum(sequences[i].length) &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= sequences[i][j] &lt;= n</code></li> <li>All the arrays of <code>sequences</code> are <strong>unique</strong>.</li> <li><code>sequences[i]</code> is a subsequence of <code>nums</code>.</li> </ul>
Graph; Topological Sort; Array
TypeScript
function sequenceReconstruction(nums: number[], sequences: number[][]): boolean { const n = nums.length; const g: number[][] = Array.from({ length: n }, () => []); const indeg: number[] = Array(n).fill(0); for (const seq of sequences) { for (let i = 1; i < seq.length; ++i) { const [a, b] = [seq[i - 1] - 1, seq[i] - 1]; g[a].push(b); ++indeg[b]; } } const q: number[] = indeg.map((v, i) => (v === 0 ? i : -1)).filter(v => v !== -1); while (q.length === 1) { const i = q.pop()!; for (const j of g[i]) { if (--indeg[j] === 0) { q.push(j); } } } return q.length === 0; }
445
Add Two Numbers II
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.</p> <p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0445.Add%20Two%20Numbers%20II/images/sumii-linked-list.jpg" style="width: 523px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [7,2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,8,0,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [8,0,7] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Could you solve it without reversing the input lists?</p>
Stack; Linked List; Math
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: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { stack<int> s1; stack<int> s2; for (; l1; l1 = l1->next) s1.push(l1->val); for (; l2; l2 = l2->next) s2.push(l2->val); ListNode* dummy = new ListNode(); int carry = 0; while (!s1.empty() || !s2.empty() || carry) { int s = carry; if (!s1.empty()) { s += s1.top(); s1.pop(); } if (!s2.empty()) { s += s2.top(); s2.pop(); } // ListNode* node = new ListNode(s % 10, dummy->next); // dummy->next = node; dummy->next = new ListNode(s % 10, dummy->next); carry = s / 10; } return dummy->next; } };
445
Add Two Numbers II
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.</p> <p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0445.Add%20Two%20Numbers%20II/images/sumii-linked-list.jpg" style="width: 523px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [7,2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,8,0,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [8,0,7] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Could you solve it without reversing the input lists?</p>
Stack; Linked List; Math
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { s1, s2 := arraystack.New(), arraystack.New() for l1 != nil { s1.Push(l1.Val) l1 = l1.Next } for l2 != nil { s2.Push(l2.Val) l2 = l2.Next } carry, dummy := 0, new(ListNode) for !s1.Empty() || !s2.Empty() || carry > 0 { s := carry v, ok := s1.Pop() if ok { s += v.(int) } v, ok = s2.Pop() if ok { s += v.(int) } // node := &ListNode{s % 10, dummy.Next} // dummy.Next = node dummy.Next = &ListNode{s % 10, dummy.Next} carry = s / 10 } return dummy.Next }
445
Add Two Numbers II
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.</p> <p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0445.Add%20Two%20Numbers%20II/images/sumii-linked-list.jpg" style="width: 523px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [7,2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,8,0,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [8,0,7] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Could you solve it without reversing the input lists?</p>
Stack; Linked List; Math
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 addTwoNumbers(ListNode l1, ListNode l2) { Deque<Integer> s1 = new ArrayDeque<>(); Deque<Integer> s2 = new ArrayDeque<>(); for (; l1 != null; l1 = l1.next) { s1.push(l1.val); } for (; l2 != null; l2 = l2.next) { s2.push(l2.val); } ListNode dummy = new ListNode(); int carry = 0; while (!s1.isEmpty() || !s2.isEmpty() || carry != 0) { int s = (s1.isEmpty() ? 0 : s1.pop()) + (s2.isEmpty() ? 0 : s2.pop()) + carry; // ListNode node = new ListNode(s % 10, dummy.next); // dummy.next = node; dummy.next = new ListNode(s % 10, dummy.next); carry = s / 10; } return dummy.next; } }
445
Add Two Numbers II
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.</p> <p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0445.Add%20Two%20Numbers%20II/images/sumii-linked-list.jpg" style="width: 523px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [7,2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,8,0,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [8,0,7] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Could you solve it without reversing the input lists?</p>
Stack; Linked List; Math
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers( self, l1: Optional[ListNode], l2: Optional[ListNode] ) -> Optional[ListNode]: s1, s2 = [], [] while l1: s1.append(l1.val) l1 = l1.next while l2: s2.append(l2.val) l2 = l2.next dummy = ListNode() carry = 0 while s1 or s2 or carry: s = (0 if not s1 else s1.pop()) + (0 if not s2 else s2.pop()) + carry carry, val = divmod(s, 10) # node = ListNode(val, dummy.next) # dummy.next = node dummy.next = ListNode(val, dummy.next) return dummy.next
445
Add Two Numbers II
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.</p> <p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0445.Add%20Two%20Numbers%20II/images/sumii-linked-list.jpg" style="width: 523px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [7,2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,8,0,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [8,0,7] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Could you solve it without reversing the input lists?</p>
Stack; Linked List; Math
Rust
// Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] // pub struct ListNode { // pub val: i32, // pub next: Option<Box<ListNode>> // } // // impl ListNode { // #[inline] // fn new(val: i32) -> Self { // ListNode { // next: None, // val // } // } // } impl Solution { fn reverse(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut pre = None; while let Some(mut node) = head { let next = node.next.take(); node.next = pre.take(); pre = Some(node); head = next; } pre } pub fn add_two_numbers( mut l1: Option<Box<ListNode>>, mut l2: Option<Box<ListNode>>, ) -> Option<Box<ListNode>> { l1 = Self::reverse(l1); l2 = Self::reverse(l2); let mut dummy = Some(Box::new(ListNode::new(0))); let mut cur = &mut dummy; let mut sum = 0; while l1.is_some() || l2.is_some() || sum != 0 { if let Some(node) = l1 { sum += node.val; l1 = node.next; } if let Some(node) = l2 { sum += node.val; l2 = node.next; } cur.as_mut().unwrap().next = Some(Box::new(ListNode::new(sum % 10))); cur = &mut cur.as_mut().unwrap().next; sum /= 10; } Self::reverse(dummy.unwrap().next.take()) } }
445
Add Two Numbers II
Medium
<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.</p> <p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0445.Add%20Two%20Numbers%20II/images/sumii-linked-list.jpg" style="width: 523px; height: 342px;" /> <pre> <strong>Input:</strong> l1 = [7,2,4,3], l2 = [5,6,4] <strong>Output:</strong> [7,8,0,7] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4] <strong>Output:</strong> [8,0,7] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> l1 = [0], l2 = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 9</code></li> <li>It is guaranteed that the list represents a number that does not have leading zeros.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong>&nbsp;Could you solve it without reversing the input lists?</p>
Stack; Linked List; Math
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 addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null { const s1: number[] = []; const s2: number[] = []; for (; l1; l1 = l1.next) { s1.push(l1.val); } for (; l2; l2 = l2.next) { s2.push(l2.val); } const dummy = new ListNode(); let carry = 0; while (s1.length || s2.length || carry) { const s = (s1.pop() ?? 0) + (s2.pop() ?? 0) + carry; // const node = new ListNode(s % 10, dummy.next); // dummy.next = node; dummy.next = new ListNode(s % 10, dummy.next); carry = Math.floor(s / 10); } return dummy.next; }
446
Arithmetic Slices II - Subsequence
Hard
<p>Given an integer array <code>nums</code>, return <em>the number of all the <strong>arithmetic subsequences</strong> of</em> <code>nums</code>.</p> <p>A sequence of numbers is called arithmetic if it consists of <strong>at least three elements</strong> and if the difference between any two consecutive elements is the same.</p> <ul> <li>For example, <code>[1, 3, 5, 7, 9]</code>, <code>[7, 7, 7, 7]</code>, and <code>[3, -1, -5, -9]</code> are arithmetic sequences.</li> <li>For example, <code>[1, 1, 2, 5, 7]</code> is not an arithmetic sequence.</li> </ul> <p>A <strong>subsequence</strong> of an array is a sequence that can be formed by removing some elements (possibly none) of the array.</p> <ul> <li>For example, <code>[2,5,10]</code> is a subsequence of <code>[1,2,1,<strong><u>2</u></strong>,4,1,<u><strong>5</strong></u>,<u><strong>10</strong></u>]</code>.</li> </ul> <p>The test cases are generated so that the answer fits in <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,6,8,10] <strong>Output:</strong> 7 <strong>Explanation:</strong> All arithmetic subsequence slices are: [2,4,6] [4,6,8] [6,8,10] [2,4,6,8] [4,6,8,10] [2,4,6,8,10] [2,6,10] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,7,7,7,7] <strong>Output:</strong> 16 <strong>Explanation:</strong> Any subsequence of this array is arithmetic. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1&nbsp; &lt;= nums.length &lt;= 1000</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Dynamic Programming
C++
class Solution { public: int numberOfArithmeticSlices(vector<int>& nums) { int n = nums.size(); unordered_map<long long, int> f[n]; int ans = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { long long d = 1LL * nums[i] - nums[j]; int cnt = f[j][d]; ans += cnt; f[i][d] += cnt + 1; } } return ans; } };
446
Arithmetic Slices II - Subsequence
Hard
<p>Given an integer array <code>nums</code>, return <em>the number of all the <strong>arithmetic subsequences</strong> of</em> <code>nums</code>.</p> <p>A sequence of numbers is called arithmetic if it consists of <strong>at least three elements</strong> and if the difference between any two consecutive elements is the same.</p> <ul> <li>For example, <code>[1, 3, 5, 7, 9]</code>, <code>[7, 7, 7, 7]</code>, and <code>[3, -1, -5, -9]</code> are arithmetic sequences.</li> <li>For example, <code>[1, 1, 2, 5, 7]</code> is not an arithmetic sequence.</li> </ul> <p>A <strong>subsequence</strong> of an array is a sequence that can be formed by removing some elements (possibly none) of the array.</p> <ul> <li>For example, <code>[2,5,10]</code> is a subsequence of <code>[1,2,1,<strong><u>2</u></strong>,4,1,<u><strong>5</strong></u>,<u><strong>10</strong></u>]</code>.</li> </ul> <p>The test cases are generated so that the answer fits in <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,6,8,10] <strong>Output:</strong> 7 <strong>Explanation:</strong> All arithmetic subsequence slices are: [2,4,6] [4,6,8] [6,8,10] [2,4,6,8] [4,6,8,10] [2,4,6,8,10] [2,6,10] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,7,7,7,7] <strong>Output:</strong> 16 <strong>Explanation:</strong> Any subsequence of this array is arithmetic. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1&nbsp; &lt;= nums.length &lt;= 1000</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Dynamic Programming
Go
func numberOfArithmeticSlices(nums []int) (ans int) { f := make([]map[int]int, len(nums)) for i := range f { f[i] = map[int]int{} } for i, x := range nums { for j, y := range nums[:i] { d := x - y cnt := f[j][d] ans += cnt f[i][d] += cnt + 1 } } return }
446
Arithmetic Slices II - Subsequence
Hard
<p>Given an integer array <code>nums</code>, return <em>the number of all the <strong>arithmetic subsequences</strong> of</em> <code>nums</code>.</p> <p>A sequence of numbers is called arithmetic if it consists of <strong>at least three elements</strong> and if the difference between any two consecutive elements is the same.</p> <ul> <li>For example, <code>[1, 3, 5, 7, 9]</code>, <code>[7, 7, 7, 7]</code>, and <code>[3, -1, -5, -9]</code> are arithmetic sequences.</li> <li>For example, <code>[1, 1, 2, 5, 7]</code> is not an arithmetic sequence.</li> </ul> <p>A <strong>subsequence</strong> of an array is a sequence that can be formed by removing some elements (possibly none) of the array.</p> <ul> <li>For example, <code>[2,5,10]</code> is a subsequence of <code>[1,2,1,<strong><u>2</u></strong>,4,1,<u><strong>5</strong></u>,<u><strong>10</strong></u>]</code>.</li> </ul> <p>The test cases are generated so that the answer fits in <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,6,8,10] <strong>Output:</strong> 7 <strong>Explanation:</strong> All arithmetic subsequence slices are: [2,4,6] [4,6,8] [6,8,10] [2,4,6,8] [4,6,8,10] [2,4,6,8,10] [2,6,10] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,7,7,7,7] <strong>Output:</strong> 16 <strong>Explanation:</strong> Any subsequence of this array is arithmetic. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1&nbsp; &lt;= nums.length &lt;= 1000</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Dynamic Programming
Java
class Solution { public int numberOfArithmeticSlices(int[] nums) { int n = nums.length; Map<Long, Integer>[] f = new Map[n]; Arrays.setAll(f, k -> new HashMap<>()); int ans = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { Long d = 1L * nums[i] - nums[j]; int cnt = f[j].getOrDefault(d, 0); ans += cnt; f[i].merge(d, cnt + 1, Integer::sum); } } return ans; } }
446
Arithmetic Slices II - Subsequence
Hard
<p>Given an integer array <code>nums</code>, return <em>the number of all the <strong>arithmetic subsequences</strong> of</em> <code>nums</code>.</p> <p>A sequence of numbers is called arithmetic if it consists of <strong>at least three elements</strong> and if the difference between any two consecutive elements is the same.</p> <ul> <li>For example, <code>[1, 3, 5, 7, 9]</code>, <code>[7, 7, 7, 7]</code>, and <code>[3, -1, -5, -9]</code> are arithmetic sequences.</li> <li>For example, <code>[1, 1, 2, 5, 7]</code> is not an arithmetic sequence.</li> </ul> <p>A <strong>subsequence</strong> of an array is a sequence that can be formed by removing some elements (possibly none) of the array.</p> <ul> <li>For example, <code>[2,5,10]</code> is a subsequence of <code>[1,2,1,<strong><u>2</u></strong>,4,1,<u><strong>5</strong></u>,<u><strong>10</strong></u>]</code>.</li> </ul> <p>The test cases are generated so that the answer fits in <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,6,8,10] <strong>Output:</strong> 7 <strong>Explanation:</strong> All arithmetic subsequence slices are: [2,4,6] [4,6,8] [6,8,10] [2,4,6,8] [4,6,8,10] [2,4,6,8,10] [2,6,10] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,7,7,7,7] <strong>Output:</strong> 16 <strong>Explanation:</strong> Any subsequence of this array is arithmetic. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1&nbsp; &lt;= nums.length &lt;= 1000</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Dynamic Programming
Python
class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: f = [defaultdict(int) for _ in nums] ans = 0 for i, x in enumerate(nums): for j, y in enumerate(nums[:i]): d = x - y ans += f[j][d] f[i][d] += f[j][d] + 1 return ans
446
Arithmetic Slices II - Subsequence
Hard
<p>Given an integer array <code>nums</code>, return <em>the number of all the <strong>arithmetic subsequences</strong> of</em> <code>nums</code>.</p> <p>A sequence of numbers is called arithmetic if it consists of <strong>at least three elements</strong> and if the difference between any two consecutive elements is the same.</p> <ul> <li>For example, <code>[1, 3, 5, 7, 9]</code>, <code>[7, 7, 7, 7]</code>, and <code>[3, -1, -5, -9]</code> are arithmetic sequences.</li> <li>For example, <code>[1, 1, 2, 5, 7]</code> is not an arithmetic sequence.</li> </ul> <p>A <strong>subsequence</strong> of an array is a sequence that can be formed by removing some elements (possibly none) of the array.</p> <ul> <li>For example, <code>[2,5,10]</code> is a subsequence of <code>[1,2,1,<strong><u>2</u></strong>,4,1,<u><strong>5</strong></u>,<u><strong>10</strong></u>]</code>.</li> </ul> <p>The test cases are generated so that the answer fits in <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [2,4,6,8,10] <strong>Output:</strong> 7 <strong>Explanation:</strong> All arithmetic subsequence slices are: [2,4,6] [4,6,8] [6,8,10] [2,4,6,8] [4,6,8,10] [2,4,6,8,10] [2,6,10] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [7,7,7,7,7] <strong>Output:</strong> 16 <strong>Explanation:</strong> Any subsequence of this array is arithmetic. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1&nbsp; &lt;= nums.length &lt;= 1000</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Dynamic Programming
TypeScript
function numberOfArithmeticSlices(nums: number[]): number { const n = nums.length; const f: Map<number, number>[] = new Array(n).fill(0).map(() => new Map()); let ans = 0; for (let i = 0; i < n; ++i) { for (let j = 0; j < i; ++j) { const d = nums[i] - nums[j]; const cnt = f[j].get(d) || 0; ans += cnt; f[i].set(d, (f[i].get(d) || 0) + cnt + 1); } } return ans; }
447
Number of Boomerangs
Medium
<p>You are given <code>n</code> <code>points</code> in the plane that are all <strong>distinct</strong>, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. A <strong>boomerang</strong> is a tuple of points <code>(i, j, k)</code> such that the distance between <code>i</code> and <code>j</code> equals the distance between <code>i</code> and <code>k</code> <strong>(the order of the tuple matters)</strong>.</p> <p>Return <em>the number of boomerangs</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> points = [[0,0],[1,0],[2,0]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> points = [[1,1],[2,2],[3,3]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> points = [[1,1]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == points.length</code></li> <li><code>1 &lt;= n &lt;= 500</code></li> <li><code>points[i].length == 2</code></li> <li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li> <li>All the points are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Math
C++
class Solution { public: int numberOfBoomerangs(vector<vector<int>>& points) { int ans = 0; for (auto& p1 : points) { unordered_map<int, int> cnt; for (auto& p2 : points) { int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); ans += cnt[d]; cnt[d]++; } } return ans << 1; } };
447
Number of Boomerangs
Medium
<p>You are given <code>n</code> <code>points</code> in the plane that are all <strong>distinct</strong>, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. A <strong>boomerang</strong> is a tuple of points <code>(i, j, k)</code> such that the distance between <code>i</code> and <code>j</code> equals the distance between <code>i</code> and <code>k</code> <strong>(the order of the tuple matters)</strong>.</p> <p>Return <em>the number of boomerangs</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> points = [[0,0],[1,0],[2,0]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> points = [[1,1],[2,2],[3,3]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> points = [[1,1]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == points.length</code></li> <li><code>1 &lt;= n &lt;= 500</code></li> <li><code>points[i].length == 2</code></li> <li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li> <li>All the points are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Math
Go
func numberOfBoomerangs(points [][]int) (ans int) { for _, p1 := range points { cnt := map[int]int{} for _, p2 := range points { d := (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) ans += cnt[d] cnt[d]++ } } ans <<= 1 return }
447
Number of Boomerangs
Medium
<p>You are given <code>n</code> <code>points</code> in the plane that are all <strong>distinct</strong>, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. A <strong>boomerang</strong> is a tuple of points <code>(i, j, k)</code> such that the distance between <code>i</code> and <code>j</code> equals the distance between <code>i</code> and <code>k</code> <strong>(the order of the tuple matters)</strong>.</p> <p>Return <em>the number of boomerangs</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> points = [[0,0],[1,0],[2,0]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> points = [[1,1],[2,2],[3,3]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> points = [[1,1]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == points.length</code></li> <li><code>1 &lt;= n &lt;= 500</code></li> <li><code>points[i].length == 2</code></li> <li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li> <li>All the points are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Math
Java
class Solution { public int numberOfBoomerangs(int[][] points) { int ans = 0; for (int[] p1 : points) { Map<Integer, Integer> cnt = new HashMap<>(); for (int[] p2 : points) { int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); ans += cnt.getOrDefault(d, 0); cnt.merge(d, 1, Integer::sum); } } return ans << 1; } }
447
Number of Boomerangs
Medium
<p>You are given <code>n</code> <code>points</code> in the plane that are all <strong>distinct</strong>, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. A <strong>boomerang</strong> is a tuple of points <code>(i, j, k)</code> such that the distance between <code>i</code> and <code>j</code> equals the distance between <code>i</code> and <code>k</code> <strong>(the order of the tuple matters)</strong>.</p> <p>Return <em>the number of boomerangs</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> points = [[0,0],[1,0],[2,0]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> points = [[1,1],[2,2],[3,3]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> points = [[1,1]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == points.length</code></li> <li><code>1 &lt;= n &lt;= 500</code></li> <li><code>points[i].length == 2</code></li> <li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li> <li>All the points are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Math
Python
class Solution: def numberOfBoomerangs(self, points: List[List[int]]) -> int: ans = 0 for p1 in points: cnt = Counter() for p2 in points: d = dist(p1, p2) ans += cnt[d] cnt[d] += 1 return ans << 1
447
Number of Boomerangs
Medium
<p>You are given <code>n</code> <code>points</code> in the plane that are all <strong>distinct</strong>, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. A <strong>boomerang</strong> is a tuple of points <code>(i, j, k)</code> such that the distance between <code>i</code> and <code>j</code> equals the distance between <code>i</code> and <code>k</code> <strong>(the order of the tuple matters)</strong>.</p> <p>Return <em>the number of boomerangs</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> points = [[0,0],[1,0],[2,0]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> points = [[1,1],[2,2],[3,3]] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> points = [[1,1]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == points.length</code></li> <li><code>1 &lt;= n &lt;= 500</code></li> <li><code>points[i].length == 2</code></li> <li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li> <li>All the points are <strong>unique</strong>.</li> </ul>
Array; Hash Table; Math
TypeScript
function numberOfBoomerangs(points: number[][]): number { let ans = 0; for (const [x1, y1] of points) { const cnt: Map<number, number> = new Map(); for (const [x2, y2] of points) { const d = (x1 - x2) ** 2 + (y1 - y2) ** 2; ans += cnt.get(d) || 0; cnt.set(d, (cnt.get(d) || 0) + 1); } } return ans << 1; }
448
Find All Numbers Disappeared in an Array
Easy
<p>Given an array <code>nums</code> of <code>n</code> integers where <code>nums[i]</code> is in the range <code>[1, n]</code>, return <em>an array of all the integers in the range</em> <code>[1, n]</code> <em>that do not appear in</em> <code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,3,2,7,8,2,3,1] <strong>Output:</strong> [5,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1] <strong>Output:</strong> [2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it without extra space and in <code>O(n)</code> runtime? You may assume the returned list does not count as extra space.</p>
Array; Hash Table
C++
class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { int n = nums.size(); bool s[n + 1]; memset(s, false, sizeof(s)); for (int& x : nums) { s[x] = true; } vector<int> ans; for (int i = 1; i <= n; ++i) { if (!s[i]) { ans.push_back(i); } } return ans; } };
448
Find All Numbers Disappeared in an Array
Easy
<p>Given an array <code>nums</code> of <code>n</code> integers where <code>nums[i]</code> is in the range <code>[1, n]</code>, return <em>an array of all the integers in the range</em> <code>[1, n]</code> <em>that do not appear in</em> <code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,3,2,7,8,2,3,1] <strong>Output:</strong> [5,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1] <strong>Output:</strong> [2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it without extra space and in <code>O(n)</code> runtime? You may assume the returned list does not count as extra space.</p>
Array; Hash Table
Go
func findDisappearedNumbers(nums []int) (ans []int) { n := len(nums) s := make([]bool, n+1) for _, x := range nums { s[x] = true } for i := 1; i <= n; i++ { if !s[i] { ans = append(ans, i) } } return }
448
Find All Numbers Disappeared in an Array
Easy
<p>Given an array <code>nums</code> of <code>n</code> integers where <code>nums[i]</code> is in the range <code>[1, n]</code>, return <em>an array of all the integers in the range</em> <code>[1, n]</code> <em>that do not appear in</em> <code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,3,2,7,8,2,3,1] <strong>Output:</strong> [5,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1] <strong>Output:</strong> [2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it without extra space and in <code>O(n)</code> runtime? You may assume the returned list does not count as extra space.</p>
Array; Hash Table
Java
class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { int n = nums.length; boolean[] s = new boolean[n + 1]; for (int x : nums) { s[x] = true; } List<Integer> ans = new ArrayList<>(); for (int i = 1; i <= n; i++) { if (!s[i]) { ans.add(i); } } return ans; } }
448
Find All Numbers Disappeared in an Array
Easy
<p>Given an array <code>nums</code> of <code>n</code> integers where <code>nums[i]</code> is in the range <code>[1, n]</code>, return <em>an array of all the integers in the range</em> <code>[1, n]</code> <em>that do not appear in</em> <code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,3,2,7,8,2,3,1] <strong>Output:</strong> [5,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1] <strong>Output:</strong> [2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it without extra space and in <code>O(n)</code> runtime? You may assume the returned list does not count as extra space.</p>
Array; Hash Table
Python
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: s = set(nums) return [x for x in range(1, len(nums) + 1) if x not in s]
448
Find All Numbers Disappeared in an Array
Easy
<p>Given an array <code>nums</code> of <code>n</code> integers where <code>nums[i]</code> is in the range <code>[1, n]</code>, return <em>an array of all the integers in the range</em> <code>[1, n]</code> <em>that do not appear in</em> <code>nums</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,3,2,7,8,2,3,1] <strong>Output:</strong> [5,6] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [1,1] <strong>Output:</strong> [2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do it without extra space and in <code>O(n)</code> runtime? You may assume the returned list does not count as extra space.</p>
Array; Hash Table
TypeScript
function findDisappearedNumbers(nums: number[]): number[] { const n = nums.length; const s: boolean[] = new Array(n + 1).fill(false); for (const x of nums) { s[x] = true; } const ans: number[] = []; for (let i = 1; i <= n; ++i) { if (!s[i]) { ans.push(i); } } return ans; }
449
Serialize and Deserialize BST
Medium
<p>Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p> <p>Design an algorithm to serialize and deserialize a <b>binary search tree</b>. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.</p> <p><b>The encoded string should be as compact as possible.</b></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [2,1,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The input tree is <strong>guaranteed</strong> to be a binary search tree.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; Binary Search Tree; String; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { if (!root) { return ""; } string data = ""; function<void(TreeNode*)> dfs = [&](TreeNode* root) { if (!root) { return; } data += to_string(root->val) + " "; dfs(root->left); dfs(root->right); }; dfs(root); data.pop_back(); return data; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if (data.empty()) { return nullptr; } vector<int> nums = split(data, ' '); int i = 0; function<TreeNode*(int, int)> dfs = [&](int mi, int mx) -> TreeNode* { if (i == nums.size() || nums[i] < mi || nums[i] > mx) { return nullptr; } int x = nums[i++]; TreeNode* root = new TreeNode(x); root->left = dfs(mi, x); root->right = dfs(x, mx); return root; }; return dfs(INT_MIN, INT_MAX); } vector<int> split(const string& s, char delim) { vector<int> tokens; stringstream ss(s); string token; while (getline(ss, token, delim)) { tokens.push_back(stoi(token)); } return tokens; } }; // Your Codec object will be instantiated and called as such: // Codec* ser = new Codec(); // Codec* deser = new Codec(); // string tree = ser->serialize(root); // TreeNode* ans = deser->deserialize(tree); // return ans;
449
Serialize and Deserialize BST
Medium
<p>Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p> <p>Design an algorithm to serialize and deserialize a <b>binary search tree</b>. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.</p> <p><b>The encoded string should be as compact as possible.</b></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [2,1,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The input tree is <strong>guaranteed</strong> to be a binary search tree.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; Binary Search Tree; String; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type Codec struct { } func Constructor() Codec { return Codec{} } // Serializes a tree to a single string. func (this *Codec) serialize(root *TreeNode) string { if root == nil { return "" } data := &strings.Builder{} var dfs func(*TreeNode) dfs = func(root *TreeNode) { if root == nil { return } data.WriteString(strconv.Itoa(root.Val)) data.WriteByte(' ') dfs(root.Left) dfs(root.Right) } dfs(root) return data.String()[0 : data.Len()-1] } // Deserializes your encoded data to tree. func (this *Codec) deserialize(data string) *TreeNode { if data == "" { return nil } vals := strings.Split(data, " ") i := 0 var dfs func(int, int) *TreeNode dfs = func(mi, mx int) *TreeNode { if i == len(vals) { return nil } x, _ := strconv.Atoi(vals[i]) if x < mi || x > mx { return nil } i++ root := &TreeNode{Val: x} root.Left = dfs(mi, x) root.Right = dfs(x, mx) return root } return dfs(math.MinInt64, math.MaxInt64) } /** * Your Codec object will be instantiated and called as such: * ser := Constructor() * deser := Constructor() * tree := ser.serialize(root) * ans := deser.deserialize(tree) * return ans */
449
Serialize and Deserialize BST
Medium
<p>Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p> <p>Design an algorithm to serialize and deserialize a <b>binary search tree</b>. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.</p> <p><b>The encoded string should be as compact as possible.</b></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [2,1,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The input tree is <strong>guaranteed</strong> to be a binary search tree.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; Binary Search Tree; String; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Codec { private int i; private List<String> nums; private final int inf = 1 << 30; // Encodes a tree to a single string. public String serialize(TreeNode root) { nums = new ArrayList<>(); dfs(root); return String.join(" ", nums); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if (data == null || "".equals(data)) { return null; } i = 0; nums = Arrays.asList(data.split(" ")); return dfs(-inf, inf); } private void dfs(TreeNode root) { if (root == null) { return; } nums.add(String.valueOf(root.val)); dfs(root.left); dfs(root.right); } private TreeNode dfs(int mi, int mx) { if (i == nums.size()) { return null; } int x = Integer.parseInt(nums.get(i)); if (x < mi || x > mx) { return null; } TreeNode root = new TreeNode(x); ++i; root.left = dfs(mi, x); root.right = dfs(x, mx); return root; } } // Your Codec object will be instantiated and called as such: // Codec ser = new Codec(); // Codec deser = new Codec(); // String tree = ser.serialize(root); // TreeNode ans = deser.deserialize(tree); // return ans;
449
Serialize and Deserialize BST
Medium
<p>Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p> <p>Design an algorithm to serialize and deserialize a <b>binary search tree</b>. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.</p> <p><b>The encoded string should be as compact as possible.</b></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [2,1,3] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>The input tree is <strong>guaranteed</strong> to be a binary search tree.</li> </ul>
Tree; Depth-First Search; Breadth-First Search; Design; Binary Search Tree; String; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root: Optional[TreeNode]) -> str: """Encodes a tree to a single string.""" def dfs(root: Optional[TreeNode]): if root is None: return nums.append(root.val) dfs(root.left) dfs(root.right) nums = [] dfs(root) return " ".join(map(str, nums)) def deserialize(self, data: str) -> Optional[TreeNode]: """Decodes your encoded data to tree.""" def dfs(mi: int, mx: int) -> Optional[TreeNode]: nonlocal i if i == len(nums) or not mi <= nums[i] <= mx: return None x = nums[i] root = TreeNode(x) i += 1 root.left = dfs(mi, x) root.right = dfs(x, mx) return root nums = list(map(int, data.split())) i = 0 return dfs(-inf, inf) # Your Codec object will be instantiated and called as such: # Your Codec object will be instantiated and called as such: # ser = Codec() # deser = Codec() # tree = ser.serialize(root) # ans = deser.deserialize(tree) # return ans
450
Delete Node in a BST
Medium
<p>Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return <em>the <strong>root node reference</strong> (possibly updated) of the BST</em>.</p> <p>Basically, the deletion can be divided into two stages:</p> <ol> <li>Search for a node to remove.</li> <li>If the node is found, delete the node.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_1.jpg" style="width: 800px; height: 214px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 3 <strong>Output:</strong> [5,4,6,2,null,null,7] <strong>Explanation:</strong> Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the above BST. Please notice that another valid answer is [5,2,6,null,4,null,7] and it&#39;s also accepted. <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_supp.jpg" style="width: 350px; height: 255px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 0 <strong>Output:</strong> [5,3,6,2,4,null,7] <strong>Explanation:</strong> The tree does not contain a node with value = 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [], key = 0 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>Each node has a <strong>unique</strong> value.</li> <li><code>root</code> is a valid binary search tree.</li> <li><code>-10<sup>5</sup> &lt;= key &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it with time complexity <code>O(height of tree)</code>?</p>
Tree; Binary Search Tree; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* deleteNode(TreeNode* root, int key) { if (!root) return root; if (root->val > key) { root->left = deleteNode(root->left, key); return root; } if (root->val < key) { root->right = deleteNode(root->right, key); return root; } if (!root->left) return root->right; if (!root->right) return root->left; TreeNode* node = root->right; while (node->left) node = node->left; node->left = root->left; root = root->right; return root; } };
450
Delete Node in a BST
Medium
<p>Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return <em>the <strong>root node reference</strong> (possibly updated) of the BST</em>.</p> <p>Basically, the deletion can be divided into two stages:</p> <ol> <li>Search for a node to remove.</li> <li>If the node is found, delete the node.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_1.jpg" style="width: 800px; height: 214px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 3 <strong>Output:</strong> [5,4,6,2,null,null,7] <strong>Explanation:</strong> Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the above BST. Please notice that another valid answer is [5,2,6,null,4,null,7] and it&#39;s also accepted. <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_supp.jpg" style="width: 350px; height: 255px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 0 <strong>Output:</strong> [5,3,6,2,4,null,7] <strong>Explanation:</strong> The tree does not contain a node with value = 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [], key = 0 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>Each node has a <strong>unique</strong> value.</li> <li><code>root</code> is a valid binary search tree.</li> <li><code>-10<sup>5</sup> &lt;= key &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it with time complexity <code>O(height of tree)</code>?</p>
Tree; Binary Search Tree; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func deleteNode(root *TreeNode, key int) *TreeNode { if root == nil { return nil } if root.Val > key { root.Left = deleteNode(root.Left, key) return root } if root.Val < key { root.Right = deleteNode(root.Right, key) return root } if root.Left == nil { return root.Right } if root.Right == nil { return root.Left } node := root.Right for node.Left != nil { node = node.Left } node.Left = root.Left root = root.Right return root }
450
Delete Node in a BST
Medium
<p>Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return <em>the <strong>root node reference</strong> (possibly updated) of the BST</em>.</p> <p>Basically, the deletion can be divided into two stages:</p> <ol> <li>Search for a node to remove.</li> <li>If the node is found, delete the node.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_1.jpg" style="width: 800px; height: 214px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 3 <strong>Output:</strong> [5,4,6,2,null,null,7] <strong>Explanation:</strong> Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the above BST. Please notice that another valid answer is [5,2,6,null,4,null,7] and it&#39;s also accepted. <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_supp.jpg" style="width: 350px; height: 255px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 0 <strong>Output:</strong> [5,3,6,2,4,null,7] <strong>Explanation:</strong> The tree does not contain a node with value = 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [], key = 0 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>Each node has a <strong>unique</strong> value.</li> <li><code>root</code> is a valid binary search tree.</li> <li><code>-10<sup>5</sup> &lt;= key &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it with time complexity <code>O(height of tree)</code>?</p>
Tree; Binary Search Tree; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode deleteNode(TreeNode root, int key) { if (root == null) { return null; } if (root.val > key) { root.left = deleteNode(root.left, key); return root; } if (root.val < key) { root.right = deleteNode(root.right, key); return root; } if (root.left == null) { return root.right; } if (root.right == null) { return root.left; } TreeNode node = root.right; while (node.left != null) { node = node.left; } node.left = root.left; root = root.right; return root; } }
450
Delete Node in a BST
Medium
<p>Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return <em>the <strong>root node reference</strong> (possibly updated) of the BST</em>.</p> <p>Basically, the deletion can be divided into two stages:</p> <ol> <li>Search for a node to remove.</li> <li>If the node is found, delete the node.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_1.jpg" style="width: 800px; height: 214px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 3 <strong>Output:</strong> [5,4,6,2,null,null,7] <strong>Explanation:</strong> Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the above BST. Please notice that another valid answer is [5,2,6,null,4,null,7] and it&#39;s also accepted. <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_supp.jpg" style="width: 350px; height: 255px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 0 <strong>Output:</strong> [5,3,6,2,4,null,7] <strong>Explanation:</strong> The tree does not contain a node with value = 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [], key = 0 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>Each node has a <strong>unique</strong> value.</li> <li><code>root</code> is a valid binary search tree.</li> <li><code>-10<sup>5</sup> &lt;= key &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it with time complexity <code>O(height of tree)</code>?</p>
Tree; Binary Search Tree; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if root is None: return None if root.val > key: root.left = self.deleteNode(root.left, key) return root if root.val < key: root.right = self.deleteNode(root.right, key) return root if root.left is None: return root.right if root.right is None: return root.left node = root.right while node.left: node = node.left node.left = root.left root = root.right return root
450
Delete Node in a BST
Medium
<p>Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return <em>the <strong>root node reference</strong> (possibly updated) of the BST</em>.</p> <p>Basically, the deletion can be divided into two stages:</p> <ol> <li>Search for a node to remove.</li> <li>If the node is found, delete the node.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_1.jpg" style="width: 800px; height: 214px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 3 <strong>Output:</strong> [5,4,6,2,null,null,7] <strong>Explanation:</strong> Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the above BST. Please notice that another valid answer is [5,2,6,null,4,null,7] and it&#39;s also accepted. <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_supp.jpg" style="width: 350px; height: 255px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 0 <strong>Output:</strong> [5,3,6,2,4,null,7] <strong>Explanation:</strong> The tree does not contain a node with value = 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [], key = 0 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>Each node has a <strong>unique</strong> value.</li> <li><code>root</code> is a valid binary search tree.</li> <li><code>-10<sup>5</sup> &lt;= key &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it with time complexity <code>O(height of tree)</code>?</p>
Tree; Binary Search Tree; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { fn dfs(root: &Option<Rc<RefCell<TreeNode>>>) -> i32 { let node = root.as_ref().unwrap().borrow(); if node.left.is_none() { return node.val; } Self::dfs(&node.left) } pub fn delete_node( mut root: Option<Rc<RefCell<TreeNode>>>, key: i32, ) -> Option<Rc<RefCell<TreeNode>>> { if root.is_some() { let mut node = root.as_mut().unwrap().borrow_mut(); match node.val.cmp(&key) { std::cmp::Ordering::Less => { node.right = Self::delete_node(node.right.take(), key); } std::cmp::Ordering::Greater => { node.left = Self::delete_node(node.left.take(), key); } std::cmp::Ordering::Equal => { match (node.left.is_some(), node.right.is_some()) { (false, false) => { return None; } (true, false) => { return node.left.take(); } (false, true) => { return node.right.take(); } (true, true) => { if node.right.as_ref().unwrap().borrow().left.is_none() { let mut r = node.right.take(); r.as_mut().unwrap().borrow_mut().left = node.left.take(); return r; } else { let val = Self::dfs(&node.right); node.val = val; node.right = Self::delete_node(node.right.take(), val); } } }; } } } root } }
450
Delete Node in a BST
Medium
<p>Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return <em>the <strong>root node reference</strong> (possibly updated) of the BST</em>.</p> <p>Basically, the deletion can be divided into two stages:</p> <ol> <li>Search for a node to remove.</li> <li>If the node is found, delete the node.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_1.jpg" style="width: 800px; height: 214px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 3 <strong>Output:</strong> [5,4,6,2,null,null,7] <strong>Explanation:</strong> Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the above BST. Please notice that another valid answer is [5,2,6,null,4,null,7] and it&#39;s also accepted. <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_supp.jpg" style="width: 350px; height: 255px;" /> </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 0 <strong>Output:</strong> [5,3,6,2,4,null,7] <strong>Explanation:</strong> The tree does not contain a node with value = 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [], key = 0 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>Each node has a <strong>unique</strong> value.</li> <li><code>root</code> is a valid binary search tree.</li> <li><code>-10<sup>5</sup> &lt;= key &lt;= 10<sup>5</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it with time complexity <code>O(height of tree)</code>?</p>
Tree; Binary Search Tree; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function deleteNode(root: TreeNode | null, key: number): TreeNode | null { if (root == null) { return root; } const { val, left, right } = root; if (val > key) { root.left = deleteNode(left, key); } else if (val < key) { root.right = deleteNode(right, key); } else { if (left == null && right == null) { root = null; } else if (left == null || right == null) { root = left || right; } else { if (right.left == null) { right.left = left; root = right; } else { let minPreNode = right; while (minPreNode.left.left != null) { minPreNode = minPreNode.left; } const minVal = minPreNode.left.val; root.val = minVal; minPreNode.left = deleteNode(minPreNode.left, minVal); } } } return root; }
451
Sort Characters By Frequency
Medium
<p>Given a string <code>s</code>, sort it in <strong>decreasing order</strong> based on the <strong>frequency</strong> of the characters. The <strong>frequency</strong> of a character is the number of times it appears in the string.</p> <p>Return <em>the sorted string</em>. If there are multiple answers, return <em>any of them</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;tree&quot; <strong>Output:</strong> &quot;eert&quot; <strong>Explanation:</strong> &#39;e&#39; appears twice while &#39;r&#39; and &#39;t&#39; both appear once. So &#39;e&#39; must appear before both &#39;r&#39; and &#39;t&#39;. Therefore &quot;eetr&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cccaaa&quot; <strong>Output:</strong> &quot;aaaccc&quot; <strong>Explanation:</strong> Both &#39;c&#39; and &#39;a&#39; appear three times, so both &quot;cccaaa&quot; and &quot;aaaccc&quot; are valid answers. Note that &quot;cacaca&quot; is incorrect, as the same characters must be together. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;Aabb&quot; <strong>Output:</strong> &quot;bbAa&quot; <strong>Explanation:</strong> &quot;bbaA&quot; is also a valid answer, but &quot;Aabb&quot; is incorrect. Note that &#39;A&#39; and &#39;a&#39; are treated as two different characters. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>s</code> consists of uppercase and lowercase English letters and digits.</li> </ul>
Hash Table; String; Bucket Sort; Counting; Sorting; Heap (Priority Queue)
C++
class Solution { public: string frequencySort(string s) { unordered_map<char, int> cnt; for (char& c : s) { ++cnt[c]; } vector<char> cs; for (auto& [c, _] : cnt) { cs.push_back(c); } sort(cs.begin(), cs.end(), [&](char& a, char& b) { return cnt[a] > cnt[b]; }); string ans; for (char& c : cs) { ans += string(cnt[c], c); } return ans; } };
451
Sort Characters By Frequency
Medium
<p>Given a string <code>s</code>, sort it in <strong>decreasing order</strong> based on the <strong>frequency</strong> of the characters. The <strong>frequency</strong> of a character is the number of times it appears in the string.</p> <p>Return <em>the sorted string</em>. If there are multiple answers, return <em>any of them</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;tree&quot; <strong>Output:</strong> &quot;eert&quot; <strong>Explanation:</strong> &#39;e&#39; appears twice while &#39;r&#39; and &#39;t&#39; both appear once. So &#39;e&#39; must appear before both &#39;r&#39; and &#39;t&#39;. Therefore &quot;eetr&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cccaaa&quot; <strong>Output:</strong> &quot;aaaccc&quot; <strong>Explanation:</strong> Both &#39;c&#39; and &#39;a&#39; appear three times, so both &quot;cccaaa&quot; and &quot;aaaccc&quot; are valid answers. Note that &quot;cacaca&quot; is incorrect, as the same characters must be together. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;Aabb&quot; <strong>Output:</strong> &quot;bbAa&quot; <strong>Explanation:</strong> &quot;bbaA&quot; is also a valid answer, but &quot;Aabb&quot; is incorrect. Note that &#39;A&#39; and &#39;a&#39; are treated as two different characters. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>s</code> consists of uppercase and lowercase English letters and digits.</li> </ul>
Hash Table; String; Bucket Sort; Counting; Sorting; Heap (Priority Queue)
Go
func frequencySort(s string) string { cnt := map[byte]int{} for i := range s { cnt[s[i]]++ } cs := make([]byte, 0, len(s)) for c := range cnt { cs = append(cs, c) } sort.Slice(cs, func(i, j int) bool { return cnt[cs[i]] > cnt[cs[j]] }) ans := make([]byte, 0, len(s)) for _, c := range cs { ans = append(ans, bytes.Repeat([]byte{c}, cnt[c])...) } return string(ans) }
451
Sort Characters By Frequency
Medium
<p>Given a string <code>s</code>, sort it in <strong>decreasing order</strong> based on the <strong>frequency</strong> of the characters. The <strong>frequency</strong> of a character is the number of times it appears in the string.</p> <p>Return <em>the sorted string</em>. If there are multiple answers, return <em>any of them</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;tree&quot; <strong>Output:</strong> &quot;eert&quot; <strong>Explanation:</strong> &#39;e&#39; appears twice while &#39;r&#39; and &#39;t&#39; both appear once. So &#39;e&#39; must appear before both &#39;r&#39; and &#39;t&#39;. Therefore &quot;eetr&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cccaaa&quot; <strong>Output:</strong> &quot;aaaccc&quot; <strong>Explanation:</strong> Both &#39;c&#39; and &#39;a&#39; appear three times, so both &quot;cccaaa&quot; and &quot;aaaccc&quot; are valid answers. Note that &quot;cacaca&quot; is incorrect, as the same characters must be together. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;Aabb&quot; <strong>Output:</strong> &quot;bbAa&quot; <strong>Explanation:</strong> &quot;bbaA&quot; is also a valid answer, but &quot;Aabb&quot; is incorrect. Note that &#39;A&#39; and &#39;a&#39; are treated as two different characters. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>s</code> consists of uppercase and lowercase English letters and digits.</li> </ul>
Hash Table; String; Bucket Sort; Counting; Sorting; Heap (Priority Queue)
Java
class Solution { public String frequencySort(String s) { Map<Character, Integer> cnt = new HashMap<>(52); for (int i = 0; i < s.length(); ++i) { cnt.merge(s.charAt(i), 1, Integer::sum); } List<Character> cs = new ArrayList<>(cnt.keySet()); cs.sort((a, b) -> cnt.get(b) - cnt.get(a)); StringBuilder ans = new StringBuilder(); for (char c : cs) { for (int v = cnt.get(c); v > 0; --v) { ans.append(c); } } return ans.toString(); } }
451
Sort Characters By Frequency
Medium
<p>Given a string <code>s</code>, sort it in <strong>decreasing order</strong> based on the <strong>frequency</strong> of the characters. The <strong>frequency</strong> of a character is the number of times it appears in the string.</p> <p>Return <em>the sorted string</em>. If there are multiple answers, return <em>any of them</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;tree&quot; <strong>Output:</strong> &quot;eert&quot; <strong>Explanation:</strong> &#39;e&#39; appears twice while &#39;r&#39; and &#39;t&#39; both appear once. So &#39;e&#39; must appear before both &#39;r&#39; and &#39;t&#39;. Therefore &quot;eetr&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cccaaa&quot; <strong>Output:</strong> &quot;aaaccc&quot; <strong>Explanation:</strong> Both &#39;c&#39; and &#39;a&#39; appear three times, so both &quot;cccaaa&quot; and &quot;aaaccc&quot; are valid answers. Note that &quot;cacaca&quot; is incorrect, as the same characters must be together. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;Aabb&quot; <strong>Output:</strong> &quot;bbAa&quot; <strong>Explanation:</strong> &quot;bbaA&quot; is also a valid answer, but &quot;Aabb&quot; is incorrect. Note that &#39;A&#39; and &#39;a&#39; are treated as two different characters. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>s</code> consists of uppercase and lowercase English letters and digits.</li> </ul>
Hash Table; String; Bucket Sort; Counting; Sorting; Heap (Priority Queue)
PHP
class Solution { /** * @param String $s * @return String */ function frequencySort($s) { $cnt = array_count_values(str_split($s)); $cs = array_keys($cnt); usort($cs, function ($a, $b) use ($cnt) { return $cnt[$b] <=> $cnt[$a]; }); $ans = ''; foreach ($cs as $c) { $ans .= str_repeat($c, $cnt[$c]); } return $ans; } }
451
Sort Characters By Frequency
Medium
<p>Given a string <code>s</code>, sort it in <strong>decreasing order</strong> based on the <strong>frequency</strong> of the characters. The <strong>frequency</strong> of a character is the number of times it appears in the string.</p> <p>Return <em>the sorted string</em>. If there are multiple answers, return <em>any of them</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;tree&quot; <strong>Output:</strong> &quot;eert&quot; <strong>Explanation:</strong> &#39;e&#39; appears twice while &#39;r&#39; and &#39;t&#39; both appear once. So &#39;e&#39; must appear before both &#39;r&#39; and &#39;t&#39;. Therefore &quot;eetr&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cccaaa&quot; <strong>Output:</strong> &quot;aaaccc&quot; <strong>Explanation:</strong> Both &#39;c&#39; and &#39;a&#39; appear three times, so both &quot;cccaaa&quot; and &quot;aaaccc&quot; are valid answers. Note that &quot;cacaca&quot; is incorrect, as the same characters must be together. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;Aabb&quot; <strong>Output:</strong> &quot;bbAa&quot; <strong>Explanation:</strong> &quot;bbaA&quot; is also a valid answer, but &quot;Aabb&quot; is incorrect. Note that &#39;A&#39; and &#39;a&#39; are treated as two different characters. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>s</code> consists of uppercase and lowercase English letters and digits.</li> </ul>
Hash Table; String; Bucket Sort; Counting; Sorting; Heap (Priority Queue)
Python
class Solution: def frequencySort(self, s: str) -> str: cnt = Counter(s) return ''.join(c * v for c, v in sorted(cnt.items(), key=lambda x: -x[1]))
451
Sort Characters By Frequency
Medium
<p>Given a string <code>s</code>, sort it in <strong>decreasing order</strong> based on the <strong>frequency</strong> of the characters. The <strong>frequency</strong> of a character is the number of times it appears in the string.</p> <p>Return <em>the sorted string</em>. If there are multiple answers, return <em>any of them</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;tree&quot; <strong>Output:</strong> &quot;eert&quot; <strong>Explanation:</strong> &#39;e&#39; appears twice while &#39;r&#39; and &#39;t&#39; both appear once. So &#39;e&#39; must appear before both &#39;r&#39; and &#39;t&#39;. Therefore &quot;eetr&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cccaaa&quot; <strong>Output:</strong> &quot;aaaccc&quot; <strong>Explanation:</strong> Both &#39;c&#39; and &#39;a&#39; appear three times, so both &quot;cccaaa&quot; and &quot;aaaccc&quot; are valid answers. Note that &quot;cacaca&quot; is incorrect, as the same characters must be together. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;Aabb&quot; <strong>Output:</strong> &quot;bbAa&quot; <strong>Explanation:</strong> &quot;bbaA&quot; is also a valid answer, but &quot;Aabb&quot; is incorrect. Note that &#39;A&#39; and &#39;a&#39; are treated as two different characters. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>s</code> consists of uppercase and lowercase English letters and digits.</li> </ul>
Hash Table; String; Bucket Sort; Counting; Sorting; Heap (Priority Queue)
Rust
use std::collections::HashMap; impl Solution { pub fn frequency_sort(s: String) -> String { let mut cnt = HashMap::new(); for c in s.chars() { cnt.insert(c, cnt.get(&c).unwrap_or(&0) + 1); } let mut cs = cnt.into_iter().collect::<Vec<(char, i32)>>(); cs.sort_unstable_by(|(_, a), (_, b)| b.cmp(&a)); cs.into_iter() .map(|(c, v)| vec![c; v as usize].into_iter().collect::<String>()) .collect() } }
451
Sort Characters By Frequency
Medium
<p>Given a string <code>s</code>, sort it in <strong>decreasing order</strong> based on the <strong>frequency</strong> of the characters. The <strong>frequency</strong> of a character is the number of times it appears in the string.</p> <p>Return <em>the sorted string</em>. If there are multiple answers, return <em>any of them</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;tree&quot; <strong>Output:</strong> &quot;eert&quot; <strong>Explanation:</strong> &#39;e&#39; appears twice while &#39;r&#39; and &#39;t&#39; both appear once. So &#39;e&#39; must appear before both &#39;r&#39; and &#39;t&#39;. Therefore &quot;eetr&quot; is also a valid answer. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;cccaaa&quot; <strong>Output:</strong> &quot;aaaccc&quot; <strong>Explanation:</strong> Both &#39;c&#39; and &#39;a&#39; appear three times, so both &quot;cccaaa&quot; and &quot;aaaccc&quot; are valid answers. Note that &quot;cacaca&quot; is incorrect, as the same characters must be together. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;Aabb&quot; <strong>Output:</strong> &quot;bbAa&quot; <strong>Explanation:</strong> &quot;bbaA&quot; is also a valid answer, but &quot;Aabb&quot; is incorrect. Note that &#39;A&#39; and &#39;a&#39; are treated as two different characters. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li> <li><code>s</code> consists of uppercase and lowercase English letters and digits.</li> </ul>
Hash Table; String; Bucket Sort; Counting; Sorting; Heap (Priority Queue)
TypeScript
function frequencySort(s: string): string { const cnt: Map<string, number> = new Map(); for (const c of s) { cnt.set(c, (cnt.get(c) || 0) + 1); } const cs = Array.from(cnt.keys()).sort((a, b) => cnt.get(b)! - cnt.get(a)!); const ans: string[] = []; for (const c of cs) { ans.push(c.repeat(cnt.get(c)!)); } return ans.join(''); }
452
Minimum Number of Arrows to Burst Balloons
Medium
<p>There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array <code>points</code> where <code>points[i] = [x<sub>start</sub>, x<sub>end</sub>]</code> denotes a balloon whose <strong>horizontal diameter</strong> stretches between <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code>. You do not know the exact y-coordinates of the balloons.</p> <p>Arrows can be shot up <strong>directly vertically</strong> (in the positive y-direction) from different points along the x-axis. A balloon with <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code> is <strong>burst</strong> by an arrow shot at <code>x</code> if <code>x<sub>start</sub> &lt;= x &lt;= x<sub>end</sub></code>. There is <strong>no limit</strong> to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.</p> <p>Given the array <code>points</code>, return <em>the <strong>minimum</strong> number of arrows that must be shot to burst all balloons</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> points = [[10,16],[2,8],[1,6],[7,12]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> points = [[1,2],[3,4],[5,6],[7,8]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One arrow needs to be shot for each balloon for a total of 4 arrows. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> points = [[1,2],[2,3],[3,4],[4,5]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= points.length &lt;= 10<sup>5</sup></code></li> <li><code>points[i].length == 2</code></li> <li><code>-2<sup>31</sup> &lt;= x<sub>start</sub> &lt; x<sub>end</sub> &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Array; Sorting
C++
class Solution { public: int findMinArrowShots(vector<vector<int>>& points) { sort(points.begin(), points.end(), [](vector<int>& a, vector<int>& b) { return a[1] < b[1]; }); int ans = 0; long long last = -(1LL << 60); for (auto& p : points) { int a = p[0], b = p[1]; if (a > last) { ++ans; last = b; } } return ans; } };
452
Minimum Number of Arrows to Burst Balloons
Medium
<p>There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array <code>points</code> where <code>points[i] = [x<sub>start</sub>, x<sub>end</sub>]</code> denotes a balloon whose <strong>horizontal diameter</strong> stretches between <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code>. You do not know the exact y-coordinates of the balloons.</p> <p>Arrows can be shot up <strong>directly vertically</strong> (in the positive y-direction) from different points along the x-axis. A balloon with <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code> is <strong>burst</strong> by an arrow shot at <code>x</code> if <code>x<sub>start</sub> &lt;= x &lt;= x<sub>end</sub></code>. There is <strong>no limit</strong> to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.</p> <p>Given the array <code>points</code>, return <em>the <strong>minimum</strong> number of arrows that must be shot to burst all balloons</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> points = [[10,16],[2,8],[1,6],[7,12]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> points = [[1,2],[3,4],[5,6],[7,8]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One arrow needs to be shot for each balloon for a total of 4 arrows. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> points = [[1,2],[2,3],[3,4],[4,5]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= points.length &lt;= 10<sup>5</sup></code></li> <li><code>points[i].length == 2</code></li> <li><code>-2<sup>31</sup> &lt;= x<sub>start</sub> &lt; x<sub>end</sub> &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Array; Sorting
C#
public class Solution { public int FindMinArrowShots(int[][] points) { Array.Sort(points, (a, b) => a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0); int ans = 0; long last = long.MinValue; foreach (var point in points) { if (point[0] > last) { ++ans; last = point[1]; } } return ans; } }
452
Minimum Number of Arrows to Burst Balloons
Medium
<p>There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array <code>points</code> where <code>points[i] = [x<sub>start</sub>, x<sub>end</sub>]</code> denotes a balloon whose <strong>horizontal diameter</strong> stretches between <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code>. You do not know the exact y-coordinates of the balloons.</p> <p>Arrows can be shot up <strong>directly vertically</strong> (in the positive y-direction) from different points along the x-axis. A balloon with <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code> is <strong>burst</strong> by an arrow shot at <code>x</code> if <code>x<sub>start</sub> &lt;= x &lt;= x<sub>end</sub></code>. There is <strong>no limit</strong> to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.</p> <p>Given the array <code>points</code>, return <em>the <strong>minimum</strong> number of arrows that must be shot to burst all balloons</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> points = [[10,16],[2,8],[1,6],[7,12]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> points = [[1,2],[3,4],[5,6],[7,8]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One arrow needs to be shot for each balloon for a total of 4 arrows. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> points = [[1,2],[2,3],[3,4],[4,5]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= points.length &lt;= 10<sup>5</sup></code></li> <li><code>points[i].length == 2</code></li> <li><code>-2<sup>31</sup> &lt;= x<sub>start</sub> &lt; x<sub>end</sub> &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Array; Sorting
Go
func findMinArrowShots(points [][]int) (ans int) { sort.Slice(points, func(i, j int) bool { return points[i][1] < points[j][1] }) last := -(1 << 60) for _, p := range points { a, b := p[0], p[1] if a > last { ans++ last = b } } return }
452
Minimum Number of Arrows to Burst Balloons
Medium
<p>There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array <code>points</code> where <code>points[i] = [x<sub>start</sub>, x<sub>end</sub>]</code> denotes a balloon whose <strong>horizontal diameter</strong> stretches between <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code>. You do not know the exact y-coordinates of the balloons.</p> <p>Arrows can be shot up <strong>directly vertically</strong> (in the positive y-direction) from different points along the x-axis. A balloon with <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code> is <strong>burst</strong> by an arrow shot at <code>x</code> if <code>x<sub>start</sub> &lt;= x &lt;= x<sub>end</sub></code>. There is <strong>no limit</strong> to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.</p> <p>Given the array <code>points</code>, return <em>the <strong>minimum</strong> number of arrows that must be shot to burst all balloons</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> points = [[10,16],[2,8],[1,6],[7,12]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> points = [[1,2],[3,4],[5,6],[7,8]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One arrow needs to be shot for each balloon for a total of 4 arrows. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> points = [[1,2],[2,3],[3,4],[4,5]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= points.length &lt;= 10<sup>5</sup></code></li> <li><code>points[i].length == 2</code></li> <li><code>-2<sup>31</sup> &lt;= x<sub>start</sub> &lt; x<sub>end</sub> &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Array; Sorting
Java
class Solution { public int findMinArrowShots(int[][] points) { // 直接 a[1] - b[1] 可能会溢出 Arrays.sort(points, Comparator.comparingInt(a -> a[1])); int ans = 0; long last = -(1L << 60); for (var p : points) { int a = p[0], b = p[1]; if (a > last) { ++ans; last = b; } } return ans; } }
452
Minimum Number of Arrows to Burst Balloons
Medium
<p>There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array <code>points</code> where <code>points[i] = [x<sub>start</sub>, x<sub>end</sub>]</code> denotes a balloon whose <strong>horizontal diameter</strong> stretches between <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code>. You do not know the exact y-coordinates of the balloons.</p> <p>Arrows can be shot up <strong>directly vertically</strong> (in the positive y-direction) from different points along the x-axis. A balloon with <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code> is <strong>burst</strong> by an arrow shot at <code>x</code> if <code>x<sub>start</sub> &lt;= x &lt;= x<sub>end</sub></code>. There is <strong>no limit</strong> to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.</p> <p>Given the array <code>points</code>, return <em>the <strong>minimum</strong> number of arrows that must be shot to burst all balloons</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> points = [[10,16],[2,8],[1,6],[7,12]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> points = [[1,2],[3,4],[5,6],[7,8]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One arrow needs to be shot for each balloon for a total of 4 arrows. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> points = [[1,2],[2,3],[3,4],[4,5]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= points.length &lt;= 10<sup>5</sup></code></li> <li><code>points[i].length == 2</code></li> <li><code>-2<sup>31</sup> &lt;= x<sub>start</sub> &lt; x<sub>end</sub> &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Array; Sorting
Python
class Solution: def findMinArrowShots(self, points: List[List[int]]) -> int: ans, last = 0, -inf for a, b in sorted(points, key=lambda x: x[1]): if a > last: ans += 1 last = b return ans
452
Minimum Number of Arrows to Burst Balloons
Medium
<p>There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array <code>points</code> where <code>points[i] = [x<sub>start</sub>, x<sub>end</sub>]</code> denotes a balloon whose <strong>horizontal diameter</strong> stretches between <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code>. You do not know the exact y-coordinates of the balloons.</p> <p>Arrows can be shot up <strong>directly vertically</strong> (in the positive y-direction) from different points along the x-axis. A balloon with <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code> is <strong>burst</strong> by an arrow shot at <code>x</code> if <code>x<sub>start</sub> &lt;= x &lt;= x<sub>end</sub></code>. There is <strong>no limit</strong> to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.</p> <p>Given the array <code>points</code>, return <em>the <strong>minimum</strong> number of arrows that must be shot to burst all balloons</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> points = [[10,16],[2,8],[1,6],[7,12]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. - Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> points = [[1,2],[3,4],[5,6],[7,8]] <strong>Output:</strong> 4 <strong>Explanation:</strong> One arrow needs to be shot for each balloon for a total of 4 arrows. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> points = [[1,2],[2,3],[3,4],[4,5]] <strong>Output:</strong> 2 <strong>Explanation:</strong> The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. - Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= points.length &lt;= 10<sup>5</sup></code></li> <li><code>points[i].length == 2</code></li> <li><code>-2<sup>31</sup> &lt;= x<sub>start</sub> &lt; x<sub>end</sub> &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Array; Sorting
TypeScript
function findMinArrowShots(points: number[][]): number { points.sort((a, b) => a[1] - b[1]); let ans = 0; let last = -Infinity; for (const [a, b] of points) { if (last < a) { ans++; last = b; } } return ans; }
453
Minimum Moves to Equal Array Elements
Medium
<p>Given an integer array <code>nums</code> of size <code>n</code>, return <em>the minimum number of moves required to make all array elements equal</em>.</p> <p>In one move, you can increment <code>n - 1</code> elements of the array by <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> Only three moves are needed (remember each move increments two elements): [1,2,3] =&gt; [2,3,3] =&gt; [3,4,3] =&gt; [4,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>The answer is guaranteed to fit in a <strong>32-bit</strong> integer.</li> </ul>
Array; Math
C++
class Solution { public: int minMoves(vector<int>& nums) { int s = 0; int mi = 1 << 30; for (int x : nums) { s += x; mi = min(mi, x); } return s - mi * nums.size(); } };
453
Minimum Moves to Equal Array Elements
Medium
<p>Given an integer array <code>nums</code> of size <code>n</code>, return <em>the minimum number of moves required to make all array elements equal</em>.</p> <p>In one move, you can increment <code>n - 1</code> elements of the array by <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> Only three moves are needed (remember each move increments two elements): [1,2,3] =&gt; [2,3,3] =&gt; [3,4,3] =&gt; [4,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>The answer is guaranteed to fit in a <strong>32-bit</strong> integer.</li> </ul>
Array; Math
Go
func minMoves(nums []int) int { mi := 1 << 30 s := 0 for _, x := range nums { s += x if x < mi { mi = x } } return s - mi*len(nums) }
453
Minimum Moves to Equal Array Elements
Medium
<p>Given an integer array <code>nums</code> of size <code>n</code>, return <em>the minimum number of moves required to make all array elements equal</em>.</p> <p>In one move, you can increment <code>n - 1</code> elements of the array by <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> Only three moves are needed (remember each move increments two elements): [1,2,3] =&gt; [2,3,3] =&gt; [3,4,3] =&gt; [4,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>The answer is guaranteed to fit in a <strong>32-bit</strong> integer.</li> </ul>
Array; Math
Java
class Solution { public int minMoves(int[] nums) { return Arrays.stream(nums).sum() - Arrays.stream(nums).min().getAsInt() * nums.length; } }
453
Minimum Moves to Equal Array Elements
Medium
<p>Given an integer array <code>nums</code> of size <code>n</code>, return <em>the minimum number of moves required to make all array elements equal</em>.</p> <p>In one move, you can increment <code>n - 1</code> elements of the array by <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> Only three moves are needed (remember each move increments two elements): [1,2,3] =&gt; [2,3,3] =&gt; [3,4,3] =&gt; [4,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>The answer is guaranteed to fit in a <strong>32-bit</strong> integer.</li> </ul>
Array; Math
Python
class Solution: def minMoves(self, nums: List[int]) -> int: return sum(nums) - min(nums) * len(nums)
453
Minimum Moves to Equal Array Elements
Medium
<p>Given an integer array <code>nums</code> of size <code>n</code>, return <em>the minimum number of moves required to make all array elements equal</em>.</p> <p>In one move, you can increment <code>n - 1</code> elements of the array by <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> 3 <strong>Explanation:</strong> Only three moves are needed (remember each move increments two elements): [1,2,3] =&gt; [2,3,3] =&gt; [3,4,3] =&gt; [4,4,4] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,1] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li>The answer is guaranteed to fit in a <strong>32-bit</strong> integer.</li> </ul>
Array; Math
TypeScript
function minMoves(nums: number[]): number { let mi = 1 << 30; let s = 0; for (const x of nums) { s += x; mi = Math.min(mi, x); } return s - mi * nums.length; }
454
4Sum II
Medium
<p>Given four integer arrays <code>nums1</code>, <code>nums2</code>, <code>nums3</code>, and <code>nums4</code> all of length <code>n</code>, return the number of tuples <code>(i, j, k, l)</code> such that:</p> <ul> <li><code>0 &lt;= i, j, k, l &lt; n</code></li> <li><code>nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two tuples are: 1. (0, 0, 0, 1) -&gt; nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -&gt; nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length</code></li> <li><code>n == nums2.length</code></li> <li><code>n == nums3.length</code></li> <li><code>n == nums4.length</code></li> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>-2<sup>28</sup> &lt;= nums1[i], nums2[i], nums3[i], nums4[i] &lt;= 2<sup>28</sup></code></li> </ul>
Array; Hash Table
C++
class Solution { public: int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) { unordered_map<int, int> cnt; for (int a : nums1) { for (int b : nums2) { ++cnt[a + b]; } } int ans = 0; for (int c : nums3) { for (int d : nums4) { ans += cnt[-(c + d)]; } } return ans; } };
454
4Sum II
Medium
<p>Given four integer arrays <code>nums1</code>, <code>nums2</code>, <code>nums3</code>, and <code>nums4</code> all of length <code>n</code>, return the number of tuples <code>(i, j, k, l)</code> such that:</p> <ul> <li><code>0 &lt;= i, j, k, l &lt; n</code></li> <li><code>nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two tuples are: 1. (0, 0, 0, 1) -&gt; nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -&gt; nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length</code></li> <li><code>n == nums2.length</code></li> <li><code>n == nums3.length</code></li> <li><code>n == nums4.length</code></li> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>-2<sup>28</sup> &lt;= nums1[i], nums2[i], nums3[i], nums4[i] &lt;= 2<sup>28</sup></code></li> </ul>
Array; Hash Table
Go
func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) (ans int) { cnt := map[int]int{} for _, a := range nums1 { for _, b := range nums2 { cnt[a+b]++ } } for _, c := range nums3 { for _, d := range nums4 { ans += cnt[-(c + d)] } } return }
454
4Sum II
Medium
<p>Given four integer arrays <code>nums1</code>, <code>nums2</code>, <code>nums3</code>, and <code>nums4</code> all of length <code>n</code>, return the number of tuples <code>(i, j, k, l)</code> such that:</p> <ul> <li><code>0 &lt;= i, j, k, l &lt; n</code></li> <li><code>nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two tuples are: 1. (0, 0, 0, 1) -&gt; nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -&gt; nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length</code></li> <li><code>n == nums2.length</code></li> <li><code>n == nums3.length</code></li> <li><code>n == nums4.length</code></li> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>-2<sup>28</sup> &lt;= nums1[i], nums2[i], nums3[i], nums4[i] &lt;= 2<sup>28</sup></code></li> </ul>
Array; Hash Table
Java
class Solution { public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { Map<Integer, Integer> cnt = new HashMap<>(); for (int a : nums1) { for (int b : nums2) { cnt.merge(a + b, 1, Integer::sum); } } int ans = 0; for (int c : nums3) { for (int d : nums4) { ans += cnt.getOrDefault(-(c + d), 0); } } return ans; } }
454
4Sum II
Medium
<p>Given four integer arrays <code>nums1</code>, <code>nums2</code>, <code>nums3</code>, and <code>nums4</code> all of length <code>n</code>, return the number of tuples <code>(i, j, k, l)</code> such that:</p> <ul> <li><code>0 &lt;= i, j, k, l &lt; n</code></li> <li><code>nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two tuples are: 1. (0, 0, 0, 1) -&gt; nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -&gt; nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length</code></li> <li><code>n == nums2.length</code></li> <li><code>n == nums3.length</code></li> <li><code>n == nums4.length</code></li> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>-2<sup>28</sup> &lt;= nums1[i], nums2[i], nums3[i], nums4[i] &lt;= 2<sup>28</sup></code></li> </ul>
Array; Hash Table
Python
class Solution: def fourSumCount( self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int] ) -> int: cnt = Counter(a + b for a in nums1 for b in nums2) return sum(cnt[-(c + d)] for c in nums3 for d in nums4)
454
4Sum II
Medium
<p>Given four integer arrays <code>nums1</code>, <code>nums2</code>, <code>nums3</code>, and <code>nums4</code> all of length <code>n</code>, return the number of tuples <code>(i, j, k, l)</code> such that:</p> <ul> <li><code>0 &lt;= i, j, k, l &lt; n</code></li> <li><code>nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two tuples are: 1. (0, 0, 0, 1) -&gt; nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -&gt; nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length</code></li> <li><code>n == nums2.length</code></li> <li><code>n == nums3.length</code></li> <li><code>n == nums4.length</code></li> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>-2<sup>28</sup> &lt;= nums1[i], nums2[i], nums3[i], nums4[i] &lt;= 2<sup>28</sup></code></li> </ul>
Array; Hash Table
Rust
use std::collections::HashMap; impl Solution { pub fn four_sum_count( nums1: Vec<i32>, nums2: Vec<i32>, nums3: Vec<i32>, nums4: Vec<i32>, ) -> i32 { let mut cnt = HashMap::new(); for &a in &nums1 { for &b in &nums2 { *cnt.entry(a + b).or_insert(0) += 1; } } let mut ans = 0; for &c in &nums3 { for &d in &nums4 { if let Some(&count) = cnt.get(&(0 - (c + d))) { ans += count; } } } ans } }
454
4Sum II
Medium
<p>Given four integer arrays <code>nums1</code>, <code>nums2</code>, <code>nums3</code>, and <code>nums4</code> all of length <code>n</code>, return the number of tuples <code>(i, j, k, l)</code> such that:</p> <ul> <li><code>0 &lt;= i, j, k, l &lt; n</code></li> <li><code>nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] <strong>Output:</strong> 2 <strong>Explanation:</strong> The two tuples are: 1. (0, 0, 0, 1) -&gt; nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -&gt; nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums1.length</code></li> <li><code>n == nums2.length</code></li> <li><code>n == nums3.length</code></li> <li><code>n == nums4.length</code></li> <li><code>1 &lt;= n &lt;= 200</code></li> <li><code>-2<sup>28</sup> &lt;= nums1[i], nums2[i], nums3[i], nums4[i] &lt;= 2<sup>28</sup></code></li> </ul>
Array; Hash Table
TypeScript
function fourSumCount(nums1: number[], nums2: number[], nums3: number[], nums4: number[]): number { const cnt: Record<number, number> = {}; for (const a of nums1) { for (const b of nums2) { const x = a + b; cnt[x] = (cnt[x] || 0) + 1; } } let ans = 0; for (const c of nums3) { for (const d of nums4) { const x = c + d; ans += cnt[-x] || 0; } } return ans; }
455
Assign Cookies
Easy
<p>Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.</p> <p>Each child <code>i</code> has a greed factor <code>g[i]</code>, which is the minimum size of a cookie that the child will be content with; and each cookie <code>j</code> has a size <code>s[j]</code>. If <code>s[j] &gt;= g[i]</code>, we can assign the cookie <code>j</code> to the child <code>i</code>, and the child <code>i</code> will be content. Your goal is to maximize the number of your content children and output the maximum number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> g = [1,2,3], s = [1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> g = [1,2], s = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= g.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= g[i], s[j] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/maximum-matching-of-players-with-trainers/description/" target="_blank"> 2410: Maximum Matching of Players With Trainers.</a></p>
Greedy; Array; Two Pointers; Sorting
C++
class Solution { public: int findContentChildren(vector<int>& g, vector<int>& s) { sort(g.begin(), g.end()); sort(s.begin(), s.end()); int m = g.size(), n = s.size(); for (int i = 0, j = 0; i < m; ++i) { while (j < n && s[j] < g[i]) { ++j; } if (j++ >= n) { return i; } } return m; } };
455
Assign Cookies
Easy
<p>Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.</p> <p>Each child <code>i</code> has a greed factor <code>g[i]</code>, which is the minimum size of a cookie that the child will be content with; and each cookie <code>j</code> has a size <code>s[j]</code>. If <code>s[j] &gt;= g[i]</code>, we can assign the cookie <code>j</code> to the child <code>i</code>, and the child <code>i</code> will be content. Your goal is to maximize the number of your content children and output the maximum number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> g = [1,2,3], s = [1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> g = [1,2], s = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= g.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= g[i], s[j] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/maximum-matching-of-players-with-trainers/description/" target="_blank"> 2410: Maximum Matching of Players With Trainers.</a></p>
Greedy; Array; Two Pointers; Sorting
Go
func findContentChildren(g []int, s []int) int { sort.Ints(g) sort.Ints(s) j := 0 for i, x := range g { for j < len(s) && s[j] < x { j++ } if j >= len(s) { return i } j++ } return len(g) }
455
Assign Cookies
Easy
<p>Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.</p> <p>Each child <code>i</code> has a greed factor <code>g[i]</code>, which is the minimum size of a cookie that the child will be content with; and each cookie <code>j</code> has a size <code>s[j]</code>. If <code>s[j] &gt;= g[i]</code>, we can assign the cookie <code>j</code> to the child <code>i</code>, and the child <code>i</code> will be content. Your goal is to maximize the number of your content children and output the maximum number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> g = [1,2,3], s = [1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> g = [1,2], s = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= g.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= g[i], s[j] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/maximum-matching-of-players-with-trainers/description/" target="_blank"> 2410: Maximum Matching of Players With Trainers.</a></p>
Greedy; Array; Two Pointers; Sorting
Java
class Solution { public int findContentChildren(int[] g, int[] s) { Arrays.sort(g); Arrays.sort(s); int m = g.length; int n = s.length; for (int i = 0, j = 0; i < m; ++i) { while (j < n && s[j] < g[i]) { ++j; } if (j++ >= n) { return i; } } return m; } }
455
Assign Cookies
Easy
<p>Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.</p> <p>Each child <code>i</code> has a greed factor <code>g[i]</code>, which is the minimum size of a cookie that the child will be content with; and each cookie <code>j</code> has a size <code>s[j]</code>. If <code>s[j] &gt;= g[i]</code>, we can assign the cookie <code>j</code> to the child <code>i</code>, and the child <code>i</code> will be content. Your goal is to maximize the number of your content children and output the maximum number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> g = [1,2,3], s = [1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> g = [1,2], s = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= g.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= g[i], s[j] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/maximum-matching-of-players-with-trainers/description/" target="_blank"> 2410: Maximum Matching of Players With Trainers.</a></p>
Greedy; Array; Two Pointers; Sorting
JavaScript
/** * @param {number[]} g * @param {number[]} s * @return {number} */ var findContentChildren = function (g, s) { g.sort((a, b) => a - b); s.sort((a, b) => a - b); const m = g.length; const n = s.length; for (let i = 0, j = 0; i < m; ++i) { while (j < n && s[j] < g[i]) { ++j; } if (j++ >= n) { return i; } } return m; };
455
Assign Cookies
Easy
<p>Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.</p> <p>Each child <code>i</code> has a greed factor <code>g[i]</code>, which is the minimum size of a cookie that the child will be content with; and each cookie <code>j</code> has a size <code>s[j]</code>. If <code>s[j] &gt;= g[i]</code>, we can assign the cookie <code>j</code> to the child <code>i</code>, and the child <code>i</code> will be content. Your goal is to maximize the number of your content children and output the maximum number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> g = [1,2,3], s = [1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> g = [1,2], s = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= g.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= g[i], s[j] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/maximum-matching-of-players-with-trainers/description/" target="_blank"> 2410: Maximum Matching of Players With Trainers.</a></p>
Greedy; Array; Two Pointers; Sorting
Python
class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort() s.sort() j = 0 for i, x in enumerate(g): while j < len(s) and s[j] < g[i]: j += 1 if j >= len(s): return i j += 1 return len(g)
455
Assign Cookies
Easy
<p>Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.</p> <p>Each child <code>i</code> has a greed factor <code>g[i]</code>, which is the minimum size of a cookie that the child will be content with; and each cookie <code>j</code> has a size <code>s[j]</code>. If <code>s[j] &gt;= g[i]</code>, we can assign the cookie <code>j</code> to the child <code>i</code>, and the child <code>i</code> will be content. Your goal is to maximize the number of your content children and output the maximum number.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> g = [1,2,3], s = [1,1] <strong>Output:</strong> 1 <strong>Explanation:</strong> You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> g = [1,2], s = [1,2,3] <strong>Output:</strong> 2 <strong>Explanation:</strong> You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= g.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= g[i], s[j] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Note:</strong> This question is the same as <a href="https://leetcode.com/problems/maximum-matching-of-players-with-trainers/description/" target="_blank"> 2410: Maximum Matching of Players With Trainers.</a></p>
Greedy; Array; Two Pointers; Sorting
TypeScript
function findContentChildren(g: number[], s: number[]): number { g.sort((a, b) => a - b); s.sort((a, b) => a - b); const m = g.length; const n = s.length; for (let i = 0, j = 0; i < m; ++i) { while (j < n && s[j] < g[i]) { ++j; } if (j++ >= n) { return i; } } return m; }
456
132 Pattern
Medium
<p>Given an array of <code>n</code> integers <code>nums</code>, a <strong>132 pattern</strong> is a subsequence of three integers <code>nums[i]</code>, <code>nums[j]</code> and <code>nums[k]</code> such that <code>i &lt; j &lt; k</code> and <code>nums[i] &lt; nums[k] &lt; nums[j]</code>.</p> <p>Return <code>true</code><em> if there is a <strong>132 pattern</strong> in </em><code>nums</code><em>, otherwise, return </em><code>false</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> false <strong>Explanation:</strong> There is no 132 pattern in the sequence. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,4,2] <strong>Output:</strong> true <strong>Explanation:</strong> There is a 132 pattern in the sequence: [1, 4, 2]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-1,3,2,0] <strong>Output:</strong> true <strong>Explanation:</strong> There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Binary Search; Ordered Set; Monotonic Stack
C++
class Solution { public: bool find132pattern(vector<int>& nums) { int vk = INT_MIN; stack<int> stk; for (int i = nums.size() - 1; ~i; --i) { if (nums[i] < vk) { return true; } while (!stk.empty() && stk.top() < nums[i]) { vk = stk.top(); stk.pop(); } stk.push(nums[i]); } return false; } };
456
132 Pattern
Medium
<p>Given an array of <code>n</code> integers <code>nums</code>, a <strong>132 pattern</strong> is a subsequence of three integers <code>nums[i]</code>, <code>nums[j]</code> and <code>nums[k]</code> such that <code>i &lt; j &lt; k</code> and <code>nums[i] &lt; nums[k] &lt; nums[j]</code>.</p> <p>Return <code>true</code><em> if there is a <strong>132 pattern</strong> in </em><code>nums</code><em>, otherwise, return </em><code>false</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> false <strong>Explanation:</strong> There is no 132 pattern in the sequence. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,4,2] <strong>Output:</strong> true <strong>Explanation:</strong> There is a 132 pattern in the sequence: [1, 4, 2]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-1,3,2,0] <strong>Output:</strong> true <strong>Explanation:</strong> There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Binary Search; Ordered Set; Monotonic Stack
Go
func find132pattern(nums []int) bool { vk := -(1 << 30) stk := []int{} for i := len(nums) - 1; i >= 0; i-- { if nums[i] < vk { return true } for len(stk) > 0 && stk[len(stk)-1] < nums[i] { vk = stk[len(stk)-1] stk = stk[:len(stk)-1] } stk = append(stk, nums[i]) } return false }
456
132 Pattern
Medium
<p>Given an array of <code>n</code> integers <code>nums</code>, a <strong>132 pattern</strong> is a subsequence of three integers <code>nums[i]</code>, <code>nums[j]</code> and <code>nums[k]</code> such that <code>i &lt; j &lt; k</code> and <code>nums[i] &lt; nums[k] &lt; nums[j]</code>.</p> <p>Return <code>true</code><em> if there is a <strong>132 pattern</strong> in </em><code>nums</code><em>, otherwise, return </em><code>false</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> false <strong>Explanation:</strong> There is no 132 pattern in the sequence. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,4,2] <strong>Output:</strong> true <strong>Explanation:</strong> There is a 132 pattern in the sequence: [1, 4, 2]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-1,3,2,0] <strong>Output:</strong> true <strong>Explanation:</strong> There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Binary Search; Ordered Set; Monotonic Stack
Java
class Solution { public boolean find132pattern(int[] nums) { int vk = -(1 << 30); Deque<Integer> stk = new ArrayDeque<>(); for (int i = nums.length - 1; i >= 0; --i) { if (nums[i] < vk) { return true; } while (!stk.isEmpty() && stk.peek() < nums[i]) { vk = stk.pop(); } stk.push(nums[i]); } return false; } }
456
132 Pattern
Medium
<p>Given an array of <code>n</code> integers <code>nums</code>, a <strong>132 pattern</strong> is a subsequence of three integers <code>nums[i]</code>, <code>nums[j]</code> and <code>nums[k]</code> such that <code>i &lt; j &lt; k</code> and <code>nums[i] &lt; nums[k] &lt; nums[j]</code>.</p> <p>Return <code>true</code><em> if there is a <strong>132 pattern</strong> in </em><code>nums</code><em>, otherwise, return </em><code>false</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> false <strong>Explanation:</strong> There is no 132 pattern in the sequence. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,4,2] <strong>Output:</strong> true <strong>Explanation:</strong> There is a 132 pattern in the sequence: [1, 4, 2]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-1,3,2,0] <strong>Output:</strong> true <strong>Explanation:</strong> There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Binary Search; Ordered Set; Monotonic Stack
Python
class Solution: def find132pattern(self, nums: List[int]) -> bool: vk = -inf stk = [] for x in nums[::-1]: if x < vk: return True while stk and stk[-1] < x: vk = stk.pop() stk.append(x) return False
456
132 Pattern
Medium
<p>Given an array of <code>n</code> integers <code>nums</code>, a <strong>132 pattern</strong> is a subsequence of three integers <code>nums[i]</code>, <code>nums[j]</code> and <code>nums[k]</code> such that <code>i &lt; j &lt; k</code> and <code>nums[i] &lt; nums[k] &lt; nums[j]</code>.</p> <p>Return <code>true</code><em> if there is a <strong>132 pattern</strong> in </em><code>nums</code><em>, otherwise, return </em><code>false</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> false <strong>Explanation:</strong> There is no 132 pattern in the sequence. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,4,2] <strong>Output:</strong> true <strong>Explanation:</strong> There is a 132 pattern in the sequence: [1, 4, 2]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-1,3,2,0] <strong>Output:</strong> true <strong>Explanation:</strong> There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Binary Search; Ordered Set; Monotonic Stack
Rust
impl Solution { pub fn find132pattern(nums: Vec<i32>) -> bool { let n = nums.len(); let mut vk = i32::MIN; let mut stk = vec![]; for i in (0..n).rev() { if nums[i] < vk { return true; } while !stk.is_empty() && stk.last().unwrap() < &nums[i] { vk = stk.pop().unwrap(); } stk.push(nums[i]); } false } }
456
132 Pattern
Medium
<p>Given an array of <code>n</code> integers <code>nums</code>, a <strong>132 pattern</strong> is a subsequence of three integers <code>nums[i]</code>, <code>nums[j]</code> and <code>nums[k]</code> such that <code>i &lt; j &lt; k</code> and <code>nums[i] &lt; nums[k] &lt; nums[j]</code>.</p> <p>Return <code>true</code><em> if there is a <strong>132 pattern</strong> in </em><code>nums</code><em>, otherwise, return </em><code>false</code><em>.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,4] <strong>Output:</strong> false <strong>Explanation:</strong> There is no 132 pattern in the sequence. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,4,2] <strong>Output:</strong> true <strong>Explanation:</strong> There is a 132 pattern in the sequence: [1, 4, 2]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [-1,3,2,0] <strong>Output:</strong> true <strong>Explanation:</strong> There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Stack; Array; Binary Search; Ordered Set; Monotonic Stack
TypeScript
function find132pattern(nums: number[]): boolean { let vk = -Infinity; const stk: number[] = []; for (let i = nums.length - 1; i >= 0; --i) { if (nums[i] < vk) { return true; } while (stk.length && stk[stk.length - 1] < nums[i]) { vk = stk.pop()!; } stk.push(nums[i]); } return false; }
457
Circular Array Loop
Medium
<p>You are playing a game involving a <strong>circular</strong> array of non-zero integers <code>nums</code>. Each <code>nums[i]</code> denotes the number of indices forward/backward you must move if you are located at index <code>i</code>:</p> <ul> <li>If <code>nums[i]</code> is positive, move <code>nums[i]</code> steps <strong>forward</strong>, and</li> <li>If <code>nums[i]</code> is negative, move <code>nums[i]</code> steps <strong>backward</strong>.</li> </ul> <p>Since the array is <strong>circular</strong>, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.</p> <p>A <strong>cycle</strong> in the array consists of a sequence of indices <code>seq</code> of length <code>k</code> where:</p> <ul> <li>Following the movement rules above results in the repeating index sequence <code>seq[0] -&gt; seq[1] -&gt; ... -&gt; seq[k - 1] -&gt; seq[0] -&gt; ...</code></li> <li>Every <code>nums[seq[j]]</code> is either <strong>all positive</strong> or <strong>all negative</strong>.</li> <li><code>k &gt; 1</code></li> </ul> <p>Return <code>true</code><em> if there is a <strong>cycle</strong> in </em><code>nums</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0457.Circular%20Array%20Loop/images/img1.jpg" style="width: 402px; height: 289px;" /> <pre> <strong>Input:</strong> nums = [2,-1,1,2,2] <strong>Output:</strong> true <strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --&gt; 2 --&gt; 3 --&gt; 0 --&gt; ..., and all of its nodes are white (jumping in the same direction). </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0457.Circular%20Array%20Loop/images/img2.jpg" style="width: 402px; height: 390px;" /> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4,-5,6] <strong>Output:</strong> false <strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. The only cycle is of size 1, so we return false. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0457.Circular%20Array%20Loop/images/img3.jpg" style="width: 497px; height: 242px;" /> <pre> <strong>Input:</strong> nums = [1,-1,5,1,4] <strong>Output:</strong> true <strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --&gt; 1 --&gt; 0 --&gt; ..., and while it is of size &gt; 1, it has a node jumping forward and a node jumping backward, so <strong>it is not a cycle</strong>. We can see the cycle 3 --&gt; 4 --&gt; 3 --&gt; ..., and all of its nodes are white (jumping in the same direction). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> <li><code>nums[i] != 0</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(n)</code> time complexity and <code>O(1)</code> extra space complexity?</p>
Array; Hash Table; Two Pointers
C++
class Solution { public: bool circularArrayLoop(vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; ++i) { if (!nums[i]) continue; int slow = i, fast = next(nums, i); while (nums[slow] * nums[fast] > 0 && nums[slow] * nums[next(nums, fast)] > 0) { if (slow == fast) { if (slow != next(nums, slow)) return true; break; } slow = next(nums, slow); fast = next(nums, next(nums, fast)); } int j = i; while (nums[j] * nums[next(nums, j)] > 0) { nums[j] = 0; j = next(nums, j); } } return false; } int next(vector<int>& nums, int i) { int n = nums.size(); return (i + nums[i] % n + n) % n; } };
457
Circular Array Loop
Medium
<p>You are playing a game involving a <strong>circular</strong> array of non-zero integers <code>nums</code>. Each <code>nums[i]</code> denotes the number of indices forward/backward you must move if you are located at index <code>i</code>:</p> <ul> <li>If <code>nums[i]</code> is positive, move <code>nums[i]</code> steps <strong>forward</strong>, and</li> <li>If <code>nums[i]</code> is negative, move <code>nums[i]</code> steps <strong>backward</strong>.</li> </ul> <p>Since the array is <strong>circular</strong>, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.</p> <p>A <strong>cycle</strong> in the array consists of a sequence of indices <code>seq</code> of length <code>k</code> where:</p> <ul> <li>Following the movement rules above results in the repeating index sequence <code>seq[0] -&gt; seq[1] -&gt; ... -&gt; seq[k - 1] -&gt; seq[0] -&gt; ...</code></li> <li>Every <code>nums[seq[j]]</code> is either <strong>all positive</strong> or <strong>all negative</strong>.</li> <li><code>k &gt; 1</code></li> </ul> <p>Return <code>true</code><em> if there is a <strong>cycle</strong> in </em><code>nums</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0457.Circular%20Array%20Loop/images/img1.jpg" style="width: 402px; height: 289px;" /> <pre> <strong>Input:</strong> nums = [2,-1,1,2,2] <strong>Output:</strong> true <strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --&gt; 2 --&gt; 3 --&gt; 0 --&gt; ..., and all of its nodes are white (jumping in the same direction). </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0457.Circular%20Array%20Loop/images/img2.jpg" style="width: 402px; height: 390px;" /> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4,-5,6] <strong>Output:</strong> false <strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. The only cycle is of size 1, so we return false. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0457.Circular%20Array%20Loop/images/img3.jpg" style="width: 497px; height: 242px;" /> <pre> <strong>Input:</strong> nums = [1,-1,5,1,4] <strong>Output:</strong> true <strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --&gt; 1 --&gt; 0 --&gt; ..., and while it is of size &gt; 1, it has a node jumping forward and a node jumping backward, so <strong>it is not a cycle</strong>. We can see the cycle 3 --&gt; 4 --&gt; 3 --&gt; ..., and all of its nodes are white (jumping in the same direction). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> <li><code>nums[i] != 0</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(n)</code> time complexity and <code>O(1)</code> extra space complexity?</p>
Array; Hash Table; Two Pointers
Go
func circularArrayLoop(nums []int) bool { for i, num := range nums { if num == 0 { continue } slow, fast := i, next(nums, i) for nums[slow]*nums[fast] > 0 && nums[slow]*nums[next(nums, fast)] > 0 { if slow == fast { if slow != next(nums, slow) { return true } break } slow, fast = next(nums, slow), next(nums, next(nums, fast)) } j := i for nums[j]*nums[next(nums, j)] > 0 { nums[j] = 0 j = next(nums, j) } } return false } func next(nums []int, i int) int { n := len(nums) return (i + nums[i]%n + n) % n }
457
Circular Array Loop
Medium
<p>You are playing a game involving a <strong>circular</strong> array of non-zero integers <code>nums</code>. Each <code>nums[i]</code> denotes the number of indices forward/backward you must move if you are located at index <code>i</code>:</p> <ul> <li>If <code>nums[i]</code> is positive, move <code>nums[i]</code> steps <strong>forward</strong>, and</li> <li>If <code>nums[i]</code> is negative, move <code>nums[i]</code> steps <strong>backward</strong>.</li> </ul> <p>Since the array is <strong>circular</strong>, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.</p> <p>A <strong>cycle</strong> in the array consists of a sequence of indices <code>seq</code> of length <code>k</code> where:</p> <ul> <li>Following the movement rules above results in the repeating index sequence <code>seq[0] -&gt; seq[1] -&gt; ... -&gt; seq[k - 1] -&gt; seq[0] -&gt; ...</code></li> <li>Every <code>nums[seq[j]]</code> is either <strong>all positive</strong> or <strong>all negative</strong>.</li> <li><code>k &gt; 1</code></li> </ul> <p>Return <code>true</code><em> if there is a <strong>cycle</strong> in </em><code>nums</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0457.Circular%20Array%20Loop/images/img1.jpg" style="width: 402px; height: 289px;" /> <pre> <strong>Input:</strong> nums = [2,-1,1,2,2] <strong>Output:</strong> true <strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --&gt; 2 --&gt; 3 --&gt; 0 --&gt; ..., and all of its nodes are white (jumping in the same direction). </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0457.Circular%20Array%20Loop/images/img2.jpg" style="width: 402px; height: 390px;" /> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4,-5,6] <strong>Output:</strong> false <strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. The only cycle is of size 1, so we return false. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0457.Circular%20Array%20Loop/images/img3.jpg" style="width: 497px; height: 242px;" /> <pre> <strong>Input:</strong> nums = [1,-1,5,1,4] <strong>Output:</strong> true <strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --&gt; 1 --&gt; 0 --&gt; ..., and while it is of size &gt; 1, it has a node jumping forward and a node jumping backward, so <strong>it is not a cycle</strong>. We can see the cycle 3 --&gt; 4 --&gt; 3 --&gt; ..., and all of its nodes are white (jumping in the same direction). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> <li><code>nums[i] != 0</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(n)</code> time complexity and <code>O(1)</code> extra space complexity?</p>
Array; Hash Table; Two Pointers
Java
class Solution { private int n; private int[] nums; public boolean circularArrayLoop(int[] nums) { n = nums.length; this.nums = nums; for (int i = 0; i < n; ++i) { if (nums[i] == 0) { continue; } int slow = i, fast = next(i); while (nums[slow] * nums[fast] > 0 && nums[slow] * nums[next(fast)] > 0) { if (slow == fast) { if (slow != next(slow)) { return true; } break; } slow = next(slow); fast = next(next(fast)); } int j = i; while (nums[j] * nums[next(j)] > 0) { nums[j] = 0; j = next(j); } } return false; } private int next(int i) { return (i + nums[i] % n + n) % n; } }
457
Circular Array Loop
Medium
<p>You are playing a game involving a <strong>circular</strong> array of non-zero integers <code>nums</code>. Each <code>nums[i]</code> denotes the number of indices forward/backward you must move if you are located at index <code>i</code>:</p> <ul> <li>If <code>nums[i]</code> is positive, move <code>nums[i]</code> steps <strong>forward</strong>, and</li> <li>If <code>nums[i]</code> is negative, move <code>nums[i]</code> steps <strong>backward</strong>.</li> </ul> <p>Since the array is <strong>circular</strong>, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.</p> <p>A <strong>cycle</strong> in the array consists of a sequence of indices <code>seq</code> of length <code>k</code> where:</p> <ul> <li>Following the movement rules above results in the repeating index sequence <code>seq[0] -&gt; seq[1] -&gt; ... -&gt; seq[k - 1] -&gt; seq[0] -&gt; ...</code></li> <li>Every <code>nums[seq[j]]</code> is either <strong>all positive</strong> or <strong>all negative</strong>.</li> <li><code>k &gt; 1</code></li> </ul> <p>Return <code>true</code><em> if there is a <strong>cycle</strong> in </em><code>nums</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0457.Circular%20Array%20Loop/images/img1.jpg" style="width: 402px; height: 289px;" /> <pre> <strong>Input:</strong> nums = [2,-1,1,2,2] <strong>Output:</strong> true <strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --&gt; 2 --&gt; 3 --&gt; 0 --&gt; ..., and all of its nodes are white (jumping in the same direction). </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0457.Circular%20Array%20Loop/images/img2.jpg" style="width: 402px; height: 390px;" /> <pre> <strong>Input:</strong> nums = [-1,-2,-3,-4,-5,6] <strong>Output:</strong> false <strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. The only cycle is of size 1, so we return false. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0457.Circular%20Array%20Loop/images/img3.jpg" style="width: 497px; height: 242px;" /> <pre> <strong>Input:</strong> nums = [1,-1,5,1,4] <strong>Output:</strong> true <strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --&gt; 1 --&gt; 0 --&gt; ..., and while it is of size &gt; 1, it has a node jumping forward and a node jumping backward, so <strong>it is not a cycle</strong>. We can see the cycle 3 --&gt; 4 --&gt; 3 --&gt; ..., and all of its nodes are white (jumping in the same direction). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> <li><code>nums[i] != 0</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(n)</code> time complexity and <code>O(1)</code> extra space complexity?</p>
Array; Hash Table; Two Pointers
Python
class Solution: def circularArrayLoop(self, nums: List[int]) -> bool: n = len(nums) def next(i): return (i + nums[i] % n + n) % n for i in range(n): if nums[i] == 0: continue slow, fast = i, next(i) while nums[slow] * nums[fast] > 0 and nums[slow] * nums[next(fast)] > 0: if slow == fast: if slow != next(slow): return True break slow, fast = next(slow), next(next(fast)) j = i while nums[j] * nums[next(j)] > 0: nums[j] = 0 j = next(j) return False
458
Poor Pigs
Hard
<p>There are <code>buckets</code> buckets of liquid, where <strong>exactly one</strong> of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have <code>minutesToTest</code> minutes to determine which bucket is poisonous.</p> <p>You can feed the pigs according to these steps:</p> <ol> <li>Choose some live pigs to feed.</li> <li>For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.</li> <li>Wait for <code>minutesToDie</code> minutes. You may <strong>not</strong> feed any other pigs during this time.</li> <li>After <code>minutesToDie</code> minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.</li> <li>Repeat this process until you run out of time.</li> </ol> <p>Given <code>buckets</code>, <code>minutesToDie</code>, and <code>minutesToTest</code>, return <em>the <strong>minimum</strong> number of pigs needed to figure out which bucket is poisonous within the allotted time</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 15 <strong>Output:</strong> 2 <strong>Explanation:</strong> We can determine the poisonous bucket as follows: At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3. At time 15, there are 4 possible outcomes: - If only the first pig dies, then bucket 1 must be poisonous. - If only the second pig dies, then bucket 3 must be poisonous. - If both pigs die, then bucket 2 must be poisonous. - If neither pig dies, then bucket 4 must be poisonous. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 30 <strong>Output:</strong> 2 <strong>Explanation:</strong> We can determine the poisonous bucket as follows: At time 0, feed the first pig bucket 1, and feed the second pig bucket 2. At time 15, there are 2 possible outcomes: - If either pig dies, then the poisonous bucket is the one it was fed. - If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4. At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= buckets &lt;= 1000</code></li> <li><code>1 &lt;=&nbsp;minutesToDie &lt;=&nbsp;minutesToTest &lt;= 100</code></li> </ul>
Math; Dynamic Programming; Combinatorics
C++
class Solution { public: int poorPigs(int buckets, int minutesToDie, int minutesToTest) { int base = minutesToTest / minutesToDie + 1; int res = 0; for (int p = 1; p < buckets; p *= base) ++res; return res; } };
458
Poor Pigs
Hard
<p>There are <code>buckets</code> buckets of liquid, where <strong>exactly one</strong> of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have <code>minutesToTest</code> minutes to determine which bucket is poisonous.</p> <p>You can feed the pigs according to these steps:</p> <ol> <li>Choose some live pigs to feed.</li> <li>For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.</li> <li>Wait for <code>minutesToDie</code> minutes. You may <strong>not</strong> feed any other pigs during this time.</li> <li>After <code>minutesToDie</code> minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.</li> <li>Repeat this process until you run out of time.</li> </ol> <p>Given <code>buckets</code>, <code>minutesToDie</code>, and <code>minutesToTest</code>, return <em>the <strong>minimum</strong> number of pigs needed to figure out which bucket is poisonous within the allotted time</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 15 <strong>Output:</strong> 2 <strong>Explanation:</strong> We can determine the poisonous bucket as follows: At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3. At time 15, there are 4 possible outcomes: - If only the first pig dies, then bucket 1 must be poisonous. - If only the second pig dies, then bucket 3 must be poisonous. - If both pigs die, then bucket 2 must be poisonous. - If neither pig dies, then bucket 4 must be poisonous. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 30 <strong>Output:</strong> 2 <strong>Explanation:</strong> We can determine the poisonous bucket as follows: At time 0, feed the first pig bucket 1, and feed the second pig bucket 2. At time 15, there are 2 possible outcomes: - If either pig dies, then the poisonous bucket is the one it was fed. - If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4. At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= buckets &lt;= 1000</code></li> <li><code>1 &lt;=&nbsp;minutesToDie &lt;=&nbsp;minutesToTest &lt;= 100</code></li> </ul>
Math; Dynamic Programming; Combinatorics
Go
func poorPigs(buckets int, minutesToDie int, minutesToTest int) int { base := minutesToTest/minutesToDie + 1 res := 0 for p := 1; p < buckets; p *= base { res++ } return res }
458
Poor Pigs
Hard
<p>There are <code>buckets</code> buckets of liquid, where <strong>exactly one</strong> of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have <code>minutesToTest</code> minutes to determine which bucket is poisonous.</p> <p>You can feed the pigs according to these steps:</p> <ol> <li>Choose some live pigs to feed.</li> <li>For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.</li> <li>Wait for <code>minutesToDie</code> minutes. You may <strong>not</strong> feed any other pigs during this time.</li> <li>After <code>minutesToDie</code> minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.</li> <li>Repeat this process until you run out of time.</li> </ol> <p>Given <code>buckets</code>, <code>minutesToDie</code>, and <code>minutesToTest</code>, return <em>the <strong>minimum</strong> number of pigs needed to figure out which bucket is poisonous within the allotted time</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 15 <strong>Output:</strong> 2 <strong>Explanation:</strong> We can determine the poisonous bucket as follows: At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3. At time 15, there are 4 possible outcomes: - If only the first pig dies, then bucket 1 must be poisonous. - If only the second pig dies, then bucket 3 must be poisonous. - If both pigs die, then bucket 2 must be poisonous. - If neither pig dies, then bucket 4 must be poisonous. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 30 <strong>Output:</strong> 2 <strong>Explanation:</strong> We can determine the poisonous bucket as follows: At time 0, feed the first pig bucket 1, and feed the second pig bucket 2. At time 15, there are 2 possible outcomes: - If either pig dies, then the poisonous bucket is the one it was fed. - If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4. At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= buckets &lt;= 1000</code></li> <li><code>1 &lt;=&nbsp;minutesToDie &lt;=&nbsp;minutesToTest &lt;= 100</code></li> </ul>
Math; Dynamic Programming; Combinatorics
Java
class Solution { public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { int base = minutesToTest / minutesToDie + 1; int res = 0; for (int p = 1; p < buckets; p *= base) { ++res; } return res; } }