id
int64
1
3.65k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
268
Missing Number
Easy
<p>Given an array <code>nums</code> containing <code>n</code> distinct numbers in the range <code>[0, n]</code>, return <em>the only number in the range that is missing from the array.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 3</code> since there are 3 numbers, so all numbers are in the range <code>[0,3]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 2</code> since there are 2 numbers, so all numbers are in the range <code>[0,2]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [9,6,4,2,3,5,7,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 9</code> since there are 9 numbers, so all numbers are in the range <code>[0,9]</code>. 8 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <div class="simple-translate-system-theme" id="simple-translate"> <div> <div class="simple-translate-button isShow" style="background-image: url(&quot;moz-extension://8a9ffb6b-7e69-4e93-aae1-436a1448eff6/icons/512.png&quot;); height: 22px; width: 22px; top: 318px; left: 36px;">&nbsp;</div> <div class="simple-translate-panel " style="width: 300px; height: 200px; top: 0px; left: 0px; font-size: 13px;"> <div class="simple-translate-result-wrapper" style="overflow: hidden;"> <div class="simple-translate-move" draggable="true">&nbsp;</div> <div class="simple-translate-result-contents"> <p class="simple-translate-result" dir="auto">&nbsp;</p> <p class="simple-translate-candidate" dir="auto">&nbsp;</p> </div> </div> </div> </div> </div> <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>0 &lt;= nums[i] &lt;= n</code></li> <li>All the numbers of <code>nums</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you implement a solution using only <code>O(1)</code> extra space complexity and <code>O(n)</code> runtime complexity?</p>
Bit Manipulation; Array; Hash Table; Math; Binary Search; Sorting
PHP
class Solution { /** * @param Integer[] $nums * @return Integer */ function missingNumber($nums) { $n = count($nums); $sumN = (($n + 1) * $n) / 2; for ($i = 0; $i < $n; $i++) { $sumN -= $nums[$i]; } return $sumN; } }
268
Missing Number
Easy
<p>Given an array <code>nums</code> containing <code>n</code> distinct numbers in the range <code>[0, n]</code>, return <em>the only number in the range that is missing from the array.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 3</code> since there are 3 numbers, so all numbers are in the range <code>[0,3]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 2</code> since there are 2 numbers, so all numbers are in the range <code>[0,2]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [9,6,4,2,3,5,7,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 9</code> since there are 9 numbers, so all numbers are in the range <code>[0,9]</code>. 8 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <div class="simple-translate-system-theme" id="simple-translate"> <div> <div class="simple-translate-button isShow" style="background-image: url(&quot;moz-extension://8a9ffb6b-7e69-4e93-aae1-436a1448eff6/icons/512.png&quot;); height: 22px; width: 22px; top: 318px; left: 36px;">&nbsp;</div> <div class="simple-translate-panel " style="width: 300px; height: 200px; top: 0px; left: 0px; font-size: 13px;"> <div class="simple-translate-result-wrapper" style="overflow: hidden;"> <div class="simple-translate-move" draggable="true">&nbsp;</div> <div class="simple-translate-result-contents"> <p class="simple-translate-result" dir="auto">&nbsp;</p> <p class="simple-translate-candidate" dir="auto">&nbsp;</p> </div> </div> </div> </div> </div> <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>0 &lt;= nums[i] &lt;= n</code></li> <li>All the numbers of <code>nums</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you implement a solution using only <code>O(1)</code> extra space complexity and <code>O(n)</code> runtime complexity?</p>
Bit Manipulation; Array; Hash Table; Math; Binary Search; Sorting
Python
class Solution: def missingNumber(self, nums: List[int]) -> int: return reduce(xor, (i ^ v for i, v in enumerate(nums, 1)))
268
Missing Number
Easy
<p>Given an array <code>nums</code> containing <code>n</code> distinct numbers in the range <code>[0, n]</code>, return <em>the only number in the range that is missing from the array.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 3</code> since there are 3 numbers, so all numbers are in the range <code>[0,3]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 2</code> since there are 2 numbers, so all numbers are in the range <code>[0,2]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [9,6,4,2,3,5,7,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 9</code> since there are 9 numbers, so all numbers are in the range <code>[0,9]</code>. 8 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <div class="simple-translate-system-theme" id="simple-translate"> <div> <div class="simple-translate-button isShow" style="background-image: url(&quot;moz-extension://8a9ffb6b-7e69-4e93-aae1-436a1448eff6/icons/512.png&quot;); height: 22px; width: 22px; top: 318px; left: 36px;">&nbsp;</div> <div class="simple-translate-panel " style="width: 300px; height: 200px; top: 0px; left: 0px; font-size: 13px;"> <div class="simple-translate-result-wrapper" style="overflow: hidden;"> <div class="simple-translate-move" draggable="true">&nbsp;</div> <div class="simple-translate-result-contents"> <p class="simple-translate-result" dir="auto">&nbsp;</p> <p class="simple-translate-candidate" dir="auto">&nbsp;</p> </div> </div> </div> </div> </div> <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>0 &lt;= nums[i] &lt;= n</code></li> <li>All the numbers of <code>nums</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you implement a solution using only <code>O(1)</code> extra space complexity and <code>O(n)</code> runtime complexity?</p>
Bit Manipulation; Array; Hash Table; Math; Binary Search; Sorting
Rust
impl Solution { pub fn missing_number(nums: Vec<i32>) -> i32 { let n = nums.len() as i32; let mut ans = n; for (i, v) in nums.iter().enumerate() { ans ^= (i as i32) ^ v; } ans } }
268
Missing Number
Easy
<p>Given an array <code>nums</code> containing <code>n</code> distinct numbers in the range <code>[0, n]</code>, return <em>the only number in the range that is missing from the array.</em></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 3</code> since there are 3 numbers, so all numbers are in the range <code>[0,3]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 2</code> since there are 2 numbers, so all numbers are in the range <code>[0,2]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [9,6,4,2,3,5,7,0,1]</span></p> <p><strong>Output:</strong> <span class="example-io">8</span></p> <p><strong>Explanation:</strong></p> <p><code>n = 9</code> since there are 9 numbers, so all numbers are in the range <code>[0,9]</code>. 8 is the missing number in the range since it does not appear in <code>nums</code>.</p> </div> <div class="simple-translate-system-theme" id="simple-translate"> <div> <div class="simple-translate-button isShow" style="background-image: url(&quot;moz-extension://8a9ffb6b-7e69-4e93-aae1-436a1448eff6/icons/512.png&quot;); height: 22px; width: 22px; top: 318px; left: 36px;">&nbsp;</div> <div class="simple-translate-panel " style="width: 300px; height: 200px; top: 0px; left: 0px; font-size: 13px;"> <div class="simple-translate-result-wrapper" style="overflow: hidden;"> <div class="simple-translate-move" draggable="true">&nbsp;</div> <div class="simple-translate-result-contents"> <p class="simple-translate-result" dir="auto">&nbsp;</p> <p class="simple-translate-candidate" dir="auto">&nbsp;</p> </div> </div> </div> </div> </div> <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>0 &lt;= nums[i] &lt;= n</code></li> <li>All the numbers of <code>nums</code> are <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you implement a solution using only <code>O(1)</code> extra space complexity and <code>O(n)</code> runtime complexity?</p>
Bit Manipulation; Array; Hash Table; Math; Binary Search; Sorting
TypeScript
function missingNumber(nums: number[]): number { const n = nums.length; let ans = n; for (let i = 0; i < n; ++i) { ans ^= i ^ nums[i]; } return ans; }
269
Alien Dictionary
Hard
<p>There is a new alien language that uses the English alphabet. However, the order of the letters is unknown to you.</p> <p>You are given a list of strings <code>words</code> from the alien language&#39;s dictionary. Now it is claimed that the strings in <code>words</code> are <span data-keyword="lexicographically-smaller-string-alien"><strong>sorted lexicographically</strong></span> by the rules of this new language.</p> <p>If this claim is incorrect, and the given arrangement of string in&nbsp;<code>words</code>&nbsp;cannot correspond to any order of letters,&nbsp;return&nbsp;<code>&quot;&quot;.</code></p> <p>Otherwise, return <em>a string of the unique letters in the new alien language sorted in <strong>lexicographically increasing order</strong> by the new language&#39;s rules</em><em>. </em>If there are multiple solutions, return<em> <strong>any of them</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;wrt&quot;,&quot;wrf&quot;,&quot;er&quot;,&quot;ett&quot;,&quot;rftt&quot;] <strong>Output:</strong> &quot;wertf&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;z&quot;,&quot;x&quot;] <strong>Output:</strong> &quot;zx&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;z&quot;,&quot;x&quot;,&quot;z&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> The order is invalid, so return <code>&quot;&quot;</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists of only lowercase English letters.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; String
C++
class Solution { public: string alienOrder(vector<string>& words) { vector<vector<bool>> g(26, vector<bool>(26)); vector<bool> s(26); int cnt = 0; int n = words.size(); for (int i = 0; i < n - 1; ++i) { for (char c : words[i]) { if (cnt == 26) break; c -= 'a'; if (!s[c]) { ++cnt; s[c] = true; } } int m = words[i].size(); for (int j = 0; j < m; ++j) { if (j >= words[i + 1].size()) return ""; char c1 = words[i][j], c2 = words[i + 1][j]; if (c1 == c2) continue; if (g[c2 - 'a'][c1 - 'a']) return ""; g[c1 - 'a'][c2 - 'a'] = true; break; } } for (char c : words[n - 1]) { if (cnt == 26) break; c -= 'a'; if (!s[c]) { ++cnt; s[c] = true; } } vector<int> indegree(26); for (int i = 0; i < 26; ++i) for (int j = 0; j < 26; ++j) if (i != j && s[i] && s[j] && g[i][j]) ++indegree[j]; queue<int> q; for (int i = 0; i < 26; ++i) if (s[i] && indegree[i] == 0) q.push(i); string ans = ""; while (!q.empty()) { int t = q.front(); ans += (t + 'a'); q.pop(); for (int i = 0; i < 26; ++i) if (i != t && s[i] && g[t][i]) if (--indegree[i] == 0) q.push(i); } return ans.size() < cnt ? "" : ans; } };
269
Alien Dictionary
Hard
<p>There is a new alien language that uses the English alphabet. However, the order of the letters is unknown to you.</p> <p>You are given a list of strings <code>words</code> from the alien language&#39;s dictionary. Now it is claimed that the strings in <code>words</code> are <span data-keyword="lexicographically-smaller-string-alien"><strong>sorted lexicographically</strong></span> by the rules of this new language.</p> <p>If this claim is incorrect, and the given arrangement of string in&nbsp;<code>words</code>&nbsp;cannot correspond to any order of letters,&nbsp;return&nbsp;<code>&quot;&quot;.</code></p> <p>Otherwise, return <em>a string of the unique letters in the new alien language sorted in <strong>lexicographically increasing order</strong> by the new language&#39;s rules</em><em>. </em>If there are multiple solutions, return<em> <strong>any of them</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;wrt&quot;,&quot;wrf&quot;,&quot;er&quot;,&quot;ett&quot;,&quot;rftt&quot;] <strong>Output:</strong> &quot;wertf&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;z&quot;,&quot;x&quot;] <strong>Output:</strong> &quot;zx&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;z&quot;,&quot;x&quot;,&quot;z&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> The order is invalid, so return <code>&quot;&quot;</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists of only lowercase English letters.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; String
Go
func alienOrder(words []string) string { g := [26][26]bool{} s := [26]bool{} cnt := 0 n := len(words) for i := 0; i < n-1; i++ { for _, c := range words[i] { if cnt == 26 { break } c -= 'a' if !s[c] { cnt++ s[c] = true } } m := len(words[i]) for j := 0; j < m; j++ { if j >= len(words[i+1]) { return "" } c1, c2 := words[i][j]-'a', words[i+1][j]-'a' if c1 == c2 { continue } if g[c2][c1] { return "" } g[c1][c2] = true break } } for _, c := range words[n-1] { if cnt == 26 { break } c -= 'a' if !s[c] { cnt++ s[c] = true } } inDegree := [26]int{} for _, out := range g { for i, v := range out { if v { inDegree[i]++ } } } q := []int{} for i, in := range inDegree { if in == 0 && s[i] { q = append(q, i) } } ans := "" for len(q) > 0 { t := q[0] q = q[1:] ans += string(t + 'a') for i, v := range g[t] { if v { inDegree[i]-- if inDegree[i] == 0 && s[i] { q = append(q, i) } } } } if len(ans) < cnt { return "" } return ans }
269
Alien Dictionary
Hard
<p>There is a new alien language that uses the English alphabet. However, the order of the letters is unknown to you.</p> <p>You are given a list of strings <code>words</code> from the alien language&#39;s dictionary. Now it is claimed that the strings in <code>words</code> are <span data-keyword="lexicographically-smaller-string-alien"><strong>sorted lexicographically</strong></span> by the rules of this new language.</p> <p>If this claim is incorrect, and the given arrangement of string in&nbsp;<code>words</code>&nbsp;cannot correspond to any order of letters,&nbsp;return&nbsp;<code>&quot;&quot;.</code></p> <p>Otherwise, return <em>a string of the unique letters in the new alien language sorted in <strong>lexicographically increasing order</strong> by the new language&#39;s rules</em><em>. </em>If there are multiple solutions, return<em> <strong>any of them</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;wrt&quot;,&quot;wrf&quot;,&quot;er&quot;,&quot;ett&quot;,&quot;rftt&quot;] <strong>Output:</strong> &quot;wertf&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;z&quot;,&quot;x&quot;] <strong>Output:</strong> &quot;zx&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;z&quot;,&quot;x&quot;,&quot;z&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> The order is invalid, so return <code>&quot;&quot;</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists of only lowercase English letters.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; String
Java
class Solution { public String alienOrder(String[] words) { boolean[][] g = new boolean[26][26]; boolean[] s = new boolean[26]; int cnt = 0; int n = words.length; for (int i = 0; i < n - 1; ++i) { for (char c : words[i].toCharArray()) { if (cnt == 26) { break; } c -= 'a'; if (!s[c]) { ++cnt; s[c] = true; } } int m = words[i].length(); for (int j = 0; j < m; ++j) { if (j >= words[i + 1].length()) { return ""; } char c1 = words[i].charAt(j), c2 = words[i + 1].charAt(j); if (c1 == c2) { continue; } if (g[c2 - 'a'][c1 - 'a']) { return ""; } g[c1 - 'a'][c2 - 'a'] = true; break; } } for (char c : words[n - 1].toCharArray()) { if (cnt == 26) { break; } c -= 'a'; if (!s[c]) { ++cnt; s[c] = true; } } int[] indegree = new int[26]; for (int i = 0; i < 26; ++i) { for (int j = 0; j < 26; ++j) { if (i != j && s[i] && s[j] && g[i][j]) { ++indegree[j]; } } } Deque<Integer> q = new LinkedList<>(); for (int i = 0; i < 26; ++i) { if (s[i] && indegree[i] == 0) { q.offerLast(i); } } StringBuilder ans = new StringBuilder(); while (!q.isEmpty()) { int t = q.pollFirst(); ans.append((char) (t + 'a')); for (int i = 0; i < 26; ++i) { if (i != t && s[i] && g[t][i]) { if (--indegree[i] == 0) { q.offerLast(i); } } } } return ans.length() < cnt ? "" : ans.toString(); } }
269
Alien Dictionary
Hard
<p>There is a new alien language that uses the English alphabet. However, the order of the letters is unknown to you.</p> <p>You are given a list of strings <code>words</code> from the alien language&#39;s dictionary. Now it is claimed that the strings in <code>words</code> are <span data-keyword="lexicographically-smaller-string-alien"><strong>sorted lexicographically</strong></span> by the rules of this new language.</p> <p>If this claim is incorrect, and the given arrangement of string in&nbsp;<code>words</code>&nbsp;cannot correspond to any order of letters,&nbsp;return&nbsp;<code>&quot;&quot;.</code></p> <p>Otherwise, return <em>a string of the unique letters in the new alien language sorted in <strong>lexicographically increasing order</strong> by the new language&#39;s rules</em><em>. </em>If there are multiple solutions, return<em> <strong>any of them</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> words = [&quot;wrt&quot;,&quot;wrf&quot;,&quot;er&quot;,&quot;ett&quot;,&quot;rftt&quot;] <strong>Output:</strong> &quot;wertf&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> words = [&quot;z&quot;,&quot;x&quot;] <strong>Output:</strong> &quot;zx&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> words = [&quot;z&quot;,&quot;x&quot;,&quot;z&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> The order is invalid, so return <code>&quot;&quot;</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= words.length &lt;= 100</code></li> <li><code>1 &lt;= words[i].length &lt;= 100</code></li> <li><code>words[i]</code> consists of only lowercase English letters.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; String
Python
class Solution: def alienOrder(self, words: List[str]) -> str: g = [[False] * 26 for _ in range(26)] s = [False] * 26 cnt = 0 n = len(words) for i in range(n - 1): for c in words[i]: if cnt == 26: break o = ord(c) - ord('a') if not s[o]: cnt += 1 s[o] = True m = len(words[i]) for j in range(m): if j >= len(words[i + 1]): return '' c1, c2 = words[i][j], words[i + 1][j] if c1 == c2: continue o1, o2 = ord(c1) - ord('a'), ord(c2) - ord('a') if g[o2][o1]: return '' g[o1][o2] = True break for c in words[n - 1]: if cnt == 26: break o = ord(c) - ord('a') if not s[o]: cnt += 1 s[o] = True indegree = [0] * 26 for i in range(26): for j in range(26): if i != j and s[i] and s[j] and g[i][j]: indegree[j] += 1 q = deque() ans = [] for i in range(26): if s[i] and indegree[i] == 0: q.append(i) while q: t = q.popleft() ans.append(chr(t + ord('a'))) for i in range(26): if s[i] and i != t and g[t][i]: indegree[i] -= 1 if indegree[i] == 0: q.append(i) return '' if len(ans) < cnt else ''.join(ans)
270
Closest Binary Search Tree Value
Easy
<p>Given the <code>root</code> of a binary search tree and a <code>target</code> value, return <em>the value in the BST that is closest to the</em> <code>target</code>. If there are multiple answers, print the smallest.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0270.Closest%20Binary%20Search%20Tree%20Value/images/closest1-1-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [4,2,5,1,3], target = 3.714286 <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1], target = 4.428571 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Search; 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: int closestValue(TreeNode* root, double target) { int ans = root->val; double diff = INT_MAX; function<void(TreeNode*)> dfs = [&](TreeNode* node) { if (!node) { return; } double nxt = abs(node->val - target); if (nxt < diff || (nxt == diff && node->val < ans)) { diff = nxt; ans = node->val; } node = target < node->val ? node->left : node->right; dfs(node); }; dfs(root); return ans; } };
270
Closest Binary Search Tree Value
Easy
<p>Given the <code>root</code> of a binary search tree and a <code>target</code> value, return <em>the value in the BST that is closest to the</em> <code>target</code>. If there are multiple answers, print the smallest.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0270.Closest%20Binary%20Search%20Tree%20Value/images/closest1-1-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [4,2,5,1,3], target = 3.714286 <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1], target = 4.428571 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func closestValue(root *TreeNode, target float64) int { ans := root.Val diff := math.MaxFloat64 var dfs func(*TreeNode) dfs = func(node *TreeNode) { if node == nil { return } nxt := math.Abs(float64(node.Val) - target) if nxt < diff || (nxt == diff && node.Val < ans) { diff = nxt ans = node.Val } if target < float64(node.Val) { dfs(node.Left) } else { dfs(node.Right) } } dfs(root) return ans }
270
Closest Binary Search Tree Value
Easy
<p>Given the <code>root</code> of a binary search tree and a <code>target</code> value, return <em>the value in the BST that is closest to the</em> <code>target</code>. If there are multiple answers, print the smallest.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0270.Closest%20Binary%20Search%20Tree%20Value/images/closest1-1-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [4,2,5,1,3], target = 3.714286 <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1], target = 4.428571 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Search; 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 { private int ans; private double target; private double diff = Double.MAX_VALUE; public int closestValue(TreeNode root, double target) { this.target = target; dfs(root); return ans; } private void dfs(TreeNode node) { if (node == null) { return; } double nxt = Math.abs(node.val - target); if (nxt < diff || (nxt == diff && node.val < ans)) { diff = nxt; ans = node.val; } node = target < node.val ? node.left : node.right; dfs(node); } }
270
Closest Binary Search Tree Value
Easy
<p>Given the <code>root</code> of a binary search tree and a <code>target</code> value, return <em>the value in the BST that is closest to the</em> <code>target</code>. If there are multiple answers, print the smallest.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0270.Closest%20Binary%20Search%20Tree%20Value/images/closest1-1-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [4,2,5,1,3], target = 3.714286 <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1], target = 4.428571 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} target * @return {number} */ var closestValue = function (root, target) { let ans = 0; let diff = Infinity; const dfs = node => { if (!node) { return; } const nxt = Math.abs(target - node.val); if (nxt < diff || (nxt === diff && node.val < ans)) { diff = nxt; ans = node.val; } node = target < node.val ? node.left : node.right; dfs(node); }; dfs(root); return ans; };
270
Closest Binary Search Tree Value
Easy
<p>Given the <code>root</code> of a binary search tree and a <code>target</code> value, return <em>the value in the BST that is closest to the</em> <code>target</code>. If there are multiple answers, print the smallest.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0270.Closest%20Binary%20Search%20Tree%20Value/images/closest1-1-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [4,2,5,1,3], target = 3.714286 <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1], target = 4.428571 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Search; 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 closestValue(self, root: Optional[TreeNode], target: float) -> int: def dfs(node: Optional[TreeNode]): if node is None: return nxt = abs(target - node.val) nonlocal ans, diff if nxt < diff or (nxt == diff and node.val < ans): diff = nxt ans = node.val node = node.left if target < node.val else node.right dfs(node) ans = 0 diff = inf dfs(root) return ans
270
Closest Binary Search Tree Value
Easy
<p>Given the <code>root</code> of a binary search tree and a <code>target</code> value, return <em>the value in the BST that is closest to the</em> <code>target</code>. If there are multiple answers, print the smallest.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0270.Closest%20Binary%20Search%20Tree%20Value/images/closest1-1-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [4,2,5,1,3], target = 3.714286 <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1], target = 4.428571 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Search; 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 closestValue(root: TreeNode | null, target: number): number { let ans = 0; let diff = Number.POSITIVE_INFINITY; const dfs = (node: TreeNode | null): void => { if (!node) { return; } const nxt = Math.abs(target - node.val); if (nxt < diff || (nxt === diff && node.val < ans)) { diff = nxt; ans = node.val; } node = target < node.val ? node.left : node.right; dfs(node); }; dfs(root); return ans; }
271
Encode and Decode Strings
Medium
<p>Design an algorithm to encode <b>a list of strings</b> to <b>a string</b>. The encoded string is then sent over the network and is decoded back to the original list of strings.</p> <p>Machine 1 (sender) has the function:</p> <pre> string encode(vector&lt;string&gt; strs) { // ... your code return encoded_string; }</pre> Machine 2 (receiver) has the function: <pre> vector&lt;string&gt; decode(string s) { //... your code return strs; } </pre> <p>So Machine 1 does:</p> <pre> string encoded_string = encode(strs); </pre> <p>and Machine 2 does:</p> <pre> vector&lt;string&gt; strs2 = decode(encoded_string); </pre> <p><code>strs2</code> in Machine 2 should be the same as <code>strs</code> in Machine 1.</p> <p>Implement the <code>encode</code> and <code>decode</code> methods.</p> <p>You are not allowed to&nbsp;solve the problem using any serialize methods (such as <code>eval</code>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dummy_input = [&quot;Hello&quot;,&quot;World&quot;] <strong>Output:</strong> [&quot;Hello&quot;,&quot;World&quot;] <strong>Explanation:</strong> Machine 1: Codec encoder = new Codec(); String msg = encoder.encode(strs); Machine 1 ---msg---&gt; Machine 2 Machine 2: Codec decoder = new Codec(); String[] strs = decoder.decode(msg); </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dummy_input = [&quot;&quot;] <strong>Output:</strong> [&quot;&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> contains any possible characters out of <code>256</code> valid ASCII characters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up: </strong>Could you write a generalized algorithm to work on any possible set of characters?</p>
Design; Array; String
C++
class Codec { public: // Encodes a list of strings to a single string. string encode(vector<string>& strs) { string ans; for (string s : strs) { int size = s.size(); ans += string((const char*) &size, sizeof(size)); ans += s; } return ans; } // Decodes a single string to a list of strings. vector<string> decode(string s) { vector<string> ans; int i = 0, n = s.size(); int size = 0; while (i < n) { memcpy(&size, s.data() + i, sizeof(size)); i += sizeof(size); ans.push_back(s.substr(i, size)); i += size; } return ans; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.decode(codec.encode(strs));
271
Encode and Decode Strings
Medium
<p>Design an algorithm to encode <b>a list of strings</b> to <b>a string</b>. The encoded string is then sent over the network and is decoded back to the original list of strings.</p> <p>Machine 1 (sender) has the function:</p> <pre> string encode(vector&lt;string&gt; strs) { // ... your code return encoded_string; }</pre> Machine 2 (receiver) has the function: <pre> vector&lt;string&gt; decode(string s) { //... your code return strs; } </pre> <p>So Machine 1 does:</p> <pre> string encoded_string = encode(strs); </pre> <p>and Machine 2 does:</p> <pre> vector&lt;string&gt; strs2 = decode(encoded_string); </pre> <p><code>strs2</code> in Machine 2 should be the same as <code>strs</code> in Machine 1.</p> <p>Implement the <code>encode</code> and <code>decode</code> methods.</p> <p>You are not allowed to&nbsp;solve the problem using any serialize methods (such as <code>eval</code>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dummy_input = [&quot;Hello&quot;,&quot;World&quot;] <strong>Output:</strong> [&quot;Hello&quot;,&quot;World&quot;] <strong>Explanation:</strong> Machine 1: Codec encoder = new Codec(); String msg = encoder.encode(strs); Machine 1 ---msg---&gt; Machine 2 Machine 2: Codec decoder = new Codec(); String[] strs = decoder.decode(msg); </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dummy_input = [&quot;&quot;] <strong>Output:</strong> [&quot;&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> contains any possible characters out of <code>256</code> valid ASCII characters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up: </strong>Could you write a generalized algorithm to work on any possible set of characters?</p>
Design; Array; String
Go
type Codec struct { } // Encodes a list of strings to a single string. func (codec *Codec) Encode(strs []string) string { ans := &bytes.Buffer{} for _, s := range strs { t := fmt.Sprintf("%04d", len(s)) ans.WriteString(t) ans.WriteString(s) } return ans.String() } // Decodes a single string to a list of strings. func (codec *Codec) Decode(strs string) []string { ans := []string{} i, n := 0, len(strs) for i < n { t := strs[i : i+4] i += 4 size, _ := strconv.Atoi(t) ans = append(ans, strs[i:i+size]) i += size } return ans } // Your Codec object will be instantiated and called as such: // var codec Codec // codec.Decode(codec.Encode(strs));
271
Encode and Decode Strings
Medium
<p>Design an algorithm to encode <b>a list of strings</b> to <b>a string</b>. The encoded string is then sent over the network and is decoded back to the original list of strings.</p> <p>Machine 1 (sender) has the function:</p> <pre> string encode(vector&lt;string&gt; strs) { // ... your code return encoded_string; }</pre> Machine 2 (receiver) has the function: <pre> vector&lt;string&gt; decode(string s) { //... your code return strs; } </pre> <p>So Machine 1 does:</p> <pre> string encoded_string = encode(strs); </pre> <p>and Machine 2 does:</p> <pre> vector&lt;string&gt; strs2 = decode(encoded_string); </pre> <p><code>strs2</code> in Machine 2 should be the same as <code>strs</code> in Machine 1.</p> <p>Implement the <code>encode</code> and <code>decode</code> methods.</p> <p>You are not allowed to&nbsp;solve the problem using any serialize methods (such as <code>eval</code>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dummy_input = [&quot;Hello&quot;,&quot;World&quot;] <strong>Output:</strong> [&quot;Hello&quot;,&quot;World&quot;] <strong>Explanation:</strong> Machine 1: Codec encoder = new Codec(); String msg = encoder.encode(strs); Machine 1 ---msg---&gt; Machine 2 Machine 2: Codec decoder = new Codec(); String[] strs = decoder.decode(msg); </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dummy_input = [&quot;&quot;] <strong>Output:</strong> [&quot;&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> contains any possible characters out of <code>256</code> valid ASCII characters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up: </strong>Could you write a generalized algorithm to work on any possible set of characters?</p>
Design; Array; String
Java
public class Codec { // Encodes a list of strings to a single string. public String encode(List<String> strs) { StringBuilder ans = new StringBuilder(); for (String s : strs) { ans.append((char) s.length()).append(s); } return ans.toString(); } // Decodes a single string to a list of strings. public List<String> decode(String s) { List<String> ans = new ArrayList<>(); int i = 0, n = s.length(); while (i < n) { int size = s.charAt(i++); ans.add(s.substring(i, i + size)); i += size; } return ans; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(strs));
271
Encode and Decode Strings
Medium
<p>Design an algorithm to encode <b>a list of strings</b> to <b>a string</b>. The encoded string is then sent over the network and is decoded back to the original list of strings.</p> <p>Machine 1 (sender) has the function:</p> <pre> string encode(vector&lt;string&gt; strs) { // ... your code return encoded_string; }</pre> Machine 2 (receiver) has the function: <pre> vector&lt;string&gt; decode(string s) { //... your code return strs; } </pre> <p>So Machine 1 does:</p> <pre> string encoded_string = encode(strs); </pre> <p>and Machine 2 does:</p> <pre> vector&lt;string&gt; strs2 = decode(encoded_string); </pre> <p><code>strs2</code> in Machine 2 should be the same as <code>strs</code> in Machine 1.</p> <p>Implement the <code>encode</code> and <code>decode</code> methods.</p> <p>You are not allowed to&nbsp;solve the problem using any serialize methods (such as <code>eval</code>).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> dummy_input = [&quot;Hello&quot;,&quot;World&quot;] <strong>Output:</strong> [&quot;Hello&quot;,&quot;World&quot;] <strong>Explanation:</strong> Machine 1: Codec encoder = new Codec(); String msg = encoder.encode(strs); Machine 1 ---msg---&gt; Machine 2 Machine 2: Codec decoder = new Codec(); String[] strs = decoder.decode(msg); </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dummy_input = [&quot;&quot;] <strong>Output:</strong> [&quot;&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> contains any possible characters out of <code>256</code> valid ASCII characters.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up: </strong>Could you write a generalized algorithm to work on any possible set of characters?</p>
Design; Array; String
Python
class Codec: def encode(self, strs: List[str]) -> str: """Encodes a list of strings to a single string.""" ans = [] for s in strs: ans.append("{:4}".format(len(s)) + s) return "".join(ans) def decode(self, s: str) -> List[str]: """Decodes a single string to a list of strings.""" ans = [] i, n = 0, len(s) while i < n: size = int(s[i : i + 4]) i += 4 ans.append(s[i : i + size]) i += size return ans # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(strs))
272
Closest Binary Search Tree Value II
Hard
<p>Given the <code>root</code> of a binary search tree, a <code>target</code> value, and an integer <code>k</code>, return <em>the </em><code>k</code><em> values in the BST that are closest to the</em> <code>target</code>. You may return the answer in <strong>any order</strong>.</p> <p>You are <strong>guaranteed</strong> to have only one unique set of <code>k</code> values in the BST that are closest to the <code>target</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0272.Closest%20Binary%20Search%20Tree%20Value%20II/images/closest1-1-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [4,2,5,1,3], target = 3.714286, k = 2 <strong>Output:</strong> [4,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1], target = 0.000000, k = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Assume that the BST is balanced. Could you solve it in less than <code>O(n)</code> runtime (where <code>n = total nodes</code>)?</p>
Stack; Tree; Depth-First Search; Binary Search Tree; Two Pointers; Binary Tree; Heap (Priority Queue)
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: queue<int> q; double target; int k; vector<int> closestKValues(TreeNode* root, double target, int k) { this->target = target; this->k = k; dfs(root); vector<int> ans; while (!q.empty()) { ans.push_back(q.front()); q.pop(); } return ans; } void dfs(TreeNode* root) { if (!root) return; dfs(root->left); if (q.size() < k) q.push(root->val); else { if (abs(root->val - target) >= abs(q.front() - target)) return; q.pop(); q.push(root->val); } dfs(root->right); } };
272
Closest Binary Search Tree Value II
Hard
<p>Given the <code>root</code> of a binary search tree, a <code>target</code> value, and an integer <code>k</code>, return <em>the </em><code>k</code><em> values in the BST that are closest to the</em> <code>target</code>. You may return the answer in <strong>any order</strong>.</p> <p>You are <strong>guaranteed</strong> to have only one unique set of <code>k</code> values in the BST that are closest to the <code>target</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0272.Closest%20Binary%20Search%20Tree%20Value%20II/images/closest1-1-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [4,2,5,1,3], target = 3.714286, k = 2 <strong>Output:</strong> [4,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1], target = 0.000000, k = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Assume that the BST is balanced. Could you solve it in less than <code>O(n)</code> runtime (where <code>n = total nodes</code>)?</p>
Stack; Tree; Depth-First Search; Binary Search Tree; Two Pointers; Binary Tree; Heap (Priority Queue)
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func closestKValues(root *TreeNode, target float64, k int) []int { var ans []int var dfs func(root *TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Left) if len(ans) < k { ans = append(ans, root.Val) } else { if math.Abs(float64(root.Val)-target) >= math.Abs(float64(ans[0])-target) { return } ans = ans[1:] ans = append(ans, root.Val) } dfs(root.Right) } dfs(root) return ans }
272
Closest Binary Search Tree Value II
Hard
<p>Given the <code>root</code> of a binary search tree, a <code>target</code> value, and an integer <code>k</code>, return <em>the </em><code>k</code><em> values in the BST that are closest to the</em> <code>target</code>. You may return the answer in <strong>any order</strong>.</p> <p>You are <strong>guaranteed</strong> to have only one unique set of <code>k</code> values in the BST that are closest to the <code>target</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0272.Closest%20Binary%20Search%20Tree%20Value%20II/images/closest1-1-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [4,2,5,1,3], target = 3.714286, k = 2 <strong>Output:</strong> [4,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1], target = 0.000000, k = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Assume that the BST is balanced. Could you solve it in less than <code>O(n)</code> runtime (where <code>n = total nodes</code>)?</p>
Stack; Tree; Depth-First Search; Binary Search Tree; Two Pointers; Binary Tree; Heap (Priority Queue)
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 { private List<Integer> ans; private double target; private int k; public List<Integer> closestKValues(TreeNode root, double target, int k) { ans = new LinkedList<>(); this.target = target; this.k = k; dfs(root); return ans; } private void dfs(TreeNode root) { if (root == null) { return; } dfs(root.left); if (ans.size() < k) { ans.add(root.val); } else { if (Math.abs(root.val - target) >= Math.abs(ans.get(0) - target)) { return; } ans.remove(0); ans.add(root.val); } dfs(root.right); } }
272
Closest Binary Search Tree Value II
Hard
<p>Given the <code>root</code> of a binary search tree, a <code>target</code> value, and an integer <code>k</code>, return <em>the </em><code>k</code><em> values in the BST that are closest to the</em> <code>target</code>. You may return the answer in <strong>any order</strong>.</p> <p>You are <strong>guaranteed</strong> to have only one unique set of <code>k</code> values in the BST that are closest to the <code>target</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0272.Closest%20Binary%20Search%20Tree%20Value%20II/images/closest1-1-tree.jpg" style="width: 292px; height: 302px;" /> <pre> <strong>Input:</strong> root = [4,2,5,1,3], target = 3.714286, k = 2 <strong>Output:</strong> [4,3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [1], target = 0.000000, k = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Assume that the BST is balanced. Could you solve it in less than <code>O(n)</code> runtime (where <code>n = total nodes</code>)?</p>
Stack; Tree; Depth-First Search; Binary Search Tree; Two Pointers; Binary Tree; Heap (Priority Queue)
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 closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]: def dfs(root): if root is None: return dfs(root.left) if len(q) < k: q.append(root.val) else: if abs(root.val - target) >= abs(q[0] - target): return q.popleft() q.append(root.val) dfs(root.right) q = deque() dfs(root) return list(q)
273
Integer to English Words
Hard
<p>Convert a non-negative integer <code>num</code> to its English words representation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 123 <strong>Output:</strong> &quot;One Hundred Twenty Three&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 12345 <strong>Output:</strong> &quot;Twelve Thousand Three Hundred Forty Five&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = 1234567 <strong>Output:</strong> &quot;One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Recursion; Math; String
C#
using System.Collections.Generic; using System.Linq; public class Solution { private string[] bases = { "Thousand", "Million", "Billion" }; public string NumberToWords(int num) { if (num == 0) { return "Zero"; } var baseIndex = -1; var parts = new List<string>(); while (num > 0) { var part = NumberToWordsInternal(num % 1000); if (part.Length > 0 && baseIndex >= 0) { part = JoinParts(part, bases[baseIndex]); } parts.Add(part); baseIndex++; num /= 1000; } parts.Reverse(); return JoinParts(parts); } private string JoinParts(IEnumerable<string> parts) { return string.Join(" ", parts.Where(p => p.Length > 0)); } private string JoinParts(params string[] parts) { return JoinParts((IEnumerable<string>)parts); } private string NumberToWordsInternal(int num) { switch(num) { case 0: return ""; case 1: return "One"; case 2: return "Two"; case 3: return "Three"; case 4: return "Four"; case 5: return "Five"; case 6: return "Six"; case 7: return "Seven"; case 8: return "Eight"; case 9: return "Nine"; case 10: return "Ten"; case 11: return "Eleven"; case 12: return "Twelve"; case 13: return "Thirteen"; case 14: return "Fourteen"; case 15: return "Fifteen"; case 16: return "Sixteen"; case 17: return "Seventeen"; case 18: return "Eighteen"; case 19: return "Nineteen"; } if (num < 100) { string part1; switch (num/10) { case 2: part1 = "Twenty"; break; case 3: part1 = "Thirty"; break; case 4: part1 = "Forty"; break; case 5: part1 = "Fifty"; break; case 6: part1 = "Sixty"; break; case 7: part1 = "Seventy"; break; case 8: part1 = "Eighty"; break; case 9: default: part1 = "Ninety"; break; } var part2 = NumberToWordsInternal(num % 10); return JoinParts(part1, part2); } { var part1 = NumberToWordsInternal(num / 100); var part2 = NumberToWordsInternal(num % 100); return JoinParts(part1, "Hundred", part2); } } }
273
Integer to English Words
Hard
<p>Convert a non-negative integer <code>num</code> to its English words representation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 123 <strong>Output:</strong> &quot;One Hundred Twenty Three&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 12345 <strong>Output:</strong> &quot;Twelve Thousand Three Hundred Forty Five&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = 1234567 <strong>Output:</strong> &quot;One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Recursion; Math; String
Java
class Solution { private static Map<Integer, String> map; static { map = new HashMap<>(); map.put(1, "One"); map.put(2, "Two"); map.put(3, "Three"); map.put(4, "Four"); map.put(5, "Five"); map.put(6, "Six"); map.put(7, "Seven"); map.put(8, "Eight"); map.put(9, "Nine"); map.put(10, "Ten"); map.put(11, "Eleven"); map.put(12, "Twelve"); map.put(13, "Thirteen"); map.put(14, "Fourteen"); map.put(15, "Fifteen"); map.put(16, "Sixteen"); map.put(17, "Seventeen"); map.put(18, "Eighteen"); map.put(19, "Nineteen"); map.put(20, "Twenty"); map.put(30, "Thirty"); map.put(40, "Forty"); map.put(50, "Fifty"); map.put(60, "Sixty"); map.put(70, "Seventy"); map.put(80, "Eighty"); map.put(90, "Ninety"); map.put(100, "Hundred"); map.put(1000, "Thousand"); map.put(1000000, "Million"); map.put(1000000000, "Billion"); } public String numberToWords(int num) { if (num == 0) { return "Zero"; } StringBuilder sb = new StringBuilder(); for (int i = 1000000000; i >= 1000; i /= 1000) { if (num >= i) { sb.append(get3Digits(num / i)).append(' ').append(map.get(i)); num %= i; } } if (num > 0) { sb.append(get3Digits(num)); } return sb.substring(1); } private String get3Digits(int num) { StringBuilder sb = new StringBuilder(); if (num >= 100) { sb.append(' ').append(map.get(num / 100)).append(' ').append(map.get(100)); num %= 100; } if (num > 0) { if (num < 20 || num % 10 == 0) { sb.append(' ').append(map.get(num)); } else { sb.append(' ').append(map.get(num / 10 * 10)).append(' ').append(map.get(num % 10)); } } return sb.toString(); } }
273
Integer to English Words
Hard
<p>Convert a non-negative integer <code>num</code> to its English words representation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 123 <strong>Output:</strong> &quot;One Hundred Twenty Three&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 12345 <strong>Output:</strong> &quot;Twelve Thousand Three Hundred Forty Five&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = 1234567 <strong>Output:</strong> &quot;One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Recursion; Math; String
JavaScript
function numberToWords(num) { if (num === 0) return 'Zero'; // prettier-ignore const f = (x) => { const dict1 = ['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen',] const dict2 = ['','','Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety',] let ans = '' if (x <= 19) ans = dict1[x] ?? '' else if (x < 100) ans = `${dict2[Math.floor(x / 10)]} ${f(x % 10)}` else if (x < 10 ** 3) ans = `${dict1[Math.floor(x / 100)]} Hundred ${f(x % 100)}` else if (x < 10 ** 6) ans = `${f(Math.floor(x / 10 ** 3))} Thousand ${f(x % 10 ** 3)}` else if (x < 10 ** 9) ans = `${f(Math.floor(x / 10 ** 6))} Million ${f(x % 10 ** 6)}` else ans = `${f(Math.floor(x / 10 ** 9))} Billion ${f(x % 10 ** 9)}` return ans.trim() } return f(num); }
273
Integer to English Words
Hard
<p>Convert a non-negative integer <code>num</code> to its English words representation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 123 <strong>Output:</strong> &quot;One Hundred Twenty Three&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 12345 <strong>Output:</strong> &quot;Twelve Thousand Three Hundred Forty Five&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = 1234567 <strong>Output:</strong> &quot;One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Recursion; Math; String
Python
class Solution: def numberToWords(self, num: int) -> str: if num == 0: return 'Zero' lt20 = [ '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', ] tens = [ '', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety', ] thousands = ['Billion', 'Million', 'Thousand', ''] def transfer(num): if num == 0: return '' if num < 20: return lt20[num] + ' ' if num < 100: return tens[num // 10] + ' ' + transfer(num % 10) return lt20[num // 100] + ' Hundred ' + transfer(num % 100) res = [] i, j = 1000000000, 0 while i > 0: if num // i != 0: res.append(transfer(num // i)) res.append(thousands[j]) res.append(' ') num %= i j += 1 i //= 1000 return ''.join(res).strip()
273
Integer to English Words
Hard
<p>Convert a non-negative integer <code>num</code> to its English words representation.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = 123 <strong>Output:</strong> &quot;One Hundred Twenty Three&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = 12345 <strong>Output:</strong> &quot;Twelve Thousand Three Hundred Forty Five&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = 1234567 <strong>Output:</strong> &quot;One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Recursion; Math; String
TypeScript
function numberToWords(num: number): string { if (num === 0) return 'Zero'; // prettier-ignore const f = (x: number): string => { const dict1 = ['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen',] const dict2 = ['','','Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety',] let ans = '' if (x <= 19) ans = dict1[x] ?? '' else if (x < 100) ans = `${dict2[Math.floor(x / 10)]} ${f(x % 10)}` else if (x < 10 ** 3) ans = `${dict1[Math.floor(x / 100)]} Hundred ${f(x % 100)}` else if (x < 10 ** 6) ans = `${f(Math.floor(x / 10 ** 3))} Thousand ${f(x % 10 ** 3)}` else if (x < 10 ** 9) ans = `${f(Math.floor(x / 10 ** 6))} Million ${f(x % 10 ** 6)}` else ans = `${f(Math.floor(x / 10 ** 9))} Billion ${f(x % 10 ** 9)}` return ans.trim() } return f(num); }
274
H-Index
Medium
<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper, return <em>the researcher&#39;s h-index</em>.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> citations = [3,0,6,1,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> citations = [1,3,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == citations.length</code></li> <li><code>1 &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= citations[i] &lt;= 1000</code></li> </ul>
Array; Counting Sort; Sorting
C++
class Solution { public: int hIndex(vector<int>& citations) { sort(citations.rbegin(), citations.rend()); for (int h = citations.size(); h; --h) { if (citations[h - 1] >= h) { return h; } } return 0; } };
274
H-Index
Medium
<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper, return <em>the researcher&#39;s h-index</em>.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> citations = [3,0,6,1,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> citations = [1,3,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == citations.length</code></li> <li><code>1 &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= citations[i] &lt;= 1000</code></li> </ul>
Array; Counting Sort; Sorting
Go
func hIndex(citations []int) int { sort.Ints(citations) n := len(citations) for h := n; h > 0; h-- { if citations[n-h] >= h { return h } } return 0 }
274
H-Index
Medium
<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper, return <em>the researcher&#39;s h-index</em>.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> citations = [3,0,6,1,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> citations = [1,3,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == citations.length</code></li> <li><code>1 &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= citations[i] &lt;= 1000</code></li> </ul>
Array; Counting Sort; Sorting
Java
class Solution { public int hIndex(int[] citations) { Arrays.sort(citations); int n = citations.length; for (int h = n; h > 0; --h) { if (citations[n - h] >= h) { return h; } } return 0; } }
274
H-Index
Medium
<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper, return <em>the researcher&#39;s h-index</em>.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> citations = [3,0,6,1,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> citations = [1,3,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == citations.length</code></li> <li><code>1 &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= citations[i] &lt;= 1000</code></li> </ul>
Array; Counting Sort; Sorting
Python
class Solution: def hIndex(self, citations: List[int]) -> int: citations.sort(reverse=True) for h in range(len(citations), 0, -1): if citations[h - 1] >= h: return h return 0
274
H-Index
Medium
<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper, return <em>the researcher&#39;s h-index</em>.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> citations = [3,0,6,1,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> citations = [1,3,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == citations.length</code></li> <li><code>1 &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= citations[i] &lt;= 1000</code></li> </ul>
Array; Counting Sort; Sorting
Rust
impl Solution { #[allow(dead_code)] pub fn h_index(citations: Vec<i32>) -> i32 { let mut citations = citations; citations.sort_by(|&lhs, &rhs| rhs.cmp(&lhs)); let n = citations.len(); for i in (1..=n).rev() { if citations[i - 1] >= (i as i32) { return i as i32; } } 0 } }
274
H-Index
Medium
<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper, return <em>the researcher&#39;s h-index</em>.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> citations = [3,0,6,1,5] <strong>Output:</strong> 3 <strong>Explanation:</strong> [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> citations = [1,3,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == citations.length</code></li> <li><code>1 &lt;= n &lt;= 5000</code></li> <li><code>0 &lt;= citations[i] &lt;= 1000</code></li> </ul>
Array; Counting Sort; Sorting
TypeScript
function hIndex(citations: number[]): number { citations.sort((a, b) => b - a); for (let h = citations.length; h; --h) { if (citations[h - 1] >= h) { return h; } } return 0; }
275
H-Index II
Medium
<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper and <code>citations</code> is sorted in <strong>non-descending order</strong>, return <em>the researcher&#39;s h-index</em>.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p> <p>You must write an algorithm that runs in logarithmic time.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> citations = [0,1,3,5,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> citations = [1,2,100] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == citations.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= citations[i] &lt;= 1000</code></li> <li><code>citations</code> is sorted in <strong>ascending order</strong>.</li> </ul>
Array; Binary Search
C++
class Solution { public: int hIndex(vector<int>& citations) { int n = citations.size(); int left = 0, right = n; while (left < right) { int mid = (left + right + 1) >> 1; if (citations[n - mid] >= mid) left = mid; else right = mid - 1; } return left; } };
275
H-Index II
Medium
<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper and <code>citations</code> is sorted in <strong>non-descending order</strong>, return <em>the researcher&#39;s h-index</em>.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p> <p>You must write an algorithm that runs in logarithmic time.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> citations = [0,1,3,5,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> citations = [1,2,100] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == citations.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= citations[i] &lt;= 1000</code></li> <li><code>citations</code> is sorted in <strong>ascending order</strong>.</li> </ul>
Array; Binary Search
C#
public class Solution { public int HIndex(int[] citations) { int n = citations.Length; int left = 0, right = n; while (left < right) { int mid = (left + right + 1) >> 1; if (citations[n - mid] >= mid) { left = mid; } else { right = mid - 1; } } return left; } }
275
H-Index II
Medium
<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper and <code>citations</code> is sorted in <strong>non-descending order</strong>, return <em>the researcher&#39;s h-index</em>.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p> <p>You must write an algorithm that runs in logarithmic time.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> citations = [0,1,3,5,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> citations = [1,2,100] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == citations.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= citations[i] &lt;= 1000</code></li> <li><code>citations</code> is sorted in <strong>ascending order</strong>.</li> </ul>
Array; Binary Search
Go
func hIndex(citations []int) int { n := len(citations) left, right := 0, n for left < right { mid := (left + right + 1) >> 1 if citations[n-mid] >= mid { left = mid } else { right = mid - 1 } } return left }
275
H-Index II
Medium
<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper and <code>citations</code> is sorted in <strong>non-descending order</strong>, return <em>the researcher&#39;s h-index</em>.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p> <p>You must write an algorithm that runs in logarithmic time.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> citations = [0,1,3,5,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> citations = [1,2,100] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == citations.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= citations[i] &lt;= 1000</code></li> <li><code>citations</code> is sorted in <strong>ascending order</strong>.</li> </ul>
Array; Binary Search
Java
class Solution { public int hIndex(int[] citations) { int n = citations.length; int left = 0, right = n; while (left < right) { int mid = (left + right) >>> 1; if (citations[mid] >= n - mid) { right = mid; } else { left = mid + 1; } } return n - left; } }
275
H-Index II
Medium
<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper and <code>citations</code> is sorted in <strong>non-descending order</strong>, return <em>the researcher&#39;s h-index</em>.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p> <p>You must write an algorithm that runs in logarithmic time.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> citations = [0,1,3,5,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> citations = [1,2,100] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == citations.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= citations[i] &lt;= 1000</code></li> <li><code>citations</code> is sorted in <strong>ascending order</strong>.</li> </ul>
Array; Binary Search
Python
class Solution: def hIndex(self, citations: List[int]) -> int: n = len(citations) left, right = 0, n while left < right: mid = (left + right + 1) >> 1 if citations[n - mid] >= mid: left = mid else: right = mid - 1 return left
275
H-Index II
Medium
<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper and <code>citations</code> is sorted in <strong>non-descending order</strong>, return <em>the researcher&#39;s h-index</em>.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p> <p>You must write an algorithm that runs in logarithmic time.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> citations = [0,1,3,5,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> citations = [1,2,100] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == citations.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= citations[i] &lt;= 1000</code></li> <li><code>citations</code> is sorted in <strong>ascending order</strong>.</li> </ul>
Array; Binary Search
Rust
impl Solution { pub fn h_index(citations: Vec<i32>) -> i32 { let n = citations.len(); let (mut left, mut right) = (0, n); while left < right { let mid = ((left + right + 1) >> 1) as usize; if citations[n - mid] >= (mid as i32) { left = mid; } else { right = mid - 1; } } left as i32 } }
275
H-Index II
Medium
<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper and <code>citations</code> is sorted in <strong>non-descending order</strong>, return <em>the researcher&#39;s h-index</em>.</p> <p>According to the <a href="https://en.wikipedia.org/wiki/H-index" target="_blank">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p> <p>You must write an algorithm that runs in logarithmic time.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> citations = [0,1,3,5,6] <strong>Output:</strong> 3 <strong>Explanation:</strong> [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> citations = [1,2,100] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == citations.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= citations[i] &lt;= 1000</code></li> <li><code>citations</code> is sorted in <strong>ascending order</strong>.</li> </ul>
Array; Binary Search
TypeScript
function hIndex(citations: number[]): number { const n = citations.length; let left = 0, right = n; while (left < right) { const mid = (left + right + 1) >> 1; if (citations[n - mid] >= mid) { left = mid; } else { right = mid - 1; } } return left; }
276
Paint Fence
Medium
<p>You are painting a fence of <code>n</code> posts with <code>k</code> different colors. You must paint the posts following these rules:</p> <ul> <li>Every post must be painted <strong>exactly one</strong> color.</li> <li>There <strong>cannot</strong> be three or more <strong>consecutive</strong> posts with the same color.</li> </ul> <p>Given the two integers <code>n</code> and <code>k</code>, return <em>the <strong>number of ways</strong> you can paint the fence</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/0200-0299/0276.Paint%20Fence/images/paintfenceex1.png" style="width: 507px; height: 313px;" /> <pre> <strong>Input:</strong> n = 3, k = 2 <strong>Output:</strong> 6 <strong>Explanation: </strong>All the possibilities are shown. Note that painting all the posts red or all the posts green is invalid because there cannot be three posts in a row with the same color. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, k = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 7, k = 2 <strong>Output:</strong> 42 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li>The testcases are generated such that the answer is in the range <code>[0, 2<sup>31</sup> - 1]</code> for the given <code>n</code> and <code>k</code>.</li> </ul>
Dynamic Programming
C++
class Solution { public: int numWays(int n, int k) { vector<int> f(n); vector<int> g(n); f[0] = k; for (int i = 1; i < n; ++i) { f[i] = (f[i - 1] + g[i - 1]) * (k - 1); g[i] = f[i - 1]; } return f[n - 1] + g[n - 1]; } };
276
Paint Fence
Medium
<p>You are painting a fence of <code>n</code> posts with <code>k</code> different colors. You must paint the posts following these rules:</p> <ul> <li>Every post must be painted <strong>exactly one</strong> color.</li> <li>There <strong>cannot</strong> be three or more <strong>consecutive</strong> posts with the same color.</li> </ul> <p>Given the two integers <code>n</code> and <code>k</code>, return <em>the <strong>number of ways</strong> you can paint the fence</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/0200-0299/0276.Paint%20Fence/images/paintfenceex1.png" style="width: 507px; height: 313px;" /> <pre> <strong>Input:</strong> n = 3, k = 2 <strong>Output:</strong> 6 <strong>Explanation: </strong>All the possibilities are shown. Note that painting all the posts red or all the posts green is invalid because there cannot be three posts in a row with the same color. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, k = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 7, k = 2 <strong>Output:</strong> 42 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li>The testcases are generated such that the answer is in the range <code>[0, 2<sup>31</sup> - 1]</code> for the given <code>n</code> and <code>k</code>.</li> </ul>
Dynamic Programming
Go
func numWays(n int, k int) int { f := make([]int, n) g := make([]int, n) f[0] = k for i := 1; i < n; i++ { f[i] = (f[i-1] + g[i-1]) * (k - 1) g[i] = f[i-1] } return f[n-1] + g[n-1] }
276
Paint Fence
Medium
<p>You are painting a fence of <code>n</code> posts with <code>k</code> different colors. You must paint the posts following these rules:</p> <ul> <li>Every post must be painted <strong>exactly one</strong> color.</li> <li>There <strong>cannot</strong> be three or more <strong>consecutive</strong> posts with the same color.</li> </ul> <p>Given the two integers <code>n</code> and <code>k</code>, return <em>the <strong>number of ways</strong> you can paint the fence</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/0200-0299/0276.Paint%20Fence/images/paintfenceex1.png" style="width: 507px; height: 313px;" /> <pre> <strong>Input:</strong> n = 3, k = 2 <strong>Output:</strong> 6 <strong>Explanation: </strong>All the possibilities are shown. Note that painting all the posts red or all the posts green is invalid because there cannot be three posts in a row with the same color. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, k = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 7, k = 2 <strong>Output:</strong> 42 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li>The testcases are generated such that the answer is in the range <code>[0, 2<sup>31</sup> - 1]</code> for the given <code>n</code> and <code>k</code>.</li> </ul>
Dynamic Programming
Java
class Solution { public int numWays(int n, int k) { int[] f = new int[n]; int[] g = new int[n]; f[0] = k; for (int i = 1; i < n; ++i) { f[i] = (f[i - 1] + g[i - 1]) * (k - 1); g[i] = f[i - 1]; } return f[n - 1] + g[n - 1]; } }
276
Paint Fence
Medium
<p>You are painting a fence of <code>n</code> posts with <code>k</code> different colors. You must paint the posts following these rules:</p> <ul> <li>Every post must be painted <strong>exactly one</strong> color.</li> <li>There <strong>cannot</strong> be three or more <strong>consecutive</strong> posts with the same color.</li> </ul> <p>Given the two integers <code>n</code> and <code>k</code>, return <em>the <strong>number of ways</strong> you can paint the fence</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/0200-0299/0276.Paint%20Fence/images/paintfenceex1.png" style="width: 507px; height: 313px;" /> <pre> <strong>Input:</strong> n = 3, k = 2 <strong>Output:</strong> 6 <strong>Explanation: </strong>All the possibilities are shown. Note that painting all the posts red or all the posts green is invalid because there cannot be three posts in a row with the same color. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, k = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 7, k = 2 <strong>Output:</strong> 42 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li>The testcases are generated such that the answer is in the range <code>[0, 2<sup>31</sup> - 1]</code> for the given <code>n</code> and <code>k</code>.</li> </ul>
Dynamic Programming
Python
class Solution: def numWays(self, n: int, k: int) -> int: f = [0] * n g = [0] * n f[0] = k for i in range(1, n): f[i] = (f[i - 1] + g[i - 1]) * (k - 1) g[i] = f[i - 1] return f[-1] + g[-1]
276
Paint Fence
Medium
<p>You are painting a fence of <code>n</code> posts with <code>k</code> different colors. You must paint the posts following these rules:</p> <ul> <li>Every post must be painted <strong>exactly one</strong> color.</li> <li>There <strong>cannot</strong> be three or more <strong>consecutive</strong> posts with the same color.</li> </ul> <p>Given the two integers <code>n</code> and <code>k</code>, return <em>the <strong>number of ways</strong> you can paint the fence</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/0200-0299/0276.Paint%20Fence/images/paintfenceex1.png" style="width: 507px; height: 313px;" /> <pre> <strong>Input:</strong> n = 3, k = 2 <strong>Output:</strong> 6 <strong>Explanation: </strong>All the possibilities are shown. Note that painting all the posts red or all the posts green is invalid because there cannot be three posts in a row with the same color. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, k = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 7, k = 2 <strong>Output:</strong> 42 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 50</code></li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> <li>The testcases are generated such that the answer is in the range <code>[0, 2<sup>31</sup> - 1]</code> for the given <code>n</code> and <code>k</code>.</li> </ul>
Dynamic Programming
TypeScript
function numWays(n: number, k: number): number { const f: number[] = Array(n).fill(0); const g: number[] = Array(n).fill(0); f[0] = k; for (let i = 1; i < n; ++i) { f[i] = (f[i - 1] + g[i - 1]) * (k - 1); g[i] = f[i - 1]; } return f[n - 1] + g[n - 1]; }
277
Find the Celebrity
Medium
<p>Suppose you are at a party with <code>n</code> people labeled from <code>0</code> to <code>n - 1</code> and among them, there may exist one celebrity. The definition of a celebrity is that all the other <code>n - 1</code> people know the celebrity, but the celebrity does not know any of them.</p> <p>Now you want to find out who the celebrity is or verify that there is not one. You are only allowed to ask questions like: &quot;Hi, A. Do you know B?&quot; to get information about whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).</p> <p>You are given an integer <code>n</code> and a helper function <code>bool knows(a, b)</code> that tells you whether <code>a</code> knows <code>b</code>. Implement a function <code>int findCelebrity(n)</code>. There will be exactly one celebrity if they are at the party.</p> <p>Return <em>the celebrity&#39;s label if there is a celebrity at the party</em>. If there is no celebrity, return <code>-1</code>.</p> <p><strong>Note</strong> that the <code>n x n</code> 2D array <code>graph</code> given as input is <strong>not</strong> directly available to you, and instead <strong>only</strong> accessible through the helper function <code>knows</code>. <code>graph[i][j] == 1</code> represents person <code>i</code> knows person <code>j</code>, wherease <code>graph[i][j] == 0</code> represents person <code>j</code> does not know person <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0277.Find%20the%20Celebrity/images/g1.jpg" style="width: 224px; height: 145px;" /> <pre> <strong>Input:</strong> graph = [[1,1,0],[0,1,0],[1,1,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> There are three persons labeled with 0, 1 and 2. graph[i][j] = 1 means person i knows person j, otherwise graph[i][j] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0277.Find%20the%20Celebrity/images/g2.jpg" style="width: 224px; height: 145px;" /> <pre> <strong>Input:</strong> graph = [[1,0,1],[1,1,0],[0,1,1]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no celebrity. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == graph.length == graph[i].length</code></li> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>graph[i][j]</code> is <code>0</code> or <code>1</code>.</li> <li><code>graph[i][i] == 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If the maximum number of allowed calls to the API <code>knows</code> is <code>3 * n</code>, could you find a solution without exceeding the maximum number of calls?</p>
Graph; Two Pointers; Interactive
C++
/* The knows API is defined for you. bool knows(int a, int b); */ class Solution { public: int findCelebrity(int n) { int ans = 0; for (int i = 1; i < n; ++i) { if (knows(ans, i)) { ans = i; } } for (int i = 0; i < n; ++i) { if (ans != i) { if (knows(ans, i) || !knows(i, ans)) { return -1; } } } return ans; } };
277
Find the Celebrity
Medium
<p>Suppose you are at a party with <code>n</code> people labeled from <code>0</code> to <code>n - 1</code> and among them, there may exist one celebrity. The definition of a celebrity is that all the other <code>n - 1</code> people know the celebrity, but the celebrity does not know any of them.</p> <p>Now you want to find out who the celebrity is or verify that there is not one. You are only allowed to ask questions like: &quot;Hi, A. Do you know B?&quot; to get information about whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).</p> <p>You are given an integer <code>n</code> and a helper function <code>bool knows(a, b)</code> that tells you whether <code>a</code> knows <code>b</code>. Implement a function <code>int findCelebrity(n)</code>. There will be exactly one celebrity if they are at the party.</p> <p>Return <em>the celebrity&#39;s label if there is a celebrity at the party</em>. If there is no celebrity, return <code>-1</code>.</p> <p><strong>Note</strong> that the <code>n x n</code> 2D array <code>graph</code> given as input is <strong>not</strong> directly available to you, and instead <strong>only</strong> accessible through the helper function <code>knows</code>. <code>graph[i][j] == 1</code> represents person <code>i</code> knows person <code>j</code>, wherease <code>graph[i][j] == 0</code> represents person <code>j</code> does not know person <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0277.Find%20the%20Celebrity/images/g1.jpg" style="width: 224px; height: 145px;" /> <pre> <strong>Input:</strong> graph = [[1,1,0],[0,1,0],[1,1,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> There are three persons labeled with 0, 1 and 2. graph[i][j] = 1 means person i knows person j, otherwise graph[i][j] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0277.Find%20the%20Celebrity/images/g2.jpg" style="width: 224px; height: 145px;" /> <pre> <strong>Input:</strong> graph = [[1,0,1],[1,1,0],[0,1,1]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no celebrity. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == graph.length == graph[i].length</code></li> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>graph[i][j]</code> is <code>0</code> or <code>1</code>.</li> <li><code>graph[i][i] == 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If the maximum number of allowed calls to the API <code>knows</code> is <code>3 * n</code>, could you find a solution without exceeding the maximum number of calls?</p>
Graph; Two Pointers; Interactive
Go
/** * The knows API is already defined for you. * knows := func(a int, b int) bool */ func solution(knows func(a int, b int) bool) func(n int) int { return func(n int) int { ans := 0 for i := 1; i < n; i++ { if knows(ans, i) { ans = i } } for i := 0; i < n; i++ { if ans != i { if knows(ans, i) || !knows(i, ans) { return -1 } } } return ans } }
277
Find the Celebrity
Medium
<p>Suppose you are at a party with <code>n</code> people labeled from <code>0</code> to <code>n - 1</code> and among them, there may exist one celebrity. The definition of a celebrity is that all the other <code>n - 1</code> people know the celebrity, but the celebrity does not know any of them.</p> <p>Now you want to find out who the celebrity is or verify that there is not one. You are only allowed to ask questions like: &quot;Hi, A. Do you know B?&quot; to get information about whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).</p> <p>You are given an integer <code>n</code> and a helper function <code>bool knows(a, b)</code> that tells you whether <code>a</code> knows <code>b</code>. Implement a function <code>int findCelebrity(n)</code>. There will be exactly one celebrity if they are at the party.</p> <p>Return <em>the celebrity&#39;s label if there is a celebrity at the party</em>. If there is no celebrity, return <code>-1</code>.</p> <p><strong>Note</strong> that the <code>n x n</code> 2D array <code>graph</code> given as input is <strong>not</strong> directly available to you, and instead <strong>only</strong> accessible through the helper function <code>knows</code>. <code>graph[i][j] == 1</code> represents person <code>i</code> knows person <code>j</code>, wherease <code>graph[i][j] == 0</code> represents person <code>j</code> does not know person <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0277.Find%20the%20Celebrity/images/g1.jpg" style="width: 224px; height: 145px;" /> <pre> <strong>Input:</strong> graph = [[1,1,0],[0,1,0],[1,1,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> There are three persons labeled with 0, 1 and 2. graph[i][j] = 1 means person i knows person j, otherwise graph[i][j] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0277.Find%20the%20Celebrity/images/g2.jpg" style="width: 224px; height: 145px;" /> <pre> <strong>Input:</strong> graph = [[1,0,1],[1,1,0],[0,1,1]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no celebrity. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == graph.length == graph[i].length</code></li> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>graph[i][j]</code> is <code>0</code> or <code>1</code>.</li> <li><code>graph[i][i] == 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If the maximum number of allowed calls to the API <code>knows</code> is <code>3 * n</code>, could you find a solution without exceeding the maximum number of calls?</p>
Graph; Two Pointers; Interactive
Java
/* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ public class Solution extends Relation { public int findCelebrity(int n) { int ans = 0; for (int i = 1; i < n; ++i) { if (knows(ans, i)) { ans = i; } } for (int i = 0; i < n; ++i) { if (ans != i) { if (knows(ans, i) || !knows(i, ans)) { return -1; } } } return ans; } }
277
Find the Celebrity
Medium
<p>Suppose you are at a party with <code>n</code> people labeled from <code>0</code> to <code>n - 1</code> and among them, there may exist one celebrity. The definition of a celebrity is that all the other <code>n - 1</code> people know the celebrity, but the celebrity does not know any of them.</p> <p>Now you want to find out who the celebrity is or verify that there is not one. You are only allowed to ask questions like: &quot;Hi, A. Do you know B?&quot; to get information about whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).</p> <p>You are given an integer <code>n</code> and a helper function <code>bool knows(a, b)</code> that tells you whether <code>a</code> knows <code>b</code>. Implement a function <code>int findCelebrity(n)</code>. There will be exactly one celebrity if they are at the party.</p> <p>Return <em>the celebrity&#39;s label if there is a celebrity at the party</em>. If there is no celebrity, return <code>-1</code>.</p> <p><strong>Note</strong> that the <code>n x n</code> 2D array <code>graph</code> given as input is <strong>not</strong> directly available to you, and instead <strong>only</strong> accessible through the helper function <code>knows</code>. <code>graph[i][j] == 1</code> represents person <code>i</code> knows person <code>j</code>, wherease <code>graph[i][j] == 0</code> represents person <code>j</code> does not know person <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0277.Find%20the%20Celebrity/images/g1.jpg" style="width: 224px; height: 145px;" /> <pre> <strong>Input:</strong> graph = [[1,1,0],[0,1,0],[1,1,1]] <strong>Output:</strong> 1 <strong>Explanation:</strong> There are three persons labeled with 0, 1 and 2. graph[i][j] = 1 means person i knows person j, otherwise graph[i][j] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0277.Find%20the%20Celebrity/images/g2.jpg" style="width: 224px; height: 145px;" /> <pre> <strong>Input:</strong> graph = [[1,0,1],[1,1,0],[0,1,1]] <strong>Output:</strong> -1 <strong>Explanation:</strong> There is no celebrity. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == graph.length == graph[i].length</code></li> <li><code>2 &lt;= n &lt;= 100</code></li> <li><code>graph[i][j]</code> is <code>0</code> or <code>1</code>.</li> <li><code>graph[i][i] == 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If the maximum number of allowed calls to the API <code>knows</code> is <code>3 * n</code>, could you find a solution without exceeding the maximum number of calls?</p>
Graph; Two Pointers; Interactive
Python
# The knows API is already defined for you. # return a bool, whether a knows b # def knows(a: int, b: int) -> bool: class Solution: def findCelebrity(self, n: int) -> int: ans = 0 for i in range(1, n): if knows(ans, i): ans = i for i in range(n): if ans != i: if knows(ans, i) or not knows(i, ans): return -1 return ans
278
First Bad Version
Easy
<p>You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.</p> <p>Suppose you have <code>n</code> versions <code>[1, 2, ..., n]</code> and you want to find out the first bad one, which causes all the following ones to be bad.</p> <p>You are given an API <code>bool isBadVersion(version)</code> which returns whether <code>version</code> is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, bad = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> call isBadVersion(3) -&gt; false call isBadVersion(5)&nbsp;-&gt; true call isBadVersion(4)&nbsp;-&gt; true Then 4 is the first bad version. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, bad = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= bad &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Binary Search; Interactive
C++
// The API isBadVersion is defined for you. // bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int l = 1, r = n; while (l < r) { int mid = l + (r - l) / 2; if (isBadVersion(mid)) { r = mid; } else { l = mid + 1; } } return l; } };
278
First Bad Version
Easy
<p>You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.</p> <p>Suppose you have <code>n</code> versions <code>[1, 2, ..., n]</code> and you want to find out the first bad one, which causes all the following ones to be bad.</p> <p>You are given an API <code>bool isBadVersion(version)</code> which returns whether <code>version</code> is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, bad = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> call isBadVersion(3) -&gt; false call isBadVersion(5)&nbsp;-&gt; true call isBadVersion(4)&nbsp;-&gt; true Then 4 is the first bad version. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, bad = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= bad &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Binary Search; Interactive
Go
/** * Forward declaration of isBadVersion API. * @param version your guess about first bad version * @return true if current version is bad * false if current version is good * func isBadVersion(version int) bool; */ func firstBadVersion(n int) int { l, r := 1, n for l < r { mid := (l + r) >> 1 if isBadVersion(mid) { r = mid } else { l = mid + 1 } } return l }
278
First Bad Version
Easy
<p>You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.</p> <p>Suppose you have <code>n</code> versions <code>[1, 2, ..., n]</code> and you want to find out the first bad one, which causes all the following ones to be bad.</p> <p>You are given an API <code>bool isBadVersion(version)</code> which returns whether <code>version</code> is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, bad = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> call isBadVersion(3) -&gt; false call isBadVersion(5)&nbsp;-&gt; true call isBadVersion(4)&nbsp;-&gt; true Then 4 is the first bad version. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, bad = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= bad &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Binary Search; Interactive
Java
/* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ public class Solution extends VersionControl { public int firstBadVersion(int n) { int l = 1, r = n; while (l < r) { int mid = (l + r) >>> 1; if (isBadVersion(mid)) { r = mid; } else { l = mid + 1; } } return l; } }
278
First Bad Version
Easy
<p>You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.</p> <p>Suppose you have <code>n</code> versions <code>[1, 2, ..., n]</code> and you want to find out the first bad one, which causes all the following ones to be bad.</p> <p>You are given an API <code>bool isBadVersion(version)</code> which returns whether <code>version</code> is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, bad = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> call isBadVersion(3) -&gt; false call isBadVersion(5)&nbsp;-&gt; true call isBadVersion(4)&nbsp;-&gt; true Then 4 is the first bad version. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, bad = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= bad &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Binary Search; Interactive
JavaScript
/** * Definition for isBadVersion() * * @param {integer} version number * @return {boolean} whether the version is bad * isBadVersion = function(version) { * ... * }; */ /** * @param {function} isBadVersion() * @return {function} */ var solution = function (isBadVersion) { /** * @param {integer} n Total versions * @return {integer} The first bad version */ return function (n) { let [l, r] = [1, n]; while (l < r) { const mid = (l + r) >>> 1; if (isBadVersion(mid)) { r = mid; } else { l = mid + 1; } } return l; }; };
278
First Bad Version
Easy
<p>You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.</p> <p>Suppose you have <code>n</code> versions <code>[1, 2, ..., n]</code> and you want to find out the first bad one, which causes all the following ones to be bad.</p> <p>You are given an API <code>bool isBadVersion(version)</code> which returns whether <code>version</code> is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, bad = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> call isBadVersion(3) -&gt; false call isBadVersion(5)&nbsp;-&gt; true call isBadVersion(4)&nbsp;-&gt; true Then 4 is the first bad version. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, bad = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= bad &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Binary Search; Interactive
Python
# The isBadVersion API is already defined for you. # def isBadVersion(version: int) -> bool: class Solution: def firstBadVersion(self, n: int) -> int: l, r = 1, n while l < r: mid = (l + r) >> 1 if isBadVersion(mid): r = mid else: l = mid + 1 return l
278
First Bad Version
Easy
<p>You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.</p> <p>Suppose you have <code>n</code> versions <code>[1, 2, ..., n]</code> and you want to find out the first bad one, which causes all the following ones to be bad.</p> <p>You are given an API <code>bool isBadVersion(version)</code> which returns whether <code>version</code> is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, bad = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> call isBadVersion(3) -&gt; false call isBadVersion(5)&nbsp;-&gt; true call isBadVersion(4)&nbsp;-&gt; true Then 4 is the first bad version. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, bad = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= bad &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Binary Search; Interactive
Rust
// The API isBadVersion is defined for you. // isBadVersion(version:i32)-> bool; // to call it use self.isBadVersion(version) impl Solution { pub fn first_bad_version(&self, n: i32) -> i32 { let (mut l, mut r) = (1, n); while l < r { let mid = l + (r - l) / 2; if self.isBadVersion(mid) { r = mid; } else { l = mid + 1; } } l } }
278
First Bad Version
Easy
<p>You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.</p> <p>Suppose you have <code>n</code> versions <code>[1, 2, ..., n]</code> and you want to find out the first bad one, which causes all the following ones to be bad.</p> <p>You are given an API <code>bool isBadVersion(version)</code> which returns whether <code>version</code> is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 5, bad = 4 <strong>Output:</strong> 4 <strong>Explanation:</strong> call isBadVersion(3) -&gt; false call isBadVersion(5)&nbsp;-&gt; true call isBadVersion(4)&nbsp;-&gt; true Then 4 is the first bad version. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1, bad = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= bad &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Binary Search; Interactive
TypeScript
/** * The knows API is defined in the parent class Relation. * isBadVersion(version: number): boolean { * ... * }; */ var solution = function (isBadVersion: any) { return function (n: number): number { let [l, r] = [1, n]; while (l < r) { const mid = (l + r) >>> 1; if (isBadVersion(mid)) { r = mid; } else { l = mid + 1; } } return l; }; };
279
Perfect Squares
Medium
<p>Given an integer <code>n</code>, return <em>the least number of perfect square numbers that sum to</em> <code>n</code>.</p> <p>A <strong>perfect square</strong> is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, <code>1</code>, <code>4</code>, <code>9</code>, and <code>16</code> are perfect squares while <code>3</code> and <code>11</code> are not.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 12 <strong>Output:</strong> 3 <strong>Explanation:</strong> 12 = 4 + 4 + 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 13 <strong>Output:</strong> 2 <strong>Explanation:</strong> 13 = 4 + 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul>
Breadth-First Search; Math; Dynamic Programming
C++
class Solution { public: int numSquares(int n) { int m = sqrt(n); int f[m + 1][n + 1]; memset(f, 0x3f, sizeof(f)); f[0][0] = 0; for (int i = 1; i <= m; ++i) { for (int j = 0; j <= n; ++j) { f[i][j] = f[i - 1][j]; if (j >= i * i) { f[i][j] = min(f[i][j], f[i][j - i * i] + 1); } } } return f[m][n]; } };
279
Perfect Squares
Medium
<p>Given an integer <code>n</code>, return <em>the least number of perfect square numbers that sum to</em> <code>n</code>.</p> <p>A <strong>perfect square</strong> is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, <code>1</code>, <code>4</code>, <code>9</code>, and <code>16</code> are perfect squares while <code>3</code> and <code>11</code> are not.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 12 <strong>Output:</strong> 3 <strong>Explanation:</strong> 12 = 4 + 4 + 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 13 <strong>Output:</strong> 2 <strong>Explanation:</strong> 13 = 4 + 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul>
Breadth-First Search; Math; Dynamic Programming
Go
func numSquares(n int) int { m := int(math.Sqrt(float64(n))) f := make([][]int, m+1) const inf = 1 << 30 for i := range f { f[i] = make([]int, n+1) for j := range f[i] { f[i][j] = inf } } f[0][0] = 0 for i := 1; i <= m; i++ { for j := 0; j <= n; j++ { f[i][j] = f[i-1][j] if j >= i*i { f[i][j] = min(f[i][j], f[i][j-i*i]+1) } } } return f[m][n] }
279
Perfect Squares
Medium
<p>Given an integer <code>n</code>, return <em>the least number of perfect square numbers that sum to</em> <code>n</code>.</p> <p>A <strong>perfect square</strong> is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, <code>1</code>, <code>4</code>, <code>9</code>, and <code>16</code> are perfect squares while <code>3</code> and <code>11</code> are not.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 12 <strong>Output:</strong> 3 <strong>Explanation:</strong> 12 = 4 + 4 + 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 13 <strong>Output:</strong> 2 <strong>Explanation:</strong> 13 = 4 + 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul>
Breadth-First Search; Math; Dynamic Programming
Java
class Solution { public int numSquares(int n) { int m = (int) Math.sqrt(n); int[][] f = new int[m + 1][n + 1]; for (var g : f) { Arrays.fill(g, 1 << 30); } f[0][0] = 0; for (int i = 1; i <= m; ++i) { for (int j = 0; j <= n; ++j) { f[i][j] = f[i - 1][j]; if (j >= i * i) { f[i][j] = Math.min(f[i][j], f[i][j - i * i] + 1); } } } return f[m][n]; } }
279
Perfect Squares
Medium
<p>Given an integer <code>n</code>, return <em>the least number of perfect square numbers that sum to</em> <code>n</code>.</p> <p>A <strong>perfect square</strong> is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, <code>1</code>, <code>4</code>, <code>9</code>, and <code>16</code> are perfect squares while <code>3</code> and <code>11</code> are not.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 12 <strong>Output:</strong> 3 <strong>Explanation:</strong> 12 = 4 + 4 + 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 13 <strong>Output:</strong> 2 <strong>Explanation:</strong> 13 = 4 + 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul>
Breadth-First Search; Math; Dynamic Programming
Python
class Solution: def numSquares(self, n: int) -> int: m = int(sqrt(n)) f = [[inf] * (n + 1) for _ in range(m + 1)] f[0][0] = 0 for i in range(1, m + 1): for j in range(n + 1): f[i][j] = f[i - 1][j] if j >= i * i: f[i][j] = min(f[i][j], f[i][j - i * i] + 1) return f[m][n]
279
Perfect Squares
Medium
<p>Given an integer <code>n</code>, return <em>the least number of perfect square numbers that sum to</em> <code>n</code>.</p> <p>A <strong>perfect square</strong> is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, <code>1</code>, <code>4</code>, <code>9</code>, and <code>16</code> are perfect squares while <code>3</code> and <code>11</code> are not.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 12 <strong>Output:</strong> 3 <strong>Explanation:</strong> 12 = 4 + 4 + 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 13 <strong>Output:</strong> 2 <strong>Explanation:</strong> 13 = 4 + 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul>
Breadth-First Search; Math; Dynamic Programming
Rust
impl Solution { pub fn num_squares(n: i32) -> i32 { let (row, col) = ((n as f32).sqrt().floor() as usize, n as usize); let mut dp = vec![vec![i32::MAX; col + 1]; row + 1]; dp[0][0] = 0; for i in 1..=row { for j in 0..=col { dp[i][j] = dp[i - 1][j]; if j >= i * i { dp[i][j] = std::cmp::min(dp[i][j], dp[i][j - i * i] + 1); } } } dp[row][col] } }
279
Perfect Squares
Medium
<p>Given an integer <code>n</code>, return <em>the least number of perfect square numbers that sum to</em> <code>n</code>.</p> <p>A <strong>perfect square</strong> is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, <code>1</code>, <code>4</code>, <code>9</code>, and <code>16</code> are perfect squares while <code>3</code> and <code>11</code> are not.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 12 <strong>Output:</strong> 3 <strong>Explanation:</strong> 12 = 4 + 4 + 4. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 13 <strong>Output:</strong> 2 <strong>Explanation:</strong> 13 = 4 + 9. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul>
Breadth-First Search; Math; Dynamic Programming
TypeScript
function numSquares(n: number): number { const m = Math.floor(Math.sqrt(n)); const f: number[][] = Array(m + 1) .fill(0) .map(() => Array(n + 1).fill(1 << 30)); f[0][0] = 0; for (let i = 1; i <= m; ++i) { for (let j = 0; j <= n; ++j) { f[i][j] = f[i - 1][j]; if (j >= i * i) { f[i][j] = Math.min(f[i][j], f[i][j - i * i] + 1); } } } return f[m][n]; }
280
Wiggle Sort
Medium
<p>Given an integer array <code>nums</code>, reorder it such that <code>nums[0] &lt;= nums[1] &gt;= nums[2] &lt;= nums[3]...</code>.</p> <p>You may assume the input array always has a valid answer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,2,1,6,4] <strong>Output:</strong> [3,5,1,6,2,4] <strong>Explanation:</strong> [1,6,2,5,3,4] is also accepted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,6,5,6,3,8] <strong>Output:</strong> [6,6,5,6,3,8] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li>It is guaranteed that there will be an answer for the given input <code>nums</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve the problem in <code>O(n)</code> time complexity?</p>
Greedy; Array; Sorting
C++
class Solution { public: void wiggleSort(vector<int>& nums) { for (int i = 1; i < nums.size(); ++i) { if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) { swap(nums[i], nums[i - 1]); } } } };
280
Wiggle Sort
Medium
<p>Given an integer array <code>nums</code>, reorder it such that <code>nums[0] &lt;= nums[1] &gt;= nums[2] &lt;= nums[3]...</code>.</p> <p>You may assume the input array always has a valid answer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,2,1,6,4] <strong>Output:</strong> [3,5,1,6,2,4] <strong>Explanation:</strong> [1,6,2,5,3,4] is also accepted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,6,5,6,3,8] <strong>Output:</strong> [6,6,5,6,3,8] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li>It is guaranteed that there will be an answer for the given input <code>nums</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve the problem in <code>O(n)</code> time complexity?</p>
Greedy; Array; Sorting
Go
func wiggleSort(nums []int) { for i := 1; i < len(nums); i++ { if (i%2 == 1 && nums[i] < nums[i-1]) || (i%2 == 0 && nums[i] > nums[i-1]) { nums[i], nums[i-1] = nums[i-1], nums[i] } } }
280
Wiggle Sort
Medium
<p>Given an integer array <code>nums</code>, reorder it such that <code>nums[0] &lt;= nums[1] &gt;= nums[2] &lt;= nums[3]...</code>.</p> <p>You may assume the input array always has a valid answer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,2,1,6,4] <strong>Output:</strong> [3,5,1,6,2,4] <strong>Explanation:</strong> [1,6,2,5,3,4] is also accepted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,6,5,6,3,8] <strong>Output:</strong> [6,6,5,6,3,8] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li>It is guaranteed that there will be an answer for the given input <code>nums</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve the problem in <code>O(n)</code> time complexity?</p>
Greedy; Array; Sorting
Java
class Solution { public void wiggleSort(int[] nums) { for (int i = 1; i < nums.length; ++i) { if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) { swap(nums, i, i - 1); } } } private void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } }
280
Wiggle Sort
Medium
<p>Given an integer array <code>nums</code>, reorder it such that <code>nums[0] &lt;= nums[1] &gt;= nums[2] &lt;= nums[3]...</code>.</p> <p>You may assume the input array always has a valid answer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,5,2,1,6,4] <strong>Output:</strong> [3,5,1,6,2,4] <strong>Explanation:</strong> [1,6,2,5,3,4] is also accepted. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [6,6,5,6,3,8] <strong>Output:</strong> [6,6,5,6,3,8] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li>It is guaranteed that there will be an answer for the given input <code>nums</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve the problem in <code>O(n)</code> time complexity?</p>
Greedy; Array; Sorting
Python
class Solution: def wiggleSort(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ for i in range(1, len(nums)): if (i % 2 == 1 and nums[i] < nums[i - 1]) or ( i % 2 == 0 and nums[i] > nums[i - 1] ): nums[i], nums[i - 1] = nums[i - 1], nums[i]
281
Zigzag Iterator
Medium
<p>Given two vectors of integers <code>v1</code> and <code>v2</code>, implement an iterator to return their elements alternately.</p> <p>Implement the <code>ZigzagIterator</code> class:</p> <ul> <li><code>ZigzagIterator(List&lt;int&gt; v1, List&lt;int&gt; v2)</code> initializes the object with the two vectors <code>v1</code> and <code>v2</code>.</li> <li><code>boolean hasNext()</code> returns <code>true</code> if the iterator still has elements, and <code>false</code> otherwise.</li> <li><code>int next()</code> returns the current element of the iterator and moves the iterator to the next element.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> v1 = [1,2], v2 = [3,4,5,6] <strong>Output:</strong> [1,3,2,4,5,6] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,3,2,4,5,6]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> v1 = [1], v2 = [] <strong>Output:</strong> [1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> v1 = [], v2 = [1] <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= v1.length, v2.length &lt;= 1000</code></li> <li><code>1 &lt;= v1.length + v2.length &lt;= 2000</code></li> <li><code>-2<sup>31</sup> &lt;= v1[i], v2[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if you are given <code>k</code> vectors? How well can your code be extended to such cases?</p> <p><strong>Clarification for the follow-up question:</strong></p> <p>The &quot;Zigzag&quot; order is not clearly defined and is ambiguous for <code>k &gt; 2</code> cases. If &quot;Zigzag&quot; does not look right to you, replace &quot;Zigzag&quot; with &quot;Cyclic&quot;.</p> <p><strong>Follow-up Example:</strong></p> <pre> <strong>Input:</strong> v1 = [1,2,3], v2 = [4,5,6,7], v3 = [8,9] <strong>Output:</strong> [1,4,8,2,5,9,3,6,7] </pre>
Design; Queue; Array; Iterator
Go
type ZigzagIterator struct { cur int size int indexes []int vectors [][]int } func Constructor(v1, v2 []int) *ZigzagIterator { return &ZigzagIterator{ cur: 0, size: 2, indexes: []int{0, 0}, vectors: [][]int{v1, v2}, } } func (this *ZigzagIterator) next() int { vector := this.vectors[this.cur] index := this.indexes[this.cur] res := vector[index] this.indexes[this.cur]++ this.cur = (this.cur + 1) % this.size return res } func (this *ZigzagIterator) hasNext() bool { start := this.cur for this.indexes[this.cur] == len(this.vectors[this.cur]) { this.cur = (this.cur + 1) % this.size if start == this.cur { return false } } return true } /** * Your ZigzagIterator object will be instantiated and called as such: * obj := Constructor(param_1, param_2); * for obj.hasNext() { * ans = append(ans, obj.next()) * } */
281
Zigzag Iterator
Medium
<p>Given two vectors of integers <code>v1</code> and <code>v2</code>, implement an iterator to return their elements alternately.</p> <p>Implement the <code>ZigzagIterator</code> class:</p> <ul> <li><code>ZigzagIterator(List&lt;int&gt; v1, List&lt;int&gt; v2)</code> initializes the object with the two vectors <code>v1</code> and <code>v2</code>.</li> <li><code>boolean hasNext()</code> returns <code>true</code> if the iterator still has elements, and <code>false</code> otherwise.</li> <li><code>int next()</code> returns the current element of the iterator and moves the iterator to the next element.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> v1 = [1,2], v2 = [3,4,5,6] <strong>Output:</strong> [1,3,2,4,5,6] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,3,2,4,5,6]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> v1 = [1], v2 = [] <strong>Output:</strong> [1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> v1 = [], v2 = [1] <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= v1.length, v2.length &lt;= 1000</code></li> <li><code>1 &lt;= v1.length + v2.length &lt;= 2000</code></li> <li><code>-2<sup>31</sup> &lt;= v1[i], v2[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if you are given <code>k</code> vectors? How well can your code be extended to such cases?</p> <p><strong>Clarification for the follow-up question:</strong></p> <p>The &quot;Zigzag&quot; order is not clearly defined and is ambiguous for <code>k &gt; 2</code> cases. If &quot;Zigzag&quot; does not look right to you, replace &quot;Zigzag&quot; with &quot;Cyclic&quot;.</p> <p><strong>Follow-up Example:</strong></p> <pre> <strong>Input:</strong> v1 = [1,2,3], v2 = [4,5,6,7], v3 = [8,9] <strong>Output:</strong> [1,4,8,2,5,9,3,6,7] </pre>
Design; Queue; Array; Iterator
Java
public class ZigzagIterator { private int cur; private int size; private List<Integer> indexes = new ArrayList<>(); private List<List<Integer>> vectors = new ArrayList<>(); public ZigzagIterator(List<Integer> v1, List<Integer> v2) { cur = 0; size = 2; indexes.add(0); indexes.add(0); vectors.add(v1); vectors.add(v2); } public int next() { List<Integer> vector = vectors.get(cur); int index = indexes.get(cur); int res = vector.get(index); indexes.set(cur, index + 1); cur = (cur + 1) % size; return res; } public boolean hasNext() { int start = cur; while (indexes.get(cur) == vectors.get(cur).size()) { cur = (cur + 1) % size; if (start == cur) { return false; } } return true; } } /** * Your ZigzagIterator object will be instantiated and called as such: * ZigzagIterator i = new ZigzagIterator(v1, v2); * while (i.hasNext()) v[f()] = i.next(); */
281
Zigzag Iterator
Medium
<p>Given two vectors of integers <code>v1</code> and <code>v2</code>, implement an iterator to return their elements alternately.</p> <p>Implement the <code>ZigzagIterator</code> class:</p> <ul> <li><code>ZigzagIterator(List&lt;int&gt; v1, List&lt;int&gt; v2)</code> initializes the object with the two vectors <code>v1</code> and <code>v2</code>.</li> <li><code>boolean hasNext()</code> returns <code>true</code> if the iterator still has elements, and <code>false</code> otherwise.</li> <li><code>int next()</code> returns the current element of the iterator and moves the iterator to the next element.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> v1 = [1,2], v2 = [3,4,5,6] <strong>Output:</strong> [1,3,2,4,5,6] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,3,2,4,5,6]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> v1 = [1], v2 = [] <strong>Output:</strong> [1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> v1 = [], v2 = [1] <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= v1.length, v2.length &lt;= 1000</code></li> <li><code>1 &lt;= v1.length + v2.length &lt;= 2000</code></li> <li><code>-2<sup>31</sup> &lt;= v1[i], v2[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if you are given <code>k</code> vectors? How well can your code be extended to such cases?</p> <p><strong>Clarification for the follow-up question:</strong></p> <p>The &quot;Zigzag&quot; order is not clearly defined and is ambiguous for <code>k &gt; 2</code> cases. If &quot;Zigzag&quot; does not look right to you, replace &quot;Zigzag&quot; with &quot;Cyclic&quot;.</p> <p><strong>Follow-up Example:</strong></p> <pre> <strong>Input:</strong> v1 = [1,2,3], v2 = [4,5,6,7], v3 = [8,9] <strong>Output:</strong> [1,4,8,2,5,9,3,6,7] </pre>
Design; Queue; Array; Iterator
Python
class ZigzagIterator: def __init__(self, v1: List[int], v2: List[int]): self.cur = 0 self.size = 2 self.indexes = [0] * self.size self.vectors = [v1, v2] def next(self) -> int: vector = self.vectors[self.cur] index = self.indexes[self.cur] res = vector[index] self.indexes[self.cur] = index + 1 self.cur = (self.cur + 1) % self.size return res def hasNext(self) -> bool: start = self.cur while self.indexes[self.cur] == len(self.vectors[self.cur]): self.cur = (self.cur + 1) % self.size if self.cur == start: return False return True # Your ZigzagIterator object will be instantiated and called as such: # i, v = ZigzagIterator(v1, v2), [] # while i.hasNext(): v.append(i.next())
281
Zigzag Iterator
Medium
<p>Given two vectors of integers <code>v1</code> and <code>v2</code>, implement an iterator to return their elements alternately.</p> <p>Implement the <code>ZigzagIterator</code> class:</p> <ul> <li><code>ZigzagIterator(List&lt;int&gt; v1, List&lt;int&gt; v2)</code> initializes the object with the two vectors <code>v1</code> and <code>v2</code>.</li> <li><code>boolean hasNext()</code> returns <code>true</code> if the iterator still has elements, and <code>false</code> otherwise.</li> <li><code>int next()</code> returns the current element of the iterator and moves the iterator to the next element.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> v1 = [1,2], v2 = [3,4,5,6] <strong>Output:</strong> [1,3,2,4,5,6] <strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,3,2,4,5,6]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> v1 = [1], v2 = [] <strong>Output:</strong> [1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> v1 = [], v2 = [1] <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= v1.length, v2.length &lt;= 1000</code></li> <li><code>1 &lt;= v1.length + v2.length &lt;= 2000</code></li> <li><code>-2<sup>31</sup> &lt;= v1[i], v2[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if you are given <code>k</code> vectors? How well can your code be extended to such cases?</p> <p><strong>Clarification for the follow-up question:</strong></p> <p>The &quot;Zigzag&quot; order is not clearly defined and is ambiguous for <code>k &gt; 2</code> cases. If &quot;Zigzag&quot; does not look right to you, replace &quot;Zigzag&quot; with &quot;Cyclic&quot;.</p> <p><strong>Follow-up Example:</strong></p> <pre> <strong>Input:</strong> v1 = [1,2,3], v2 = [4,5,6,7], v3 = [8,9] <strong>Output:</strong> [1,4,8,2,5,9,3,6,7] </pre>
Design; Queue; Array; Iterator
Rust
struct ZigzagIterator { v1: Vec<i32>, v2: Vec<i32>, /// `false` represents `v1`, `true` represents `v2` flag: bool, } impl ZigzagIterator { fn new(v1: Vec<i32>, v2: Vec<i32>) -> Self { Self { v1, v2, // Initially beginning with `v1` flag: false, } } fn next(&mut self) -> i32 { if !self.flag { // v1 if self.v1.is_empty() && !self.v2.is_empty() { self.flag = true; let ret = self.v2.remove(0); return ret; } if self.v2.is_empty() { let ret = self.v1.remove(0); return ret; } let ret = self.v1.remove(0); self.flag = true; return ret; } else { // v2 if self.v2.is_empty() && !self.v1.is_empty() { self.flag = false; let ret = self.v1.remove(0); return ret; } if self.v1.is_empty() { let ret = self.v2.remove(0); return ret; } let ret = self.v2.remove(0); self.flag = false; return ret; } } fn has_next(&self) -> bool { !self.v1.is_empty() || !self.v2.is_empty() } }
282
Expression Add Operators
Hard
<p>Given a string <code>num</code> that contains only digits and an integer <code>target</code>, return <em><strong>all possibilities</strong> to insert the binary operators </em><code>&#39;+&#39;</code><em>, </em><code>&#39;-&#39;</code><em>, and/or </em><code>&#39;*&#39;</code><em> between the digits of </em><code>num</code><em> so that the resultant expression evaluates to the </em><code>target</code><em> value</em>.</p> <p>Note that operands in the returned expressions <strong>should not</strong> contain leading zeros.</p> <p><strong>Note</strong> that a number can contain multiple digits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;123&quot;, target = 6 <strong>Output:</strong> [&quot;1*2*3&quot;,&quot;1+2+3&quot;] <strong>Explanation:</strong> Both &quot;1*2*3&quot; and &quot;1+2+3&quot; evaluate to 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;232&quot;, target = 8 <strong>Output:</strong> [&quot;2*3+2&quot;,&quot;2+3*2&quot;] <strong>Explanation:</strong> Both &quot;2*3+2&quot; and &quot;2+3*2&quot; evaluate to 8. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;3456237490&quot;, target = 9191 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no expressions that can be created from &quot;3456237490&quot; to evaluate to 9191. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 10</code></li> <li><code>num</code> consists of only digits.</li> <li><code>-2<sup>31</sup> &lt;= target &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; String; Backtracking
C#
using System; using System.Collections.Generic; public class Expression { public long Value; public override string ToString() { return Value.ToString(); } } public class BinaryExpression : Expression { public char Operator; public Expression LeftChild; public Expression RightChild; public override string ToString() { return string.Format("{0}{1}{2}", LeftChild, Operator, RightChild); } } public class Solution { public IList<string> AddOperators(string num, int target) { var results = new List<string>(); if (string.IsNullOrEmpty(num)) return results; this.num = num; this.results = new List<Expression>[num.Length, num.Length, 3]; foreach (var ex in Search(0, num.Length - 1, 0)) { if (ex.Value == target) { results.Add(ex.ToString()); } } return results; } private string num; private List<Expression>[,,] results; private List<Expression> Search(int left, int right, int level) { if (results[left, right, level] != null) { return results[left, right, level]; } var result = new List<Expression>(); if (level < 2) { for (var i = left + 1; i <= right; ++i) { List<Expression> leftResult, rightResult; leftResult = Search(left, i - 1, level); rightResult = Search(i, right, level + 1); foreach (var l in leftResult) { foreach (var r in rightResult) { var newObjects = new List<Tuple<char, long>>(); if (level == 0) { newObjects.Add(Tuple.Create('+', l.Value + r.Value)); newObjects.Add(Tuple.Create('-', l.Value - r.Value)); } else { newObjects.Add(Tuple.Create('*', l.Value * r.Value)); } foreach (var newObject in newObjects) { result.Add(new BinaryExpression { Value = newObject.Item2, Operator = newObject.Item1, LeftChild = l, RightChild = r }); } } } } } else { if (left == right || num[left] != '0') { long x = 0; for (var i = left; i <= right; ++i) { x = x * 10 + num[i] - '0'; } result.Add(new Expression { Value = x }); } } if (level < 2) { result.AddRange(Search(left, right, level + 1)); } return results[left, right, level] = result; } }
282
Expression Add Operators
Hard
<p>Given a string <code>num</code> that contains only digits and an integer <code>target</code>, return <em><strong>all possibilities</strong> to insert the binary operators </em><code>&#39;+&#39;</code><em>, </em><code>&#39;-&#39;</code><em>, and/or </em><code>&#39;*&#39;</code><em> between the digits of </em><code>num</code><em> so that the resultant expression evaluates to the </em><code>target</code><em> value</em>.</p> <p>Note that operands in the returned expressions <strong>should not</strong> contain leading zeros.</p> <p><strong>Note</strong> that a number can contain multiple digits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;123&quot;, target = 6 <strong>Output:</strong> [&quot;1*2*3&quot;,&quot;1+2+3&quot;] <strong>Explanation:</strong> Both &quot;1*2*3&quot; and &quot;1+2+3&quot; evaluate to 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;232&quot;, target = 8 <strong>Output:</strong> [&quot;2*3+2&quot;,&quot;2+3*2&quot;] <strong>Explanation:</strong> Both &quot;2*3+2&quot; and &quot;2+3*2&quot; evaluate to 8. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;3456237490&quot;, target = 9191 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no expressions that can be created from &quot;3456237490&quot; to evaluate to 9191. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 10</code></li> <li><code>num</code> consists of only digits.</li> <li><code>-2<sup>31</sup> &lt;= target &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; String; Backtracking
Java
class Solution { private List<String> ans; private String num; private int target; public List<String> addOperators(String num, int target) { ans = new ArrayList<>(); this.num = num; this.target = target; dfs(0, 0, 0, ""); return ans; } private void dfs(int u, long prev, long curr, String path) { if (u == num.length()) { if (curr == target) ans.add(path); return; } for (int i = u; i < num.length(); i++) { if (i != u && num.charAt(u) == '0') { break; } long next = Long.parseLong(num.substring(u, i + 1)); if (u == 0) { dfs(i + 1, next, next, path + next); } else { dfs(i + 1, next, curr + next, path + "+" + next); dfs(i + 1, -next, curr - next, path + "-" + next); dfs(i + 1, prev * next, curr - prev + prev * next, path + "*" + next); } } } }
282
Expression Add Operators
Hard
<p>Given a string <code>num</code> that contains only digits and an integer <code>target</code>, return <em><strong>all possibilities</strong> to insert the binary operators </em><code>&#39;+&#39;</code><em>, </em><code>&#39;-&#39;</code><em>, and/or </em><code>&#39;*&#39;</code><em> between the digits of </em><code>num</code><em> so that the resultant expression evaluates to the </em><code>target</code><em> value</em>.</p> <p>Note that operands in the returned expressions <strong>should not</strong> contain leading zeros.</p> <p><strong>Note</strong> that a number can contain multiple digits.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> num = &quot;123&quot;, target = 6 <strong>Output:</strong> [&quot;1*2*3&quot;,&quot;1+2+3&quot;] <strong>Explanation:</strong> Both &quot;1*2*3&quot; and &quot;1+2+3&quot; evaluate to 6. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> num = &quot;232&quot;, target = 8 <strong>Output:</strong> [&quot;2*3+2&quot;,&quot;2+3*2&quot;] <strong>Explanation:</strong> Both &quot;2*3+2&quot; and &quot;2+3*2&quot; evaluate to 8. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> num = &quot;3456237490&quot;, target = 9191 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no expressions that can be created from &quot;3456237490&quot; to evaluate to 9191. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num.length &lt;= 10</code></li> <li><code>num</code> consists of only digits.</li> <li><code>-2<sup>31</sup> &lt;= target &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; String; Backtracking
Python
class Solution: def addOperators(self, num: str, target: int) -> List[str]: ans = [] def dfs(u, prev, curr, path): if u == len(num): if curr == target: ans.append(path) return for i in range(u, len(num)): if i != u and num[u] == '0': break next = int(num[u : i + 1]) if u == 0: dfs(i + 1, next, next, path + str(next)) else: dfs(i + 1, next, curr + next, path + "+" + str(next)) dfs(i + 1, -next, curr - next, path + "-" + str(next)) dfs( i + 1, prev * next, curr - prev + prev * next, path + "*" + str(next), ) dfs(0, 0, 0, "") return ans
283
Move Zeroes
Easy
<p>Given an integer array <code>nums</code>, move all <code>0</code>&#39;s to the end of it while maintaining the relative order of the non-zero elements.</p> <p><strong>Note</strong> that you must do this in-place without making a copy of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [0,1,0,3,12] <strong>Output:</strong> [1,3,12,0,0] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you minimize the total number of operations done?
Array; Two Pointers
C
void moveZeroes(int* nums, int numsSize) { int k = 0; for (int i = 0; i < numsSize; ++i) { if (nums[i] != 0) { int t = nums[i]; nums[i] = nums[k]; nums[k++] = t; } } }
283
Move Zeroes
Easy
<p>Given an integer array <code>nums</code>, move all <code>0</code>&#39;s to the end of it while maintaining the relative order of the non-zero elements.</p> <p><strong>Note</strong> that you must do this in-place without making a copy of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [0,1,0,3,12] <strong>Output:</strong> [1,3,12,0,0] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you minimize the total number of operations done?
Array; Two Pointers
C++
class Solution { public: void moveZeroes(vector<int>& nums) { int k = 0, n = nums.size(); for (int i = 0; i < n; ++i) { if (nums[i]) { swap(nums[i], nums[k++]); } } } };
283
Move Zeroes
Easy
<p>Given an integer array <code>nums</code>, move all <code>0</code>&#39;s to the end of it while maintaining the relative order of the non-zero elements.</p> <p><strong>Note</strong> that you must do this in-place without making a copy of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [0,1,0,3,12] <strong>Output:</strong> [1,3,12,0,0] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you minimize the total number of operations done?
Array; Two Pointers
Go
func moveZeroes(nums []int) { k := 0 for i, x := range nums { if x != 0 { nums[i], nums[k] = nums[k], nums[i] k++ } } }
283
Move Zeroes
Easy
<p>Given an integer array <code>nums</code>, move all <code>0</code>&#39;s to the end of it while maintaining the relative order of the non-zero elements.</p> <p><strong>Note</strong> that you must do this in-place without making a copy of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [0,1,0,3,12] <strong>Output:</strong> [1,3,12,0,0] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you minimize the total number of operations done?
Array; Two Pointers
Java
class Solution { public void moveZeroes(int[] nums) { int k = 0, n = nums.length; for (int i = 0; i < n; ++i) { if (nums[i] != 0) { int t = nums[i]; nums[i] = nums[k]; nums[k++] = t; } } } }
283
Move Zeroes
Easy
<p>Given an integer array <code>nums</code>, move all <code>0</code>&#39;s to the end of it while maintaining the relative order of the non-zero elements.</p> <p><strong>Note</strong> that you must do this in-place without making a copy of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [0,1,0,3,12] <strong>Output:</strong> [1,3,12,0,0] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you minimize the total number of operations done?
Array; Two Pointers
JavaScript
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var moveZeroes = function (nums) { let k = 0; for (let i = 0; i < nums.length; ++i) { if (nums[i]) { [nums[i], nums[k]] = [nums[k], nums[i]]; ++k; } } };
283
Move Zeroes
Easy
<p>Given an integer array <code>nums</code>, move all <code>0</code>&#39;s to the end of it while maintaining the relative order of the non-zero elements.</p> <p><strong>Note</strong> that you must do this in-place without making a copy of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [0,1,0,3,12] <strong>Output:</strong> [1,3,12,0,0] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you minimize the total number of operations done?
Array; Two Pointers
Python
class Solution: def moveZeroes(self, nums: List[int]) -> None: k = 0 for i, x in enumerate(nums): if x: nums[k], nums[i] = nums[i], nums[k] k += 1
283
Move Zeroes
Easy
<p>Given an integer array <code>nums</code>, move all <code>0</code>&#39;s to the end of it while maintaining the relative order of the non-zero elements.</p> <p><strong>Note</strong> that you must do this in-place without making a copy of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [0,1,0,3,12] <strong>Output:</strong> [1,3,12,0,0] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you minimize the total number of operations done?
Array; Two Pointers
Rust
impl Solution { pub fn move_zeroes(nums: &mut Vec<i32>) { let mut k = 0; let n = nums.len(); for i in 0..n { if nums[i] != 0 { nums.swap(i, k); k += 1; } } } }
283
Move Zeroes
Easy
<p>Given an integer array <code>nums</code>, move all <code>0</code>&#39;s to the end of it while maintaining the relative order of the non-zero elements.</p> <p><strong>Note</strong> that you must do this in-place without making a copy of the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [0,1,0,3,12] <strong>Output:</strong> [1,3,12,0,0] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [0] <strong>Output:</strong> [0] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you minimize the total number of operations done?
Array; Two Pointers
TypeScript
/** Do not return anything, modify nums in-place instead. */ function moveZeroes(nums: number[]): void { let k = 0; for (let i = 0; i < nums.length; ++i) { if (nums[i]) { [nums[i], nums[k]] = [nums[k], nums[i]]; ++k; } } }
284
Peeking Iterator
Medium
<p>Design an iterator that supports the <code>peek</code> operation on an existing iterator in addition to the <code>hasNext</code> and the <code>next</code> operations.</p> <p>Implement the <code>PeekingIterator</code> class:</p> <ul> <li><code>PeekingIterator(Iterator&lt;int&gt; nums)</code> Initializes the object with the given integer iterator <code>iterator</code>.</li> <li><code>int next()</code> Returns the next element in the array and moves the pointer to the next element.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there are still elements in the array.</li> <li><code>int peek()</code> Returns the next element in the array <strong>without</strong> moving the pointer.</li> </ul> <p><strong>Note:</strong> Each language may have a different implementation of the constructor and <code>Iterator</code>, but they all support the <code>int next()</code> and <code>boolean hasNext()</code> functions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;PeekingIterator&quot;, &quot;next&quot;, &quot;peek&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[1, 2, 3]], [], [], [], [], []] <strong>Output</strong> [null, 1, 2, 2, 3, false] <strong>Explanation</strong> PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [<u><strong>1</strong></u>,2,3] peekingIterator.next(); // return 1, the pointer moves to the next element [1,<u><strong>2</strong></u>,3]. peekingIterator.peek(); // return 2, the pointer does not move [1,<u><strong>2</strong></u>,3]. peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,<u><strong>3</strong></u>] peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3] peekingIterator.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li>All the calls to <code>next</code> and <code>peek</code> are valid.</li> <li>At most <code>1000</code> calls will be made to <code>next</code>, <code>hasNext</code>, and <code>peek</code>.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> How would you extend your design to be generic and work with all types, not just integer?
Design; Array; Iterator
C++
/* * Below is the interface for Iterator, which is already defined for you. * **DO NOT** modify the interface for Iterator. * * class Iterator { * struct Data; * Data* data; * public: * Iterator(const vector<int>& nums); * Iterator(const Iterator& iter); * * // Returns the next element in the iteration. * int next(); * * // Returns true if the iteration has more elements. * bool hasNext() const; * }; */ class PeekingIterator : public Iterator { public: PeekingIterator(const vector<int>& nums) : Iterator(nums) { // Initialize any member here. // **DO NOT** save a copy of nums and manipulate it directly. // You should only use the Iterator interface methods. hasPeeked = false; } // Returns the next element in the iteration without advancing the iterator. int peek() { if (!hasPeeked) { peekedElement = Iterator::next(); hasPeeked = true; } return peekedElement; } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. int next() { if (!hasPeeked) return Iterator::next(); hasPeeked = false; return peekedElement; } bool hasNext() const { return hasPeeked || Iterator::hasNext(); } private: bool hasPeeked; int peekedElement; };
284
Peeking Iterator
Medium
<p>Design an iterator that supports the <code>peek</code> operation on an existing iterator in addition to the <code>hasNext</code> and the <code>next</code> operations.</p> <p>Implement the <code>PeekingIterator</code> class:</p> <ul> <li><code>PeekingIterator(Iterator&lt;int&gt; nums)</code> Initializes the object with the given integer iterator <code>iterator</code>.</li> <li><code>int next()</code> Returns the next element in the array and moves the pointer to the next element.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there are still elements in the array.</li> <li><code>int peek()</code> Returns the next element in the array <strong>without</strong> moving the pointer.</li> </ul> <p><strong>Note:</strong> Each language may have a different implementation of the constructor and <code>Iterator</code>, but they all support the <code>int next()</code> and <code>boolean hasNext()</code> functions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;PeekingIterator&quot;, &quot;next&quot;, &quot;peek&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[1, 2, 3]], [], [], [], [], []] <strong>Output</strong> [null, 1, 2, 2, 3, false] <strong>Explanation</strong> PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [<u><strong>1</strong></u>,2,3] peekingIterator.next(); // return 1, the pointer moves to the next element [1,<u><strong>2</strong></u>,3]. peekingIterator.peek(); // return 2, the pointer does not move [1,<u><strong>2</strong></u>,3]. peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,<u><strong>3</strong></u>] peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3] peekingIterator.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li>All the calls to <code>next</code> and <code>peek</code> are valid.</li> <li>At most <code>1000</code> calls will be made to <code>next</code>, <code>hasNext</code>, and <code>peek</code>.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> How would you extend your design to be generic and work with all types, not just integer?
Design; Array; Iterator
Go
/* Below is the interface for Iterator, which is already defined for you. * * type Iterator struct { * * } * * func (this *Iterator) hasNext() bool { * // Returns true if the iteration has more elements. * } * * func (this *Iterator) next() int { * // Returns the next element in the iteration. * } */ type PeekingIterator struct { iter *Iterator hasPeeked bool peekedElement int } func Constructor(iter *Iterator) *PeekingIterator { return &PeekingIterator{iter, iter.hasNext(), iter.next()} } func (this *PeekingIterator) hasNext() bool { return this.hasPeeked || this.iter.hasNext() } func (this *PeekingIterator) next() int { if !this.hasPeeked { return this.iter.next() } this.hasPeeked = false return this.peekedElement } func (this *PeekingIterator) peek() int { if !this.hasPeeked { this.peekedElement = this.iter.next() this.hasPeeked = true } return this.peekedElement }
284
Peeking Iterator
Medium
<p>Design an iterator that supports the <code>peek</code> operation on an existing iterator in addition to the <code>hasNext</code> and the <code>next</code> operations.</p> <p>Implement the <code>PeekingIterator</code> class:</p> <ul> <li><code>PeekingIterator(Iterator&lt;int&gt; nums)</code> Initializes the object with the given integer iterator <code>iterator</code>.</li> <li><code>int next()</code> Returns the next element in the array and moves the pointer to the next element.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there are still elements in the array.</li> <li><code>int peek()</code> Returns the next element in the array <strong>without</strong> moving the pointer.</li> </ul> <p><strong>Note:</strong> Each language may have a different implementation of the constructor and <code>Iterator</code>, but they all support the <code>int next()</code> and <code>boolean hasNext()</code> functions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;PeekingIterator&quot;, &quot;next&quot;, &quot;peek&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[1, 2, 3]], [], [], [], [], []] <strong>Output</strong> [null, 1, 2, 2, 3, false] <strong>Explanation</strong> PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [<u><strong>1</strong></u>,2,3] peekingIterator.next(); // return 1, the pointer moves to the next element [1,<u><strong>2</strong></u>,3]. peekingIterator.peek(); // return 2, the pointer does not move [1,<u><strong>2</strong></u>,3]. peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,<u><strong>3</strong></u>] peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3] peekingIterator.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li>All the calls to <code>next</code> and <code>peek</code> are valid.</li> <li>At most <code>1000</code> calls will be made to <code>next</code>, <code>hasNext</code>, and <code>peek</code>.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> How would you extend your design to be generic and work with all types, not just integer?
Design; Array; Iterator
Java
// Java Iterator interface reference: // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html class PeekingIterator implements Iterator<Integer> { private Iterator<Integer> iterator; private boolean hasPeeked; private Integer peekedElement; public PeekingIterator(Iterator<Integer> iterator) { // initialize any member here. this.iterator = iterator; } // Returns the next element in the iteration without advancing the iterator. public Integer peek() { if (!hasPeeked) { peekedElement = iterator.next(); hasPeeked = true; } return peekedElement; } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. @Override public Integer next() { if (!hasPeeked) { return iterator.next(); } Integer result = peekedElement; hasPeeked = false; peekedElement = null; return result; } @Override public boolean hasNext() { return hasPeeked || iterator.hasNext(); } }
284
Peeking Iterator
Medium
<p>Design an iterator that supports the <code>peek</code> operation on an existing iterator in addition to the <code>hasNext</code> and the <code>next</code> operations.</p> <p>Implement the <code>PeekingIterator</code> class:</p> <ul> <li><code>PeekingIterator(Iterator&lt;int&gt; nums)</code> Initializes the object with the given integer iterator <code>iterator</code>.</li> <li><code>int next()</code> Returns the next element in the array and moves the pointer to the next element.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there are still elements in the array.</li> <li><code>int peek()</code> Returns the next element in the array <strong>without</strong> moving the pointer.</li> </ul> <p><strong>Note:</strong> Each language may have a different implementation of the constructor and <code>Iterator</code>, but they all support the <code>int next()</code> and <code>boolean hasNext()</code> functions.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;PeekingIterator&quot;, &quot;next&quot;, &quot;peek&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[1, 2, 3]], [], [], [], [], []] <strong>Output</strong> [null, 1, 2, 2, 3, false] <strong>Explanation</strong> PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [<u><strong>1</strong></u>,2,3] peekingIterator.next(); // return 1, the pointer moves to the next element [1,<u><strong>2</strong></u>,3]. peekingIterator.peek(); // return 2, the pointer does not move [1,<u><strong>2</strong></u>,3]. peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,<u><strong>3</strong></u>] peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3] peekingIterator.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li>All the calls to <code>next</code> and <code>peek</code> are valid.</li> <li>At most <code>1000</code> calls will be made to <code>next</code>, <code>hasNext</code>, and <code>peek</code>.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> How would you extend your design to be generic and work with all types, not just integer?
Design; Array; Iterator
Python
# Below is the interface for Iterator, which is already defined for you. # # class Iterator: # def __init__(self, nums): # """ # Initializes an iterator object to the beginning of a list. # :type nums: List[int] # """ # # def hasNext(self): # """ # Returns true if the iteration has more elements. # :rtype: bool # """ # # def next(self): # """ # Returns the next element in the iteration. # :rtype: int # """ class PeekingIterator: def __init__(self, iterator): """ Initialize your data structure here. :type iterator: Iterator """ self.iterator = iterator self.has_peeked = False self.peeked_element = None def peek(self): """ Returns the next element in the iteration without advancing the iterator. :rtype: int """ if not self.has_peeked: self.peeked_element = self.iterator.next() self.has_peeked = True return self.peeked_element def next(self): """ :rtype: int """ if not self.has_peeked: return self.iterator.next() result = self.peeked_element self.has_peeked = False self.peeked_element = None return result def hasNext(self): """ :rtype: bool """ return self.has_peeked or self.iterator.hasNext() # Your PeekingIterator object will be instantiated and called as such: # iter = PeekingIterator(Iterator(nums)) # while iter.hasNext(): # val = iter.peek() # Get the next element but not advance the iterator. # iter.next() # Should return the same value as [val].
285
Inorder Successor in BST
Medium
<p>Given the <code>root</code> of a binary search tree and a node <code>p</code> in it, return <em>the in-order successor of that node in the BST</em>. If the given node has no in-order successor in the tree, return <code>null</code>.</p> <p>The successor of a node <code>p</code> is the node with the smallest key greater than <code>p.val</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0285.Inorder%20Successor%20in%20BST/images/285_example_1.png" style="width: 122px; height: 117px;" /> <pre> <strong>Input:</strong> root = [2,1,3], p = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> 1&#39;s in-order successor node is 2. Note that both p and the return value is of TreeNode type. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0285.Inorder%20Successor%20in%20BST/images/285_example_2.png" style="width: 246px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,null,1], p = 6 <strong>Output:</strong> null <strong>Explanation:</strong> There is no in-order successor of the current node, so the answer is <code>null</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>All Nodes will have unique values.</li> </ul>
Tree; Depth-First Search; Binary Search Tree; 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 Solution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { TreeNode* ans = nullptr; while (root) { if (root->val > p->val) { ans = root; root = root->left; } else { root = root->right; } } return ans; } };
285
Inorder Successor in BST
Medium
<p>Given the <code>root</code> of a binary search tree and a node <code>p</code> in it, return <em>the in-order successor of that node in the BST</em>. If the given node has no in-order successor in the tree, return <code>null</code>.</p> <p>The successor of a node <code>p</code> is the node with the smallest key greater than <code>p.val</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0285.Inorder%20Successor%20in%20BST/images/285_example_1.png" style="width: 122px; height: 117px;" /> <pre> <strong>Input:</strong> root = [2,1,3], p = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> 1&#39;s in-order successor node is 2. Note that both p and the return value is of TreeNode type. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0285.Inorder%20Successor%20in%20BST/images/285_example_2.png" style="width: 246px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,null,1], p = 6 <strong>Output:</strong> null <strong>Explanation:</strong> There is no in-order successor of the current node, so the answer is <code>null</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>All Nodes will have unique values.</li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func inorderSuccessor(root *TreeNode, p *TreeNode) (ans *TreeNode) { for root != nil { if root.Val > p.Val { ans = root root = root.Left } else { root = root.Right } } return }
285
Inorder Successor in BST
Medium
<p>Given the <code>root</code> of a binary search tree and a node <code>p</code> in it, return <em>the in-order successor of that node in the BST</em>. If the given node has no in-order successor in the tree, return <code>null</code>.</p> <p>The successor of a node <code>p</code> is the node with the smallest key greater than <code>p.val</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0285.Inorder%20Successor%20in%20BST/images/285_example_1.png" style="width: 122px; height: 117px;" /> <pre> <strong>Input:</strong> root = [2,1,3], p = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> 1&#39;s in-order successor node is 2. Note that both p and the return value is of TreeNode type. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0285.Inorder%20Successor%20in%20BST/images/285_example_2.png" style="width: 246px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,null,1], p = 6 <strong>Output:</strong> null <strong>Explanation:</strong> There is no in-order successor of the current node, so the answer is <code>null</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>All Nodes will have unique values.</li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { TreeNode ans = null; while (root != null) { if (root.val > p.val) { ans = root; root = root.left; } else { root = root.right; } } return ans; } }
285
Inorder Successor in BST
Medium
<p>Given the <code>root</code> of a binary search tree and a node <code>p</code> in it, return <em>the in-order successor of that node in the BST</em>. If the given node has no in-order successor in the tree, return <code>null</code>.</p> <p>The successor of a node <code>p</code> is the node with the smallest key greater than <code>p.val</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0285.Inorder%20Successor%20in%20BST/images/285_example_1.png" style="width: 122px; height: 117px;" /> <pre> <strong>Input:</strong> root = [2,1,3], p = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> 1&#39;s in-order successor node is 2. Note that both p and the return value is of TreeNode type. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0285.Inorder%20Successor%20in%20BST/images/285_example_2.png" style="width: 246px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,null,1], p = 6 <strong>Output:</strong> null <strong>Explanation:</strong> There is no in-order successor of the current node, so the answer is <code>null</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>All Nodes will have unique values.</li> </ul>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @param {TreeNode} p * @return {TreeNode} */ var inorderSuccessor = function (root, p) { let ans = null; while (root) { if (root.val > p.val) { ans = root; root = root.left; } else { root = root.right; } } return ans; };
285
Inorder Successor in BST
Medium
<p>Given the <code>root</code> of a binary search tree and a node <code>p</code> in it, return <em>the in-order successor of that node in the BST</em>. If the given node has no in-order successor in the tree, return <code>null</code>.</p> <p>The successor of a node <code>p</code> is the node with the smallest key greater than <code>p.val</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0285.Inorder%20Successor%20in%20BST/images/285_example_1.png" style="width: 122px; height: 117px;" /> <pre> <strong>Input:</strong> root = [2,1,3], p = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> 1&#39;s in-order successor node is 2. Note that both p and the return value is of TreeNode type. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0285.Inorder%20Successor%20in%20BST/images/285_example_2.png" style="width: 246px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,null,1], p = 6 <strong>Output:</strong> null <strong>Explanation:</strong> There is no in-order successor of the current node, so the answer is <code>null</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>All Nodes will have unique values.</li> </ul>
Tree; Depth-First Search; Binary Search Tree; 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 Solution: def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> Optional[TreeNode]: ans = None while root: if root.val > p.val: ans = root root = root.left else: root = root.right return ans
285
Inorder Successor in BST
Medium
<p>Given the <code>root</code> of a binary search tree and a node <code>p</code> in it, return <em>the in-order successor of that node in the BST</em>. If the given node has no in-order successor in the tree, return <code>null</code>.</p> <p>The successor of a node <code>p</code> is the node with the smallest key greater than <code>p.val</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0285.Inorder%20Successor%20in%20BST/images/285_example_1.png" style="width: 122px; height: 117px;" /> <pre> <strong>Input:</strong> root = [2,1,3], p = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> 1&#39;s in-order successor node is 2. Note that both p and the return value is of TreeNode type. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0285.Inorder%20Successor%20in%20BST/images/285_example_2.png" style="width: 246px; height: 229px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,null,1], p = 6 <strong>Output:</strong> null <strong>Explanation:</strong> There is no in-order successor of the current node, so the answer is <code>null</code>. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li>All Nodes will have unique values.</li> </ul>
Tree; Depth-First Search; 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 inorderSuccessor(root: TreeNode | null, p: TreeNode | null): TreeNode | null { let ans: TreeNode | null = null; while (root) { if (root.val > p.val) { ans = root; root = root.left; } else { root = root.right; } } return ans; }
286
Walls and Gates
Medium
<p>You are given an <code>m x n</code> grid <code>rooms</code>&nbsp;initialized with these three possible values.</p> <ul> <li><code>-1</code>&nbsp;A wall or an obstacle.</li> <li><code>0</code> A gate.</li> <li><code>INF</code> Infinity means an empty room. We use the value <code>2<sup>31</sup> - 1 = 2147483647</code> to represent <code>INF</code> as you may assume that the distance to a gate is less than <code>2147483647</code>.</li> </ul> <p>Fill each empty room with the distance to <em>its nearest gate</em>. If it is impossible to reach a gate, it should be filled with <code>INF</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0286.Walls%20and%20Gates/images/grid.jpg" style="width: 500px; height: 223px;" /> <pre> <strong>Input:</strong> rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]] <strong>Output:</strong> [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> rooms = [[-1]] <strong>Output:</strong> [[-1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == rooms.length</code></li> <li><code>n == rooms[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 250</code></li> <li><code>rooms[i][j]</code> is <code>-1</code>, <code>0</code>, or <code>2<sup>31</sup> - 1</code>.</li> </ul>
Breadth-First Search; Array; Matrix
C++
class Solution { public: void wallsAndGates(vector<vector<int>>& rooms) { int m = rooms.size(); int n = rooms[0].size(); queue<pair<int, int>> q; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (rooms[i][j] == 0) q.emplace(i, j); int d = 0; vector<int> dirs = {-1, 0, 1, 0, -1}; while (!q.empty()) { ++d; for (int i = q.size(); i > 0; --i) { auto p = q.front(); q.pop(); for (int j = 0; j < 4; ++j) { int x = p.first + dirs[j]; int y = p.second + dirs[j + 1]; if (x >= 0 && x < m && y >= 0 && y < n && rooms[x][y] == INT_MAX) { rooms[x][y] = d; q.emplace(x, y); } } } } } };
286
Walls and Gates
Medium
<p>You are given an <code>m x n</code> grid <code>rooms</code>&nbsp;initialized with these three possible values.</p> <ul> <li><code>-1</code>&nbsp;A wall or an obstacle.</li> <li><code>0</code> A gate.</li> <li><code>INF</code> Infinity means an empty room. We use the value <code>2<sup>31</sup> - 1 = 2147483647</code> to represent <code>INF</code> as you may assume that the distance to a gate is less than <code>2147483647</code>.</li> </ul> <p>Fill each empty room with the distance to <em>its nearest gate</em>. If it is impossible to reach a gate, it should be filled with <code>INF</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0286.Walls%20and%20Gates/images/grid.jpg" style="width: 500px; height: 223px;" /> <pre> <strong>Input:</strong> rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]] <strong>Output:</strong> [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> rooms = [[-1]] <strong>Output:</strong> [[-1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == rooms.length</code></li> <li><code>n == rooms[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 250</code></li> <li><code>rooms[i][j]</code> is <code>-1</code>, <code>0</code>, or <code>2<sup>31</sup> - 1</code>.</li> </ul>
Breadth-First Search; Array; Matrix
Go
func wallsAndGates(rooms [][]int) { m, n := len(rooms), len(rooms[0]) var q [][]int for i := 0; i < m; i++ { for j := 0; j < n; j++ { if rooms[i][j] == 0 { q = append(q, []int{i, j}) } } } d := 0 dirs := []int{-1, 0, 1, 0, -1} for len(q) > 0 { d++ for i := len(q); i > 0; i-- { p := q[0] q = q[1:] for j := 0; j < 4; j++ { x, y := p[0]+dirs[j], p[1]+dirs[j+1] if x >= 0 && x < m && y >= 0 && y < n && rooms[x][y] == math.MaxInt32 { rooms[x][y] = d q = append(q, []int{x, y}) } } } } }
286
Walls and Gates
Medium
<p>You are given an <code>m x n</code> grid <code>rooms</code>&nbsp;initialized with these three possible values.</p> <ul> <li><code>-1</code>&nbsp;A wall or an obstacle.</li> <li><code>0</code> A gate.</li> <li><code>INF</code> Infinity means an empty room. We use the value <code>2<sup>31</sup> - 1 = 2147483647</code> to represent <code>INF</code> as you may assume that the distance to a gate is less than <code>2147483647</code>.</li> </ul> <p>Fill each empty room with the distance to <em>its nearest gate</em>. If it is impossible to reach a gate, it should be filled with <code>INF</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0286.Walls%20and%20Gates/images/grid.jpg" style="width: 500px; height: 223px;" /> <pre> <strong>Input:</strong> rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]] <strong>Output:</strong> [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> rooms = [[-1]] <strong>Output:</strong> [[-1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == rooms.length</code></li> <li><code>n == rooms[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 250</code></li> <li><code>rooms[i][j]</code> is <code>-1</code>, <code>0</code>, or <code>2<sup>31</sup> - 1</code>.</li> </ul>
Breadth-First Search; Array; Matrix
Java
class Solution { public void wallsAndGates(int[][] rooms) { int m = rooms.length; int n = rooms[0].length; Deque<int[]> q = new LinkedList<>(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (rooms[i][j] == 0) { q.offer(new int[] {i, j}); } } } int d = 0; int[] dirs = {-1, 0, 1, 0, -1}; while (!q.isEmpty()) { ++d; for (int i = q.size(); i > 0; --i) { int[] p = q.poll(); for (int j = 0; j < 4; ++j) { int x = p[0] + dirs[j]; int y = p[1] + dirs[j + 1]; if (x >= 0 && x < m && y >= 0 && y < n && rooms[x][y] == Integer.MAX_VALUE) { rooms[x][y] = d; q.offer(new int[] {x, y}); } } } } } }
286
Walls and Gates
Medium
<p>You are given an <code>m x n</code> grid <code>rooms</code>&nbsp;initialized with these three possible values.</p> <ul> <li><code>-1</code>&nbsp;A wall or an obstacle.</li> <li><code>0</code> A gate.</li> <li><code>INF</code> Infinity means an empty room. We use the value <code>2<sup>31</sup> - 1 = 2147483647</code> to represent <code>INF</code> as you may assume that the distance to a gate is less than <code>2147483647</code>.</li> </ul> <p>Fill each empty room with the distance to <em>its nearest gate</em>. If it is impossible to reach a gate, it should be filled with <code>INF</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0286.Walls%20and%20Gates/images/grid.jpg" style="width: 500px; height: 223px;" /> <pre> <strong>Input:</strong> rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]] <strong>Output:</strong> [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> rooms = [[-1]] <strong>Output:</strong> [[-1]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == rooms.length</code></li> <li><code>n == rooms[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 250</code></li> <li><code>rooms[i][j]</code> is <code>-1</code>, <code>0</code>, or <code>2<sup>31</sup> - 1</code>.</li> </ul>
Breadth-First Search; Array; Matrix
Python
class Solution: def wallsAndGates(self, rooms: List[List[int]]) -> None: """ Do not return anything, modify rooms in-place instead. """ m, n = len(rooms), len(rooms[0]) inf = 2**31 - 1 q = deque([(i, j) for i in range(m) for j in range(n) if rooms[i][j] == 0]) d = 0 while q: d += 1 for _ in range(len(q)): i, j = q.popleft() for a, b in [[0, 1], [0, -1], [1, 0], [-1, 0]]: x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and rooms[x][y] == inf: rooms[x][y] = d q.append((x, y))
287
Find the Duplicate Number
Medium
<p>Given an array of integers <code>nums</code> containing&nbsp;<code>n + 1</code> integers where each integer is in the range <code>[1, n]</code> inclusive.</p> <p>There is only <strong>one repeated number</strong> in <code>nums</code>, return <em>this&nbsp;repeated&nbsp;number</em>.</p> <p>You must solve the problem <strong>without</strong> modifying the array <code>nums</code>&nbsp;and using only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,2,2] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,3,4,2] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3,3] <strong>Output:</strong> 3</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>nums.length == n + 1</code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> <li>All the integers in <code>nums</code> appear only <strong>once</strong> except for <strong>precisely one integer</strong> which appears <strong>two or more</strong> times.</li> </ul> <p>&nbsp;</p> <p><b>Follow up:</b></p> <ul> <li>How can we prove that at least one duplicate number must exist in <code>nums</code>?</li> <li>Can you solve the problem in linear runtime complexity?</li> </ul>
Bit Manipulation; Array; Two Pointers; Binary Search
C++
class Solution { public: int findDuplicate(vector<int>& nums) { int l = 0, r = nums.size() - 1; while (l < r) { int mid = (l + r) >> 1; int cnt = 0; for (int& v : nums) { cnt += v <= mid; } if (cnt > mid) { r = mid; } else { l = mid + 1; } } return l; } };
287
Find the Duplicate Number
Medium
<p>Given an array of integers <code>nums</code> containing&nbsp;<code>n + 1</code> integers where each integer is in the range <code>[1, n]</code> inclusive.</p> <p>There is only <strong>one repeated number</strong> in <code>nums</code>, return <em>this&nbsp;repeated&nbsp;number</em>.</p> <p>You must solve the problem <strong>without</strong> modifying the array <code>nums</code>&nbsp;and using only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,2,2] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,3,4,2] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3,3] <strong>Output:</strong> 3</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>nums.length == n + 1</code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> <li>All the integers in <code>nums</code> appear only <strong>once</strong> except for <strong>precisely one integer</strong> which appears <strong>two or more</strong> times.</li> </ul> <p>&nbsp;</p> <p><b>Follow up:</b></p> <ul> <li>How can we prove that at least one duplicate number must exist in <code>nums</code>?</li> <li>Can you solve the problem in linear runtime complexity?</li> </ul>
Bit Manipulation; Array; Two Pointers; Binary Search
Go
func findDuplicate(nums []int) int { return sort.Search(len(nums), func(x int) bool { cnt := 0 for _, v := range nums { if v <= x { cnt++ } } return cnt > x }) }
287
Find the Duplicate Number
Medium
<p>Given an array of integers <code>nums</code> containing&nbsp;<code>n + 1</code> integers where each integer is in the range <code>[1, n]</code> inclusive.</p> <p>There is only <strong>one repeated number</strong> in <code>nums</code>, return <em>this&nbsp;repeated&nbsp;number</em>.</p> <p>You must solve the problem <strong>without</strong> modifying the array <code>nums</code>&nbsp;and using only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,2,2] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,3,4,2] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3,3] <strong>Output:</strong> 3</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>nums.length == n + 1</code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> <li>All the integers in <code>nums</code> appear only <strong>once</strong> except for <strong>precisely one integer</strong> which appears <strong>two or more</strong> times.</li> </ul> <p>&nbsp;</p> <p><b>Follow up:</b></p> <ul> <li>How can we prove that at least one duplicate number must exist in <code>nums</code>?</li> <li>Can you solve the problem in linear runtime complexity?</li> </ul>
Bit Manipulation; Array; Two Pointers; Binary Search
Java
class Solution { public int findDuplicate(int[] nums) { int l = 0, r = nums.length - 1; while (l < r) { int mid = (l + r) >> 1; int cnt = 0; for (int v : nums) { if (v <= mid) { ++cnt; } } if (cnt > mid) { r = mid; } else { l = mid + 1; } } return l; } }
287
Find the Duplicate Number
Medium
<p>Given an array of integers <code>nums</code> containing&nbsp;<code>n + 1</code> integers where each integer is in the range <code>[1, n]</code> inclusive.</p> <p>There is only <strong>one repeated number</strong> in <code>nums</code>, return <em>this&nbsp;repeated&nbsp;number</em>.</p> <p>You must solve the problem <strong>without</strong> modifying the array <code>nums</code>&nbsp;and using only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,2,2] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,3,4,2] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3,3] <strong>Output:</strong> 3</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>nums.length == n + 1</code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> <li>All the integers in <code>nums</code> appear only <strong>once</strong> except for <strong>precisely one integer</strong> which appears <strong>two or more</strong> times.</li> </ul> <p>&nbsp;</p> <p><b>Follow up:</b></p> <ul> <li>How can we prove that at least one duplicate number must exist in <code>nums</code>?</li> <li>Can you solve the problem in linear runtime complexity?</li> </ul>
Bit Manipulation; Array; Two Pointers; Binary Search
JavaScript
/** * @param {number[]} nums * @return {number} */ var findDuplicate = function (nums) { let l = 0; let r = nums.length - 1; while (l < r) { const mid = (l + r) >> 1; let cnt = 0; for (const v of nums) { if (v <= mid) { ++cnt; } } if (cnt > mid) { r = mid; } else { l = mid + 1; } } return l; };
287
Find the Duplicate Number
Medium
<p>Given an array of integers <code>nums</code> containing&nbsp;<code>n + 1</code> integers where each integer is in the range <code>[1, n]</code> inclusive.</p> <p>There is only <strong>one repeated number</strong> in <code>nums</code>, return <em>this&nbsp;repeated&nbsp;number</em>.</p> <p>You must solve the problem <strong>without</strong> modifying the array <code>nums</code>&nbsp;and using only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,4,2,2] <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,1,3,4,2] <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [3,3,3,3,3] <strong>Output:</strong> 3</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>nums.length == n + 1</code></li> <li><code>1 &lt;= nums[i] &lt;= n</code></li> <li>All the integers in <code>nums</code> appear only <strong>once</strong> except for <strong>precisely one integer</strong> which appears <strong>two or more</strong> times.</li> </ul> <p>&nbsp;</p> <p><b>Follow up:</b></p> <ul> <li>How can we prove that at least one duplicate number must exist in <code>nums</code>?</li> <li>Can you solve the problem in linear runtime complexity?</li> </ul>
Bit Manipulation; Array; Two Pointers; Binary Search
Python
class Solution: def findDuplicate(self, nums: List[int]) -> int: def f(x: int) -> bool: return sum(v <= x for v in nums) > x return bisect_left(range(len(nums)), True, key=f)