id
int64
1
3.63k
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
31
Next Permutation
Medium
<p>A <strong>permutation</strong> of an array of integers is an arrangement of its members into a sequence or linear order.</p> <ul> <li>For example, for <code>arr = [1,2,3]</code>, the following are all the permutations of <code>arr</code>: <code>[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]</code>.</li> </ul> <p>The <strong>next permutation</strong> of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the <strong>next permutation</strong> of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).</p> <ul> <li>For example, the next permutation of <code>arr = [1,2,3]</code> is <code>[1,3,2]</code>.</li> <li>Similarly, the next permutation of <code>arr = [2,3,1]</code> is <code>[3,1,2]</code>.</li> <li>While the next permutation of <code>arr = [3,2,1]</code> is <code>[1,2,3]</code> because <code>[3,2,1]</code> does not have a lexicographical larger rearrangement.</li> </ul> <p>Given an array of integers <code>nums</code>, <em>find the next permutation of</em> <code>nums</code>.</p> <p>The replacement must be <strong><a href="http://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in place</a></strong> and use only constant extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,3,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [1,2,3] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,5] <strong>Output:</strong> [1,5,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Two Pointers
PHP
class Solution { /** * @param integer[] $nums * @return void */ function nextPermutation(&$nums) { $n = count($nums); $i = $n - 2; while ($i >= 0 && $nums[$i] >= $nums[$i + 1]) { $i--; } if ($i >= 0) { $j = $n - 1; while ($j >= $i && $nums[$j] <= $nums[$i]) { $j--; } $temp = $nums[$i]; $nums[$i] = $nums[$j]; $nums[$j] = $temp; } $this->reverse($nums, $i + 1, $n - 1); } function reverse(&$nums, $start, $end) { while ($start < $end) { $temp = $nums[$start]; $nums[$start] = $nums[$end]; $nums[$end] = $temp; $start++; $end--; } } }
31
Next Permutation
Medium
<p>A <strong>permutation</strong> of an array of integers is an arrangement of its members into a sequence or linear order.</p> <ul> <li>For example, for <code>arr = [1,2,3]</code>, the following are all the permutations of <code>arr</code>: <code>[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]</code>.</li> </ul> <p>The <strong>next permutation</strong> of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the <strong>next permutation</strong> of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).</p> <ul> <li>For example, the next permutation of <code>arr = [1,2,3]</code> is <code>[1,3,2]</code>.</li> <li>Similarly, the next permutation of <code>arr = [2,3,1]</code> is <code>[3,1,2]</code>.</li> <li>While the next permutation of <code>arr = [3,2,1]</code> is <code>[1,2,3]</code> because <code>[3,2,1]</code> does not have a lexicographical larger rearrangement.</li> </ul> <p>Given an array of integers <code>nums</code>, <em>find the next permutation of</em> <code>nums</code>.</p> <p>The replacement must be <strong><a href="http://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in place</a></strong> and use only constant extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,3,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [1,2,3] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,5] <strong>Output:</strong> [1,5,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Two Pointers
Python
class Solution: def nextPermutation(self, nums: List[int]) -> None: n = len(nums) i = next((i for i in range(n - 2, -1, -1) if nums[i] < nums[i + 1]), -1) if ~i: j = next((j for j in range(n - 1, i, -1) if nums[j] > nums[i])) nums[i], nums[j] = nums[j], nums[i] nums[i + 1 :] = nums[i + 1 :][::-1]
31
Next Permutation
Medium
<p>A <strong>permutation</strong> of an array of integers is an arrangement of its members into a sequence or linear order.</p> <ul> <li>For example, for <code>arr = [1,2,3]</code>, the following are all the permutations of <code>arr</code>: <code>[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]</code>.</li> </ul> <p>The <strong>next permutation</strong> of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the <strong>next permutation</strong> of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).</p> <ul> <li>For example, the next permutation of <code>arr = [1,2,3]</code> is <code>[1,3,2]</code>.</li> <li>Similarly, the next permutation of <code>arr = [2,3,1]</code> is <code>[3,1,2]</code>.</li> <li>While the next permutation of <code>arr = [3,2,1]</code> is <code>[1,2,3]</code> because <code>[3,2,1]</code> does not have a lexicographical larger rearrangement.</li> </ul> <p>Given an array of integers <code>nums</code>, <em>find the next permutation of</em> <code>nums</code>.</p> <p>The replacement must be <strong><a href="http://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in place</a></strong> and use only constant extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3] <strong>Output:</strong> [1,3,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,1] <strong>Output:</strong> [1,2,3] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,1,5] <strong>Output:</strong> [1,5,1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>0 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Two Pointers
TypeScript
function nextPermutation(nums: number[]): void { const n = nums.length; let i = n - 2; while (i >= 0 && nums[i] >= nums[i + 1]) { --i; } if (i >= 0) { for (let j = n - 1; j > i; --j) { if (nums[j] > nums[i]) { [nums[i], nums[j]] = [nums[j], nums[i]]; break; } } } for (let j = n - 1; j > i; --j, ++i) { [nums[i + 1], nums[j]] = [nums[j], nums[i + 1]]; } }
32
Longest Valid Parentheses
Hard
<p>Given a string containing just the characters <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>, return <em>the length of the longest valid (well-formed) parentheses </em><span data-keyword="substring-nonempty"><em>substring</em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;(()&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;)()())&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()()&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot; <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s[i]</code> is <code>&#39;(&#39;</code>, or <code>&#39;)&#39;</code>.</li> </ul>
Stack; String; Dynamic Programming
C++
class Solution { public: int longestValidParentheses(string s) { int n = s.size(); int f[n + 1]; memset(f, 0, sizeof(f)); for (int i = 2; i <= n; ++i) { if (s[i - 1] == ')') { if (s[i - 2] == '(') { f[i] = f[i - 2] + 2; } else { int j = i - f[i - 1] - 1; if (j && s[j - 1] == '(') { f[i] = f[i - 1] + 2 + f[j - 1]; } } } } return *max_element(f, f + n + 1); } };
32
Longest Valid Parentheses
Hard
<p>Given a string containing just the characters <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>, return <em>the length of the longest valid (well-formed) parentheses </em><span data-keyword="substring-nonempty"><em>substring</em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;(()&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;)()())&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()()&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot; <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s[i]</code> is <code>&#39;(&#39;</code>, or <code>&#39;)&#39;</code>.</li> </ul>
Stack; String; Dynamic Programming
C#
public class Solution { public int LongestValidParentheses(string s) { int n = s.Length; int[] f = new int[n + 1]; int ans = 0; for (int i = 2; i <= n; ++i) { if (s[i - 1] == ')') { if (s[i - 2] == '(') { f[i] = f[i - 2] + 2; } else { int j = i - f[i - 1] - 1; if (j > 0 && s[j - 1] == '(') { f[i] = f[i - 1] + 2 + f[j - 1]; } } ans = Math.Max(ans, f[i]); } } return ans; } }
32
Longest Valid Parentheses
Hard
<p>Given a string containing just the characters <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>, return <em>the length of the longest valid (well-formed) parentheses </em><span data-keyword="substring-nonempty"><em>substring</em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;(()&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;)()())&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()()&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot; <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s[i]</code> is <code>&#39;(&#39;</code>, or <code>&#39;)&#39;</code>.</li> </ul>
Stack; String; Dynamic Programming
Go
func longestValidParentheses(s string) int { n := len(s) f := make([]int, n+1) for i := 2; i <= n; i++ { if s[i-1] == ')' { if s[i-2] == '(' { f[i] = f[i-2] + 2 } else if j := i - f[i-1] - 1; j > 0 && s[j-1] == '(' { f[i] = f[i-1] + 2 + f[j-1] } } } return slices.Max(f) }
32
Longest Valid Parentheses
Hard
<p>Given a string containing just the characters <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>, return <em>the length of the longest valid (well-formed) parentheses </em><span data-keyword="substring-nonempty"><em>substring</em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;(()&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;)()())&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()()&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot; <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s[i]</code> is <code>&#39;(&#39;</code>, or <code>&#39;)&#39;</code>.</li> </ul>
Stack; String; Dynamic Programming
Java
class Solution { public int longestValidParentheses(String s) { int n = s.length(); int[] f = new int[n + 1]; int ans = 0; for (int i = 2; i <= n; ++i) { if (s.charAt(i - 1) == ')') { if (s.charAt(i - 2) == '(') { f[i] = f[i - 2] + 2; } else { int j = i - f[i - 1] - 1; if (j > 0 && s.charAt(j - 1) == '(') { f[i] = f[i - 1] + 2 + f[j - 1]; } } ans = Math.max(ans, f[i]); } } return ans; } }
32
Longest Valid Parentheses
Hard
<p>Given a string containing just the characters <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>, return <em>the length of the longest valid (well-formed) parentheses </em><span data-keyword="substring-nonempty"><em>substring</em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;(()&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;)()())&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()()&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot; <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s[i]</code> is <code>&#39;(&#39;</code>, or <code>&#39;)&#39;</code>.</li> </ul>
Stack; String; Dynamic Programming
JavaScript
/** * @param {string} s * @return {number} */ var longestValidParentheses = function (s) { const n = s.length; const f = new Array(n + 1).fill(0); for (let i = 2; i <= n; ++i) { if (s[i - 1] === ')') { if (s[i - 2] === '(') { f[i] = f[i - 2] + 2; } else { const j = i - f[i - 1] - 1; if (j && s[j - 1] === '(') { f[i] = f[i - 1] + 2 + f[j - 1]; } } } } return Math.max(...f); };
32
Longest Valid Parentheses
Hard
<p>Given a string containing just the characters <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>, return <em>the length of the longest valid (well-formed) parentheses </em><span data-keyword="substring-nonempty"><em>substring</em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;(()&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;)()())&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()()&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot; <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s[i]</code> is <code>&#39;(&#39;</code>, or <code>&#39;)&#39;</code>.</li> </ul>
Stack; String; Dynamic Programming
PHP
class Solution { /** * @param string $s * @return integer */ function longestValidParentheses($s) { $stack = []; $maxLength = 0; array_push($stack, -1); for ($i = 0; $i < strlen($s); $i++) { if ($s[$i] === '(') { array_push($stack, $i); } else { array_pop($stack); if (empty($stack)) { array_push($stack, $i); } else { $length = $i - end($stack); $maxLength = max($maxLength, $length); } } } return $maxLength; } }
32
Longest Valid Parentheses
Hard
<p>Given a string containing just the characters <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>, return <em>the length of the longest valid (well-formed) parentheses </em><span data-keyword="substring-nonempty"><em>substring</em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;(()&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;)()())&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()()&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot; <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s[i]</code> is <code>&#39;(&#39;</code>, or <code>&#39;)&#39;</code>.</li> </ul>
Stack; String; Dynamic Programming
Python
class Solution: def longestValidParentheses(self, s: str) -> int: n = len(s) f = [0] * (n + 1) for i, c in enumerate(s, 1): if c == ")": if i > 1 and s[i - 2] == "(": f[i] = f[i - 2] + 2 else: j = i - f[i - 1] - 1 if j and s[j - 1] == "(": f[i] = f[i - 1] + 2 + f[j - 1] return max(f)
32
Longest Valid Parentheses
Hard
<p>Given a string containing just the characters <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>, return <em>the length of the longest valid (well-formed) parentheses </em><span data-keyword="substring-nonempty"><em>substring</em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;(()&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;)()())&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()()&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot; <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s[i]</code> is <code>&#39;(&#39;</code>, or <code>&#39;)&#39;</code>.</li> </ul>
Stack; String; Dynamic Programming
Rust
impl Solution { pub fn longest_valid_parentheses(s: String) -> i32 { let mut ans = 0; let mut f = vec![0; s.len() + 1]; for i in 2..=s.len() { if s.chars().nth(i - 1).unwrap() == ')' { if s.chars().nth(i - 2).unwrap() == '(' { f[i] = f[i - 2] + 2; } else if (i as i32) - f[i - 1] - 1 > 0 && s.chars().nth(i - (f[i - 1] as usize) - 2).unwrap() == '(' { f[i] = f[i - 1] + 2 + f[i - (f[i - 1] as usize) - 2]; } ans = ans.max(f[i]); } } ans } }
32
Longest Valid Parentheses
Hard
<p>Given a string containing just the characters <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>, return <em>the length of the longest valid (well-formed) parentheses </em><span data-keyword="substring-nonempty"><em>substring</em></span>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;(()&quot; <strong>Output:</strong> 2 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;)()())&quot; <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest valid parentheses substring is &quot;()()&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot; <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>s[i]</code> is <code>&#39;(&#39;</code>, or <code>&#39;)&#39;</code>.</li> </ul>
Stack; String; Dynamic Programming
TypeScript
function longestValidParentheses(s: string): number { const n = s.length; const f: number[] = new Array(n + 1).fill(0); for (let i = 2; i <= n; ++i) { if (s[i - 1] === ')') { if (s[i - 2] === '(') { f[i] = f[i - 2] + 2; } else { const j = i - f[i - 1] - 1; if (j && s[j - 1] === '(') { f[i] = f[i - 1] + 2 + f[j - 1]; } } } } return Math.max(...f); }
33
Search in Rotated Sorted Array
Medium
<p>There is an integer array <code>nums</code> sorted in ascending order (with <strong>distinct</strong> values).</p> <p>Prior to being passed to your function, <code>nums</code> is <strong>possibly rotated</strong> at an unknown pivot index <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,5,6,7]</code> might be rotated at pivot index <code>3</code> and become <code>[4,5,6,7,0,1,2]</code>.</p> <p>Given the array <code>nums</code> <strong>after</strong> the possible rotation and an integer <code>target</code>, return <em>the index of </em><code>target</code><em> if it is in </em><code>nums</code><em>, or </em><code>-1</code><em> if it is not in </em><code>nums</code>.</p> <p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 0 <strong>Output:</strong> 4 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 3 <strong>Output:</strong> -1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1], target = 0 <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li>All values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is an ascending array that is possibly rotated.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
C++
class Solution { public: int search(vector<int>& nums, int target) { int n = nums.size(); int left = 0, right = n - 1; while (left < right) { int mid = (left + right) >> 1; if (nums[0] <= nums[mid]) { if (nums[0] <= target && target <= nums[mid]) right = mid; else left = mid + 1; } else { if (nums[mid] < target && target <= nums[n - 1]) left = mid + 1; else right = mid; } } return nums[left] == target ? left : -1; } };
33
Search in Rotated Sorted Array
Medium
<p>There is an integer array <code>nums</code> sorted in ascending order (with <strong>distinct</strong> values).</p> <p>Prior to being passed to your function, <code>nums</code> is <strong>possibly rotated</strong> at an unknown pivot index <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,5,6,7]</code> might be rotated at pivot index <code>3</code> and become <code>[4,5,6,7,0,1,2]</code>.</p> <p>Given the array <code>nums</code> <strong>after</strong> the possible rotation and an integer <code>target</code>, return <em>the index of </em><code>target</code><em> if it is in </em><code>nums</code><em>, or </em><code>-1</code><em> if it is not in </em><code>nums</code>.</p> <p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 0 <strong>Output:</strong> 4 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 3 <strong>Output:</strong> -1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1], target = 0 <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li>All values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is an ascending array that is possibly rotated.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
C#
public class Solution { public int Search(int[] nums, int target) { int n = nums.Length; int left = 0, right = n - 1; while (left < right) { int mid = (left + right) >> 1; if (nums[0] <= nums[mid]) { if (nums[0] <= target && target <= nums[mid]) { right = mid; } else { left = mid + 1; } } else { if (nums[mid] < target && target <= nums[n - 1]) { left = mid + 1; } else { right = mid; } } } return nums[left] == target ? left : -1; } }
33
Search in Rotated Sorted Array
Medium
<p>There is an integer array <code>nums</code> sorted in ascending order (with <strong>distinct</strong> values).</p> <p>Prior to being passed to your function, <code>nums</code> is <strong>possibly rotated</strong> at an unknown pivot index <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,5,6,7]</code> might be rotated at pivot index <code>3</code> and become <code>[4,5,6,7,0,1,2]</code>.</p> <p>Given the array <code>nums</code> <strong>after</strong> the possible rotation and an integer <code>target</code>, return <em>the index of </em><code>target</code><em> if it is in </em><code>nums</code><em>, or </em><code>-1</code><em> if it is not in </em><code>nums</code>.</p> <p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 0 <strong>Output:</strong> 4 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 3 <strong>Output:</strong> -1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1], target = 0 <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li>All values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is an ascending array that is possibly rotated.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
Go
func search(nums []int, target int) int { n := len(nums) left, right := 0, n-1 for left < right { mid := (left + right) >> 1 if nums[0] <= nums[mid] { if nums[0] <= target && target <= nums[mid] { right = mid } else { left = mid + 1 } } else { if nums[mid] < target && target <= nums[n-1] { left = mid + 1 } else { right = mid } } } if nums[left] == target { return left } return -1 }
33
Search in Rotated Sorted Array
Medium
<p>There is an integer array <code>nums</code> sorted in ascending order (with <strong>distinct</strong> values).</p> <p>Prior to being passed to your function, <code>nums</code> is <strong>possibly rotated</strong> at an unknown pivot index <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,5,6,7]</code> might be rotated at pivot index <code>3</code> and become <code>[4,5,6,7,0,1,2]</code>.</p> <p>Given the array <code>nums</code> <strong>after</strong> the possible rotation and an integer <code>target</code>, return <em>the index of </em><code>target</code><em> if it is in </em><code>nums</code><em>, or </em><code>-1</code><em> if it is not in </em><code>nums</code>.</p> <p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 0 <strong>Output:</strong> 4 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 3 <strong>Output:</strong> -1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1], target = 0 <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li>All values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is an ascending array that is possibly rotated.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
Java
class Solution { public int search(int[] nums, int target) { int n = nums.length; int left = 0, right = n - 1; while (left < right) { int mid = (left + right) >> 1; if (nums[0] <= nums[mid]) { if (nums[0] <= target && target <= nums[mid]) { right = mid; } else { left = mid + 1; } } else { if (nums[mid] < target && target <= nums[n - 1]) { left = mid + 1; } else { right = mid; } } } return nums[left] == target ? left : -1; } }
33
Search in Rotated Sorted Array
Medium
<p>There is an integer array <code>nums</code> sorted in ascending order (with <strong>distinct</strong> values).</p> <p>Prior to being passed to your function, <code>nums</code> is <strong>possibly rotated</strong> at an unknown pivot index <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,5,6,7]</code> might be rotated at pivot index <code>3</code> and become <code>[4,5,6,7,0,1,2]</code>.</p> <p>Given the array <code>nums</code> <strong>after</strong> the possible rotation and an integer <code>target</code>, return <em>the index of </em><code>target</code><em> if it is in </em><code>nums</code><em>, or </em><code>-1</code><em> if it is not in </em><code>nums</code>.</p> <p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 0 <strong>Output:</strong> 4 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 3 <strong>Output:</strong> -1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1], target = 0 <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li>All values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is an ascending array that is possibly rotated.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
JavaScript
/** * @param {number[]} nums * @param {number} target * @return {number} */ var search = function (nums, target) { const n = nums.length; let left = 0, right = n - 1; while (left < right) { const mid = (left + right) >> 1; if (nums[0] <= nums[mid]) { if (nums[0] <= target && target <= nums[mid]) { right = mid; } else { left = mid + 1; } } else { if (nums[mid] < target && target <= nums[n - 1]) { left = mid + 1; } else { right = mid; } } } return nums[left] == target ? left : -1; };
33
Search in Rotated Sorted Array
Medium
<p>There is an integer array <code>nums</code> sorted in ascending order (with <strong>distinct</strong> values).</p> <p>Prior to being passed to your function, <code>nums</code> is <strong>possibly rotated</strong> at an unknown pivot index <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,5,6,7]</code> might be rotated at pivot index <code>3</code> and become <code>[4,5,6,7,0,1,2]</code>.</p> <p>Given the array <code>nums</code> <strong>after</strong> the possible rotation and an integer <code>target</code>, return <em>the index of </em><code>target</code><em> if it is in </em><code>nums</code><em>, or </em><code>-1</code><em> if it is not in </em><code>nums</code>.</p> <p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 0 <strong>Output:</strong> 4 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 3 <strong>Output:</strong> -1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1], target = 0 <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li>All values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is an ascending array that is possibly rotated.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
PHP
class Solution { /** * @param integer[] $nums * @param integer $target * @return integer */ function search($nums, $target) { $foundKey = -1; foreach ($nums as $key => $value) { if ($value === $target) { $foundKey = $key; } } return $foundKey; } }
33
Search in Rotated Sorted Array
Medium
<p>There is an integer array <code>nums</code> sorted in ascending order (with <strong>distinct</strong> values).</p> <p>Prior to being passed to your function, <code>nums</code> is <strong>possibly rotated</strong> at an unknown pivot index <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,5,6,7]</code> might be rotated at pivot index <code>3</code> and become <code>[4,5,6,7,0,1,2]</code>.</p> <p>Given the array <code>nums</code> <strong>after</strong> the possible rotation and an integer <code>target</code>, return <em>the index of </em><code>target</code><em> if it is in </em><code>nums</code><em>, or </em><code>-1</code><em> if it is not in </em><code>nums</code>.</p> <p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 0 <strong>Output:</strong> 4 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 3 <strong>Output:</strong> -1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1], target = 0 <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li>All values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is an ascending array that is possibly rotated.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
Python
class Solution: def search(self, nums: List[int], target: int) -> int: n = len(nums) left, right = 0, n - 1 while left < right: mid = (left + right) >> 1 if nums[0] <= nums[mid]: if nums[0] <= target <= nums[mid]: right = mid else: left = mid + 1 else: if nums[mid] < target <= nums[n - 1]: left = mid + 1 else: right = mid return left if nums[left] == target else -1
33
Search in Rotated Sorted Array
Medium
<p>There is an integer array <code>nums</code> sorted in ascending order (with <strong>distinct</strong> values).</p> <p>Prior to being passed to your function, <code>nums</code> is <strong>possibly rotated</strong> at an unknown pivot index <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,5,6,7]</code> might be rotated at pivot index <code>3</code> and become <code>[4,5,6,7,0,1,2]</code>.</p> <p>Given the array <code>nums</code> <strong>after</strong> the possible rotation and an integer <code>target</code>, return <em>the index of </em><code>target</code><em> if it is in </em><code>nums</code><em>, or </em><code>-1</code><em> if it is not in </em><code>nums</code>.</p> <p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 0 <strong>Output:</strong> 4 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 3 <strong>Output:</strong> -1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1], target = 0 <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li>All values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is an ascending array that is possibly rotated.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
Rust
impl Solution { pub fn search(nums: Vec<i32>, target: i32) -> i32 { let mut l = 0; let mut r = nums.len() - 1; while l <= r { let mid = (l + r) >> 1; if nums[mid] == target { return mid as i32; } if nums[l] <= nums[mid] { if target < nums[mid] && target >= nums[l] { r = mid - 1; } else { l = mid + 1; } } else { if target > nums[mid] && target <= nums[r] { l = mid + 1; } else { r = mid - 1; } } } -1 } }
33
Search in Rotated Sorted Array
Medium
<p>There is an integer array <code>nums</code> sorted in ascending order (with <strong>distinct</strong> values).</p> <p>Prior to being passed to your function, <code>nums</code> is <strong>possibly rotated</strong> at an unknown pivot index <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,5,6,7]</code> might be rotated at pivot index <code>3</code> and become <code>[4,5,6,7,0,1,2]</code>.</p> <p>Given the array <code>nums</code> <strong>after</strong> the possible rotation and an integer <code>target</code>, return <em>the index of </em><code>target</code><em> if it is in </em><code>nums</code><em>, or </em><code>-1</code><em> if it is not in </em><code>nums</code>.</p> <p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 0 <strong>Output:</strong> 4 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 3 <strong>Output:</strong> -1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [1], target = 0 <strong>Output:</strong> -1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5000</code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li>All values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is an ascending array that is possibly rotated.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
TypeScript
function search(nums: number[], target: number): number { const n = nums.length; let left = 0, right = n - 1; while (left < right) { const mid = (left + right) >> 1; if (nums[0] <= nums[mid]) { if (nums[0] <= target && target <= nums[mid]) { right = mid; } else { left = mid + 1; } } else { if (nums[mid] < target && target <= nums[n - 1]) { left = mid + 1; } else { right = mid; } } } return nums[left] == target ? left : -1; }
34
Find First and Last Position of Element in Sorted Array
Medium
<p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p> <p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8 <strong>Output:</strong> [3,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6 <strong>Output:</strong> [-1,-1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> [-1,-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is a non-decreasing array.</li> <li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
C++
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int l = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); int r = lower_bound(nums.begin(), nums.end(), target + 1) - nums.begin(); if (l == r) { return {-1, -1}; } return {l, r - 1}; } };
34
Find First and Last Position of Element in Sorted Array
Medium
<p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p> <p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8 <strong>Output:</strong> [3,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6 <strong>Output:</strong> [-1,-1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> [-1,-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is a non-decreasing array.</li> <li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
C#
public class Solution { public int[] SearchRange(int[] nums, int target) { int l = Search(nums, target); int r = Search(nums, target + 1); return l == r ? new int[] {-1, -1} : new int[] {l, r - 1}; } private int Search(int[] nums, int x) { int left = 0, right = nums.Length; while (left < right) { int mid = (left + right) >>> 1; if (nums[mid] >= x) { right = mid; } else { left = mid + 1; } } return left; } }
34
Find First and Last Position of Element in Sorted Array
Medium
<p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p> <p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8 <strong>Output:</strong> [3,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6 <strong>Output:</strong> [-1,-1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> [-1,-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is a non-decreasing array.</li> <li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
Go
func searchRange(nums []int, target int) []int { l := sort.SearchInts(nums, target) r := sort.SearchInts(nums, target+1) if l == r { return []int{-1, -1} } return []int{l, r - 1} }
34
Find First and Last Position of Element in Sorted Array
Medium
<p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p> <p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8 <strong>Output:</strong> [3,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6 <strong>Output:</strong> [-1,-1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> [-1,-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is a non-decreasing array.</li> <li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
Java
class Solution { public int[] searchRange(int[] nums, int target) { int l = search(nums, target); int r = search(nums, target + 1); return l == r ? new int[] {-1, -1} : new int[] {l, r - 1}; } private int search(int[] nums, int x) { int left = 0, right = nums.length; while (left < right) { int mid = (left + right) >>> 1; if (nums[mid] >= x) { right = mid; } else { left = mid + 1; } } return left; } }
34
Find First and Last Position of Element in Sorted Array
Medium
<p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p> <p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8 <strong>Output:</strong> [3,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6 <strong>Output:</strong> [-1,-1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> [-1,-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is a non-decreasing array.</li> <li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
JavaScript
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var searchRange = function (nums, target) { function search(x) { let left = 0, right = nums.length; while (left < right) { const mid = (left + right) >> 1; if (nums[mid] >= x) { right = mid; } else { left = mid + 1; } } return left; } const l = search(target); const r = search(target + 1); return l == r ? [-1, -1] : [l, r - 1]; };
34
Find First and Last Position of Element in Sorted Array
Medium
<p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p> <p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8 <strong>Output:</strong> [3,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6 <strong>Output:</strong> [-1,-1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> [-1,-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is a non-decreasing array.</li> <li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
Kotlin
class Solution { fun searchRange(nums: IntArray, target: Int): IntArray { val left = this.search(nums, target) val right = this.search(nums, target + 1) return if (left == right) intArrayOf(-1, -1) else intArrayOf(left, right - 1) } private fun search(nums: IntArray, target: Int): Int { var left = 0 var right = nums.size while (left < right) { val middle = (left + right) / 2 if (nums[middle] < target) { left = middle + 1 } else { right = middle } } return left } }
34
Find First and Last Position of Element in Sorted Array
Medium
<p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p> <p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8 <strong>Output:</strong> [3,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6 <strong>Output:</strong> [-1,-1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> [-1,-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is a non-decreasing array.</li> <li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
PHP
class Solution { /** * @param integer[] $nums * @param integer $target * @return integer[] */ function searchRange($nums, $target) { $min = -1; $max = -1; foreach ($nums as $key => $value) { if ($value == $target) { if ($min == -1) { $min = $key; } if ($key > $max) { $max = $key; } } } return [$min, $max]; } }
34
Find First and Last Position of Element in Sorted Array
Medium
<p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p> <p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8 <strong>Output:</strong> [3,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6 <strong>Output:</strong> [-1,-1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> [-1,-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is a non-decreasing array.</li> <li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
Python
class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: l = bisect_left(nums, target) r = bisect_left(nums, target + 1) return [-1, -1] if l == r else [l, r - 1]
34
Find First and Last Position of Element in Sorted Array
Medium
<p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p> <p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8 <strong>Output:</strong> [3,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6 <strong>Output:</strong> [-1,-1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> [-1,-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is a non-decreasing array.</li> <li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
Rust
impl Solution { pub fn search_range(nums: Vec<i32>, target: i32) -> Vec<i32> { let n = nums.len(); let search = |x| { let mut left = 0; let mut right = n; while left < right { let mid = left + (right - left) / 2; if nums[mid] < x { left = mid + 1; } else { right = mid; } } left }; let l = search(target); let r = search(target + 1); if l == r { return vec![-1, -1]; } vec![l as i32, (r - 1) as i32] } }
34
Find First and Last Position of Element in Sorted Array
Medium
<p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p> <p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8 <strong>Output:</strong> [3,4] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6 <strong>Output:</strong> [-1,-1] </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> nums = [], target = 0 <strong>Output:</strong> [-1,-1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li> <li><code>nums</code> is a non-decreasing array.</li> <li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li> </ul>
Array; Binary Search
TypeScript
function searchRange(nums: number[], target: number): number[] { const search = (x: number): number => { let [left, right] = [0, nums.length]; while (left < right) { const mid = (left + right) >> 1; if (nums[mid] >= x) { right = mid; } else { left = mid + 1; } } return left; }; const l = search(target); const r = search(target + 1); return l === r ? [-1, -1] : [l, r - 1]; }
35
Search Insert Position
Easy
<p>Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 5 <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 2 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 7 <strong>Output:</strong> 4 </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>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> contains <strong>distinct</strong> values sorted in <strong>ascending</strong> order.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
C++
class Solution { public: int searchInsert(vector<int>& nums, int target) { int l = 0, r = nums.size(); while (l < r) { int mid = (l + r) >> 1; if (nums[mid] >= target) { r = mid; } else { l = mid + 1; } } return l; } };
35
Search Insert Position
Easy
<p>Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 5 <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 2 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 7 <strong>Output:</strong> 4 </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>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> contains <strong>distinct</strong> values sorted in <strong>ascending</strong> order.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
Go
func searchInsert(nums []int, target int) int { l, r := 0, len(nums) for l < r { mid := (l + r) >> 1 if nums[mid] >= target { r = mid } else { l = mid + 1 } } return l }
35
Search Insert Position
Easy
<p>Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 5 <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 2 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 7 <strong>Output:</strong> 4 </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>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> contains <strong>distinct</strong> values sorted in <strong>ascending</strong> order.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
Java
class Solution { public int searchInsert(int[] nums, int target) { int l = 0, r = nums.length; while (l < r) { int mid = (l + r) >>> 1; if (nums[mid] >= target) { r = mid; } else { l = mid + 1; } } return l; } }
35
Search Insert Position
Easy
<p>Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 5 <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 2 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 7 <strong>Output:</strong> 4 </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>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> contains <strong>distinct</strong> values sorted in <strong>ascending</strong> order.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
JavaScript
/** * @param {number[]} nums * @param {number} target * @return {number} */ var searchInsert = function (nums, target) { let [l, r] = [0, nums.length]; while (l < r) { const mid = (l + r) >> 1; if (nums[mid] >= target) { r = mid; } else { l = mid + 1; } } return l; };
35
Search Insert Position
Easy
<p>Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 5 <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 2 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 7 <strong>Output:</strong> 4 </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>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> contains <strong>distinct</strong> values sorted in <strong>ascending</strong> order.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
PHP
class Solution { /** * @param Integer[] $nums * @param Integer $target * @return Integer */ function searchInsert($nums, $target) { $l = 0; $r = count($nums); while ($l < $r) { $mid = $l + $r >> 1; if ($nums[$mid] >= $target) { $r = $mid; } else { $l = $mid + 1; } } return $l; } }
35
Search Insert Position
Easy
<p>Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 5 <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 2 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 7 <strong>Output:</strong> 4 </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>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> contains <strong>distinct</strong> values sorted in <strong>ascending</strong> order.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
Python
class Solution: def searchInsert(self, nums: List[int], target: int) -> int: l, r = 0, len(nums) while l < r: mid = (l + r) >> 1 if nums[mid] >= target: r = mid else: l = mid + 1 return l
35
Search Insert Position
Easy
<p>Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 5 <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 2 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 7 <strong>Output:</strong> 4 </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>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> contains <strong>distinct</strong> values sorted in <strong>ascending</strong> order.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
Rust
impl Solution { pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 { let mut l: usize = 0; let mut r: usize = nums.len(); while l < r { let mid = (l + r) >> 1; if nums[mid] >= target { r = mid; } else { l = mid + 1; } } l as i32 } }
35
Search Insert Position
Easy
<p>Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.</p> <p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 5 <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 2 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,3,5,6], target = 7 <strong>Output:</strong> 4 </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>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>nums</code> contains <strong>distinct</strong> values sorted in <strong>ascending</strong> order.</li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Binary Search
TypeScript
function searchInsert(nums: number[], target: number): number { let [l, r] = [0, nums.length]; while (l < r) { const mid = (l + r) >> 1; if (nums[mid] >= target) { r = mid; } else { l = mid + 1; } } return l; }
36
Valid Sudoku
Medium
<p>Determine if a&nbsp;<code>9 x 9</code> Sudoku board&nbsp;is valid.&nbsp;Only the filled cells need to be validated&nbsp;<strong>according to the following rules</strong>:</p> <ol> <li>Each row&nbsp;must contain the&nbsp;digits&nbsp;<code>1-9</code> without repetition.</li> <li>Each column must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> <li>Each of the nine&nbsp;<code>3 x 3</code> sub-boxes of the grid must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> </ol> <p><strong>Note:</strong></p> <ul> <li>A Sudoku board (partially filled) could be valid but is not necessarily solvable.</li> <li>Only the filled cells need to be validated according to the mentioned&nbsp;rules.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0036.Valid%20Sudoku/images/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /> <pre> <strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> board = [[&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> false <strong>Explanation:</strong> Same as Example 1, except with the <strong>5</strong> in the top left corner being modified to <strong>8</strong>. Since there are two 8&#39;s in the top left 3x3 sub-box, it is invalid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>board.length == 9</code></li> <li><code>board[i].length == 9</code></li> <li><code>board[i][j]</code> is a digit <code>1-9</code> or <code>&#39;.&#39;</code>.</li> </ul>
Array; Hash Table; Matrix
C++
class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { vector<vector<bool>> row(9, vector<bool>(9, false)); vector<vector<bool>> col(9, vector<bool>(9, false)); vector<vector<bool>> sub(9, vector<bool>(9, false)); for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { char c = board[i][j]; if (c == '.') continue; int num = c - '0' - 1; int k = i / 3 * 3 + j / 3; if (row[i][num] || col[j][num] || sub[k][num]) { return false; } row[i][num] = true; col[j][num] = true; sub[k][num] = true; } } return true; } };
36
Valid Sudoku
Medium
<p>Determine if a&nbsp;<code>9 x 9</code> Sudoku board&nbsp;is valid.&nbsp;Only the filled cells need to be validated&nbsp;<strong>according to the following rules</strong>:</p> <ol> <li>Each row&nbsp;must contain the&nbsp;digits&nbsp;<code>1-9</code> without repetition.</li> <li>Each column must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> <li>Each of the nine&nbsp;<code>3 x 3</code> sub-boxes of the grid must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> </ol> <p><strong>Note:</strong></p> <ul> <li>A Sudoku board (partially filled) could be valid but is not necessarily solvable.</li> <li>Only the filled cells need to be validated according to the mentioned&nbsp;rules.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0036.Valid%20Sudoku/images/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /> <pre> <strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> board = [[&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> false <strong>Explanation:</strong> Same as Example 1, except with the <strong>5</strong> in the top left corner being modified to <strong>8</strong>. Since there are two 8&#39;s in the top left 3x3 sub-box, it is invalid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>board.length == 9</code></li> <li><code>board[i].length == 9</code></li> <li><code>board[i][j]</code> is a digit <code>1-9</code> or <code>&#39;.&#39;</code>.</li> </ul>
Array; Hash Table; Matrix
Go
func isValidSudoku(board [][]byte) bool { row, col, sub := [9][9]bool{}, [9][9]bool{}, [9][9]bool{} for i := 0; i < 9; i++ { for j := 0; j < 9; j++ { num := board[i][j] - byte('1') if num < 0 || num > 9 { continue } k := i/3*3 + j/3 if row[i][num] || col[j][num] || sub[k][num] { return false } row[i][num] = true col[j][num] = true sub[k][num] = true } } return true }
36
Valid Sudoku
Medium
<p>Determine if a&nbsp;<code>9 x 9</code> Sudoku board&nbsp;is valid.&nbsp;Only the filled cells need to be validated&nbsp;<strong>according to the following rules</strong>:</p> <ol> <li>Each row&nbsp;must contain the&nbsp;digits&nbsp;<code>1-9</code> without repetition.</li> <li>Each column must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> <li>Each of the nine&nbsp;<code>3 x 3</code> sub-boxes of the grid must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> </ol> <p><strong>Note:</strong></p> <ul> <li>A Sudoku board (partially filled) could be valid but is not necessarily solvable.</li> <li>Only the filled cells need to be validated according to the mentioned&nbsp;rules.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0036.Valid%20Sudoku/images/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /> <pre> <strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> board = [[&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> false <strong>Explanation:</strong> Same as Example 1, except with the <strong>5</strong> in the top left corner being modified to <strong>8</strong>. Since there are two 8&#39;s in the top left 3x3 sub-box, it is invalid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>board.length == 9</code></li> <li><code>board[i].length == 9</code></li> <li><code>board[i][j]</code> is a digit <code>1-9</code> or <code>&#39;.&#39;</code>.</li> </ul>
Array; Hash Table; Matrix
Java
class Solution { public boolean isValidSudoku(char[][] board) { boolean[][] row = new boolean[9][9]; boolean[][] col = new boolean[9][9]; boolean[][] sub = new boolean[9][9]; for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { char c = board[i][j]; if (c == '.') { continue; } int num = c - '0' - 1; int k = i / 3 * 3 + j / 3; if (row[i][num] || col[j][num] || sub[k][num]) { return false; } row[i][num] = true; col[j][num] = true; sub[k][num] = true; } } return true; } }
36
Valid Sudoku
Medium
<p>Determine if a&nbsp;<code>9 x 9</code> Sudoku board&nbsp;is valid.&nbsp;Only the filled cells need to be validated&nbsp;<strong>according to the following rules</strong>:</p> <ol> <li>Each row&nbsp;must contain the&nbsp;digits&nbsp;<code>1-9</code> without repetition.</li> <li>Each column must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> <li>Each of the nine&nbsp;<code>3 x 3</code> sub-boxes of the grid must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> </ol> <p><strong>Note:</strong></p> <ul> <li>A Sudoku board (partially filled) could be valid but is not necessarily solvable.</li> <li>Only the filled cells need to be validated according to the mentioned&nbsp;rules.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0036.Valid%20Sudoku/images/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /> <pre> <strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> board = [[&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> false <strong>Explanation:</strong> Same as Example 1, except with the <strong>5</strong> in the top left corner being modified to <strong>8</strong>. Since there are two 8&#39;s in the top left 3x3 sub-box, it is invalid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>board.length == 9</code></li> <li><code>board[i].length == 9</code></li> <li><code>board[i][j]</code> is a digit <code>1-9</code> or <code>&#39;.&#39;</code>.</li> </ul>
Array; Hash Table; Matrix
JavaScript
/** * @param {character[][]} board * @return {boolean} */ var isValidSudoku = function (board) { const row = [...Array(9)].map(() => Array(9).fill(false)); const col = [...Array(9)].map(() => Array(9).fill(false)); const sub = [...Array(9)].map(() => Array(9).fill(false)); for (let i = 0; i < 9; ++i) { for (let j = 0; j < 9; ++j) { const num = board[i][j].charCodeAt() - '1'.charCodeAt(); if (num < 0 || num > 8) { continue; } const k = Math.floor(i / 3) * 3 + Math.floor(j / 3); if (row[i][num] || col[j][num] || sub[k][num]) { return false; } row[i][num] = true; col[j][num] = true; sub[k][num] = true; } } return true; };
36
Valid Sudoku
Medium
<p>Determine if a&nbsp;<code>9 x 9</code> Sudoku board&nbsp;is valid.&nbsp;Only the filled cells need to be validated&nbsp;<strong>according to the following rules</strong>:</p> <ol> <li>Each row&nbsp;must contain the&nbsp;digits&nbsp;<code>1-9</code> without repetition.</li> <li>Each column must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> <li>Each of the nine&nbsp;<code>3 x 3</code> sub-boxes of the grid must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> </ol> <p><strong>Note:</strong></p> <ul> <li>A Sudoku board (partially filled) could be valid but is not necessarily solvable.</li> <li>Only the filled cells need to be validated according to the mentioned&nbsp;rules.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0036.Valid%20Sudoku/images/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /> <pre> <strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> board = [[&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> false <strong>Explanation:</strong> Same as Example 1, except with the <strong>5</strong> in the top left corner being modified to <strong>8</strong>. Since there are two 8&#39;s in the top left 3x3 sub-box, it is invalid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>board.length == 9</code></li> <li><code>board[i].length == 9</code></li> <li><code>board[i][j]</code> is a digit <code>1-9</code> or <code>&#39;.&#39;</code>.</li> </ul>
Array; Hash Table; Matrix
PHP
class Solution { /** * @param string[][] $board * @return boolean */ function isValidSudoku($board) { $rows = []; $columns = []; $boxes = []; for ($i = 0; $i < 9; $i++) { $rows[$i] = []; $columns[$i] = []; $boxes[$i] = []; } for ($row = 0; $row < 9; $row++) { for ($column = 0; $column < 9; $column++) { $cell = $board[$row][$column]; if ($cell != '.') { if (in_array($cell, $rows[$row]) || in_array($cell, $columns[$column]) || in_array($cell, $boxes[floor($row / 3) * 3 + floor($column / 3)])) { return false; } $rows[$row][] = $cell; $columns[$column][] = $cell; $boxes[floor($row / 3) * 3 + floor($column / 3)][] = $cell; } } } return true; } }
36
Valid Sudoku
Medium
<p>Determine if a&nbsp;<code>9 x 9</code> Sudoku board&nbsp;is valid.&nbsp;Only the filled cells need to be validated&nbsp;<strong>according to the following rules</strong>:</p> <ol> <li>Each row&nbsp;must contain the&nbsp;digits&nbsp;<code>1-9</code> without repetition.</li> <li>Each column must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> <li>Each of the nine&nbsp;<code>3 x 3</code> sub-boxes of the grid must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> </ol> <p><strong>Note:</strong></p> <ul> <li>A Sudoku board (partially filled) could be valid but is not necessarily solvable.</li> <li>Only the filled cells need to be validated according to the mentioned&nbsp;rules.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0036.Valid%20Sudoku/images/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /> <pre> <strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> board = [[&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> false <strong>Explanation:</strong> Same as Example 1, except with the <strong>5</strong> in the top left corner being modified to <strong>8</strong>. Since there are two 8&#39;s in the top left 3x3 sub-box, it is invalid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>board.length == 9</code></li> <li><code>board[i].length == 9</code></li> <li><code>board[i][j]</code> is a digit <code>1-9</code> or <code>&#39;.&#39;</code>.</li> </ul>
Array; Hash Table; Matrix
Python
class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: row = [[False] * 9 for _ in range(9)] col = [[False] * 9 for _ in range(9)] sub = [[False] * 9 for _ in range(9)] for i in range(9): for j in range(9): c = board[i][j] if c == '.': continue num = int(c) - 1 k = i // 3 * 3 + j // 3 if row[i][num] or col[j][num] or sub[k][num]: return False row[i][num] = True col[j][num] = True sub[k][num] = True return True
36
Valid Sudoku
Medium
<p>Determine if a&nbsp;<code>9 x 9</code> Sudoku board&nbsp;is valid.&nbsp;Only the filled cells need to be validated&nbsp;<strong>according to the following rules</strong>:</p> <ol> <li>Each row&nbsp;must contain the&nbsp;digits&nbsp;<code>1-9</code> without repetition.</li> <li>Each column must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> <li>Each of the nine&nbsp;<code>3 x 3</code> sub-boxes of the grid must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li> </ol> <p><strong>Note:</strong></p> <ul> <li>A Sudoku board (partially filled) could be valid but is not necessarily solvable.</li> <li>Only the filled cells need to be validated according to the mentioned&nbsp;rules.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0036.Valid%20Sudoku/images/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /> <pre> <strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> board = [[&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;] ,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;] ,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;] ,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;] ,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;] ,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> false <strong>Explanation:</strong> Same as Example 1, except with the <strong>5</strong> in the top left corner being modified to <strong>8</strong>. Since there are two 8&#39;s in the top left 3x3 sub-box, it is invalid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>board.length == 9</code></li> <li><code>board[i].length == 9</code></li> <li><code>board[i][j]</code> is a digit <code>1-9</code> or <code>&#39;.&#39;</code>.</li> </ul>
Array; Hash Table; Matrix
TypeScript
function isValidSudoku(board: string[][]): boolean { const row: boolean[][] = Array.from({ length: 9 }, () => Array.from({ length: 9 }, () => false), ); const col: boolean[][] = Array.from({ length: 9 }, () => Array.from({ length: 9 }, () => false), ); const sub: boolean[][] = Array.from({ length: 9 }, () => Array.from({ length: 9 }, () => false), ); for (let i = 0; i < 9; ++i) { for (let j = 0; j < 9; ++j) { const num = board[i][j].charCodeAt(0) - '1'.charCodeAt(0); if (num < 0 || num > 8) { continue; } const k = Math.floor(i / 3) * 3 + Math.floor(j / 3); if (row[i][num] || col[j][num] || sub[k][num]) { return false; } row[i][num] = true; col[j][num] = true; sub[k][num] = true; } } return true; }
37
Sudoku Solver
Hard
<p>Write a program to solve a Sudoku puzzle by filling the empty cells.</p> <p>A sudoku solution must satisfy <strong>all of the following rules</strong>:</p> <ol> <li>Each of the digits <code>1-9</code> must occur exactly once in each row.</li> <li>Each of the digits <code>1-9</code> must occur exactly once in each column.</li> <li>Each of the digits <code>1-9</code> must occur exactly once in each of the 9 <code>3x3</code> sub-boxes of the grid.</li> </ol> <p>The <code>&#39;.&#39;</code> character indicates empty cells.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0037.Sudoku%20Solver/images/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /> <pre> <strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;],[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;],[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> [[&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;1&quot;,&quot;2&quot;],[&quot;6&quot;,&quot;7&quot;,&quot;2&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;8&quot;],[&quot;1&quot;,&quot;9&quot;,&quot;8&quot;,&quot;3&quot;,&quot;4&quot;,&quot;2&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;],[&quot;8&quot;,&quot;5&quot;,&quot;9&quot;,&quot;7&quot;,&quot;6&quot;,&quot;1&quot;,&quot;4&quot;,&quot;2&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;2&quot;,&quot;6&quot;,&quot;8&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;9&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;1&quot;,&quot;3&quot;,&quot;9&quot;,&quot;2&quot;,&quot;4&quot;,&quot;8&quot;,&quot;5&quot;,&quot;6&quot;],[&quot;9&quot;,&quot;6&quot;,&quot;1&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;2&quot;,&quot;8&quot;,&quot;4&quot;],[&quot;2&quot;,&quot;8&quot;,&quot;7&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;6&quot;,&quot;3&quot;,&quot;5&quot;],[&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;2&quot;,&quot;8&quot;,&quot;6&quot;,&quot;1&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Explanation:</strong>&nbsp;The input board is shown above and the only valid solution is shown below: <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0037.Sudoku%20Solver/images/250px-Sudoku-by-L2G-20050714_solution.svg.png" style="height:250px; width:250px" /> </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>board.length == 9</code></li> <li><code>board[i].length == 9</code></li> <li><code>board[i][j]</code> is a digit or <code>&#39;.&#39;</code>.</li> <li>It is <strong>guaranteed</strong> that the input board has only one solution.</li> </ul>
Array; Hash Table; Backtracking; Matrix
C++
using pii = pair<int, int>; class Solution { public: void solveSudoku(vector<vector<char>>& board) { bool row[9][9] = {false}; bool col[9][9] = {false}; bool block[3][3][9] = {false}; bool ok = false; vector<pii> t; for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { if (board[i][j] == '.') { t.push_back({i, j}); } else { int v = board[i][j] - '1'; row[i][v] = col[j][v] = block[i / 3][j / 3][v] = true; } } } function<void(int k)> dfs = [&](int k) { if (k == t.size()) { ok = true; return; } int i = t[k].first, j = t[k].second; for (int v = 0; v < 9; ++v) { if (!row[i][v] && !col[j][v] && !block[i / 3][j / 3][v]) { row[i][v] = col[j][v] = block[i / 3][j / 3][v] = true; board[i][j] = v + '1'; dfs(k + 1); row[i][v] = col[j][v] = block[i / 3][j / 3][v] = false; } if (ok) { return; } } }; dfs(0); } };
37
Sudoku Solver
Hard
<p>Write a program to solve a Sudoku puzzle by filling the empty cells.</p> <p>A sudoku solution must satisfy <strong>all of the following rules</strong>:</p> <ol> <li>Each of the digits <code>1-9</code> must occur exactly once in each row.</li> <li>Each of the digits <code>1-9</code> must occur exactly once in each column.</li> <li>Each of the digits <code>1-9</code> must occur exactly once in each of the 9 <code>3x3</code> sub-boxes of the grid.</li> </ol> <p>The <code>&#39;.&#39;</code> character indicates empty cells.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0037.Sudoku%20Solver/images/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /> <pre> <strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;],[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;],[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> [[&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;1&quot;,&quot;2&quot;],[&quot;6&quot;,&quot;7&quot;,&quot;2&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;8&quot;],[&quot;1&quot;,&quot;9&quot;,&quot;8&quot;,&quot;3&quot;,&quot;4&quot;,&quot;2&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;],[&quot;8&quot;,&quot;5&quot;,&quot;9&quot;,&quot;7&quot;,&quot;6&quot;,&quot;1&quot;,&quot;4&quot;,&quot;2&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;2&quot;,&quot;6&quot;,&quot;8&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;9&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;1&quot;,&quot;3&quot;,&quot;9&quot;,&quot;2&quot;,&quot;4&quot;,&quot;8&quot;,&quot;5&quot;,&quot;6&quot;],[&quot;9&quot;,&quot;6&quot;,&quot;1&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;2&quot;,&quot;8&quot;,&quot;4&quot;],[&quot;2&quot;,&quot;8&quot;,&quot;7&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;6&quot;,&quot;3&quot;,&quot;5&quot;],[&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;2&quot;,&quot;8&quot;,&quot;6&quot;,&quot;1&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Explanation:</strong>&nbsp;The input board is shown above and the only valid solution is shown below: <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0037.Sudoku%20Solver/images/250px-Sudoku-by-L2G-20050714_solution.svg.png" style="height:250px; width:250px" /> </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>board.length == 9</code></li> <li><code>board[i].length == 9</code></li> <li><code>board[i][j]</code> is a digit or <code>&#39;.&#39;</code>.</li> <li>It is <strong>guaranteed</strong> that the input board has only one solution.</li> </ul>
Array; Hash Table; Backtracking; Matrix
C#
public class Solution { public void SolveSudoku(char[][] board) { this.board = new ushort?[9,9]; for (var i = 0; i < 9; ++i) { for (var j = 0; j < 9; ++j) { if (board[i][j] != '.') { this.board[i, j] = (ushort) (1 << (board[i][j] - '0' - 1)); } } } if (SolveSudoku(0, 0)) { for (var i = 0; i < 9; ++i) { for (var j = 0; j < 9; ++j) { if (board[i][j] == '.') { board[i][j] = '0'; while (this.board[i, j].Value != 0) { board[i][j] = (char)(board[i][j] + 1); this.board[i, j] >>= 1; } } } } } } private ushort?[,] board; private bool ValidateHorizontalRule(int row) { ushort temp = 0; for (var i = 0; i < 9; ++i) { if (board[row, i].HasValue) { if ((temp | board[row, i].Value) == temp) { return false; } temp |= board[row, i].Value; } } return true; } private bool ValidateVerticalRule(int column) { ushort temp = 0; for (var i = 0; i < 9; ++i) { if (board[i, column].HasValue) { if ((temp | board[i, column].Value) == temp) { return false; } temp |= board[i, column].Value; } } return true; } private bool ValidateBlockRule(int row, int column) { var startRow = row / 3 * 3; var startColumn = column / 3 * 3; ushort temp = 0; for (var i = startRow; i < startRow + 3; ++i) { for (var j = startColumn; j < startColumn + 3; ++j) { if (board[i, j].HasValue) { if ((temp | board[i, j].Value) == temp) { return false; } temp |= board[i, j].Value; } } } return true; } private bool SolveSudoku(int i, int j) { while (true) { if (j == 9) { ++i; j = 0; } if (i == 9) { return true; } if (board[i, j].HasValue) { ++j; } else { break; } } ushort stop = 1 << 9; for (ushort t = 1; t != stop; t <<= 1) { board[i, j] = t; if (ValidateHorizontalRule(i) && ValidateVerticalRule(j) && ValidateBlockRule(i, j)) { if (SolveSudoku(i, j + 1)) { return true; } } } board[i, j] = null; return false; } }
37
Sudoku Solver
Hard
<p>Write a program to solve a Sudoku puzzle by filling the empty cells.</p> <p>A sudoku solution must satisfy <strong>all of the following rules</strong>:</p> <ol> <li>Each of the digits <code>1-9</code> must occur exactly once in each row.</li> <li>Each of the digits <code>1-9</code> must occur exactly once in each column.</li> <li>Each of the digits <code>1-9</code> must occur exactly once in each of the 9 <code>3x3</code> sub-boxes of the grid.</li> </ol> <p>The <code>&#39;.&#39;</code> character indicates empty cells.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0037.Sudoku%20Solver/images/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /> <pre> <strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;],[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;],[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> [[&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;1&quot;,&quot;2&quot;],[&quot;6&quot;,&quot;7&quot;,&quot;2&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;8&quot;],[&quot;1&quot;,&quot;9&quot;,&quot;8&quot;,&quot;3&quot;,&quot;4&quot;,&quot;2&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;],[&quot;8&quot;,&quot;5&quot;,&quot;9&quot;,&quot;7&quot;,&quot;6&quot;,&quot;1&quot;,&quot;4&quot;,&quot;2&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;2&quot;,&quot;6&quot;,&quot;8&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;9&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;1&quot;,&quot;3&quot;,&quot;9&quot;,&quot;2&quot;,&quot;4&quot;,&quot;8&quot;,&quot;5&quot;,&quot;6&quot;],[&quot;9&quot;,&quot;6&quot;,&quot;1&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;2&quot;,&quot;8&quot;,&quot;4&quot;],[&quot;2&quot;,&quot;8&quot;,&quot;7&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;6&quot;,&quot;3&quot;,&quot;5&quot;],[&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;2&quot;,&quot;8&quot;,&quot;6&quot;,&quot;1&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Explanation:</strong>&nbsp;The input board is shown above and the only valid solution is shown below: <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0037.Sudoku%20Solver/images/250px-Sudoku-by-L2G-20050714_solution.svg.png" style="height:250px; width:250px" /> </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>board.length == 9</code></li> <li><code>board[i].length == 9</code></li> <li><code>board[i][j]</code> is a digit or <code>&#39;.&#39;</code>.</li> <li>It is <strong>guaranteed</strong> that the input board has only one solution.</li> </ul>
Array; Hash Table; Backtracking; Matrix
Go
func solveSudoku(board [][]byte) { var row, col [9][9]bool var block [3][3][9]bool var t [][2]int ok := false for i := 0; i < 9; i++ { for j := 0; j < 9; j++ { if board[i][j] == '.' { t = append(t, [2]int{i, j}) } else { v := int(board[i][j] - '1') row[i][v], col[j][v], block[i/3][j/3][v] = true, true, true } } } var dfs func(int) dfs = func(k int) { if k == len(t) { ok = true return } i, j := t[k][0], t[k][1] for v := 0; v < 9; v++ { if !row[i][v] && !col[j][v] && !block[i/3][j/3][v] { row[i][v], col[j][v], block[i/3][j/3][v] = true, true, true board[i][j] = byte(v + '1') dfs(k + 1) row[i][v], col[j][v], block[i/3][j/3][v] = false, false, false } if ok { return } } } dfs(0) }
37
Sudoku Solver
Hard
<p>Write a program to solve a Sudoku puzzle by filling the empty cells.</p> <p>A sudoku solution must satisfy <strong>all of the following rules</strong>:</p> <ol> <li>Each of the digits <code>1-9</code> must occur exactly once in each row.</li> <li>Each of the digits <code>1-9</code> must occur exactly once in each column.</li> <li>Each of the digits <code>1-9</code> must occur exactly once in each of the 9 <code>3x3</code> sub-boxes of the grid.</li> </ol> <p>The <code>&#39;.&#39;</code> character indicates empty cells.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0037.Sudoku%20Solver/images/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /> <pre> <strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;],[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;],[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> [[&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;1&quot;,&quot;2&quot;],[&quot;6&quot;,&quot;7&quot;,&quot;2&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;8&quot;],[&quot;1&quot;,&quot;9&quot;,&quot;8&quot;,&quot;3&quot;,&quot;4&quot;,&quot;2&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;],[&quot;8&quot;,&quot;5&quot;,&quot;9&quot;,&quot;7&quot;,&quot;6&quot;,&quot;1&quot;,&quot;4&quot;,&quot;2&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;2&quot;,&quot;6&quot;,&quot;8&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;9&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;1&quot;,&quot;3&quot;,&quot;9&quot;,&quot;2&quot;,&quot;4&quot;,&quot;8&quot;,&quot;5&quot;,&quot;6&quot;],[&quot;9&quot;,&quot;6&quot;,&quot;1&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;2&quot;,&quot;8&quot;,&quot;4&quot;],[&quot;2&quot;,&quot;8&quot;,&quot;7&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;6&quot;,&quot;3&quot;,&quot;5&quot;],[&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;2&quot;,&quot;8&quot;,&quot;6&quot;,&quot;1&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Explanation:</strong>&nbsp;The input board is shown above and the only valid solution is shown below: <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0037.Sudoku%20Solver/images/250px-Sudoku-by-L2G-20050714_solution.svg.png" style="height:250px; width:250px" /> </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>board.length == 9</code></li> <li><code>board[i].length == 9</code></li> <li><code>board[i][j]</code> is a digit or <code>&#39;.&#39;</code>.</li> <li>It is <strong>guaranteed</strong> that the input board has only one solution.</li> </ul>
Array; Hash Table; Backtracking; Matrix
Java
class Solution { private boolean ok; private char[][] board; private List<Integer> t = new ArrayList<>(); private boolean[][] row = new boolean[9][9]; private boolean[][] col = new boolean[9][9]; private boolean[][][] block = new boolean[3][3][9]; public void solveSudoku(char[][] board) { this.board = board; for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { if (board[i][j] == '.') { t.add(i * 9 + j); } else { int v = board[i][j] - '1'; row[i][v] = col[j][v] = block[i / 3][j / 3][v] = true; } } } dfs(0); } private void dfs(int k) { if (k == t.size()) { ok = true; return; } int i = t.get(k) / 9, j = t.get(k) % 9; for (int v = 0; v < 9; ++v) { if (!row[i][v] && !col[j][v] && !block[i / 3][j / 3][v]) { row[i][v] = col[j][v] = block[i / 3][j / 3][v] = true; board[i][j] = (char) (v + '1'); dfs(k + 1); row[i][v] = col[j][v] = block[i / 3][j / 3][v] = false; } if (ok) { return; } } } }
37
Sudoku Solver
Hard
<p>Write a program to solve a Sudoku puzzle by filling the empty cells.</p> <p>A sudoku solution must satisfy <strong>all of the following rules</strong>:</p> <ol> <li>Each of the digits <code>1-9</code> must occur exactly once in each row.</li> <li>Each of the digits <code>1-9</code> must occur exactly once in each column.</li> <li>Each of the digits <code>1-9</code> must occur exactly once in each of the 9 <code>3x3</code> sub-boxes of the grid.</li> </ol> <p>The <code>&#39;.&#39;</code> character indicates empty cells.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0037.Sudoku%20Solver/images/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /> <pre> <strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;],[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;],[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> [[&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;1&quot;,&quot;2&quot;],[&quot;6&quot;,&quot;7&quot;,&quot;2&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;8&quot;],[&quot;1&quot;,&quot;9&quot;,&quot;8&quot;,&quot;3&quot;,&quot;4&quot;,&quot;2&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;],[&quot;8&quot;,&quot;5&quot;,&quot;9&quot;,&quot;7&quot;,&quot;6&quot;,&quot;1&quot;,&quot;4&quot;,&quot;2&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;2&quot;,&quot;6&quot;,&quot;8&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;9&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;1&quot;,&quot;3&quot;,&quot;9&quot;,&quot;2&quot;,&quot;4&quot;,&quot;8&quot;,&quot;5&quot;,&quot;6&quot;],[&quot;9&quot;,&quot;6&quot;,&quot;1&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;2&quot;,&quot;8&quot;,&quot;4&quot;],[&quot;2&quot;,&quot;8&quot;,&quot;7&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;6&quot;,&quot;3&quot;,&quot;5&quot;],[&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;2&quot;,&quot;8&quot;,&quot;6&quot;,&quot;1&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Explanation:</strong>&nbsp;The input board is shown above and the only valid solution is shown below: <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0037.Sudoku%20Solver/images/250px-Sudoku-by-L2G-20050714_solution.svg.png" style="height:250px; width:250px" /> </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>board.length == 9</code></li> <li><code>board[i].length == 9</code></li> <li><code>board[i][j]</code> is a digit or <code>&#39;.&#39;</code>.</li> <li>It is <strong>guaranteed</strong> that the input board has only one solution.</li> </ul>
Array; Hash Table; Backtracking; Matrix
PHP
class Solution { /** * @param string[][] $board * @return bool */ public function solveSudoku(&$board) { if (isSolved($board)) { return true; } $emptyCell = findEmptyCell($board); $row = $emptyCell[0]; $col = $emptyCell[1]; for ($num = 1; $num <= 9; $num++) { if (isValid($board, $row, $col, $num)) { $board[$row][$col] = (string) $num; if ($this->solveSudoku($board)) { return true; } $board[$row][$col] = '.'; } } return false; } } function isSolved($board) { foreach ($board as $row) { if (in_array('.', $row)) { return false; } } return true; } function findEmptyCell($board) { for ($row = 0; $row < 9; $row++) { for ($col = 0; $col < 9; $col++) { if ($board[$row][$col] === '.') { return [$row, $col]; } } } return null; } function isValid($board, $row, $col, $num) { for ($i = 0; $i < 9; $i++) { if ($board[$row][$i] == $num) { return false; } } for ($i = 0; $i < 9; $i++) { if ($board[$i][$col] == $num) { return false; } } $startRow = floor($row / 3) * 3; $endCol = floor($col / 3) * 3; for ($i = 0; $i < 3; $i++) { for ($j = 0; $j < 3; $j++) { if ($board[$startRow + $i][$endCol + $j] == $num) { return false; } } } return true; }
37
Sudoku Solver
Hard
<p>Write a program to solve a Sudoku puzzle by filling the empty cells.</p> <p>A sudoku solution must satisfy <strong>all of the following rules</strong>:</p> <ol> <li>Each of the digits <code>1-9</code> must occur exactly once in each row.</li> <li>Each of the digits <code>1-9</code> must occur exactly once in each column.</li> <li>Each of the digits <code>1-9</code> must occur exactly once in each of the 9 <code>3x3</code> sub-boxes of the grid.</li> </ol> <p>The <code>&#39;.&#39;</code> character indicates empty cells.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0037.Sudoku%20Solver/images/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /> <pre> <strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;],[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;],[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Output:</strong> [[&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;1&quot;,&quot;2&quot;],[&quot;6&quot;,&quot;7&quot;,&quot;2&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;8&quot;],[&quot;1&quot;,&quot;9&quot;,&quot;8&quot;,&quot;3&quot;,&quot;4&quot;,&quot;2&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;],[&quot;8&quot;,&quot;5&quot;,&quot;9&quot;,&quot;7&quot;,&quot;6&quot;,&quot;1&quot;,&quot;4&quot;,&quot;2&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;2&quot;,&quot;6&quot;,&quot;8&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;9&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;1&quot;,&quot;3&quot;,&quot;9&quot;,&quot;2&quot;,&quot;4&quot;,&quot;8&quot;,&quot;5&quot;,&quot;6&quot;],[&quot;9&quot;,&quot;6&quot;,&quot;1&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;2&quot;,&quot;8&quot;,&quot;4&quot;],[&quot;2&quot;,&quot;8&quot;,&quot;7&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;6&quot;,&quot;3&quot;,&quot;5&quot;],[&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;2&quot;,&quot;8&quot;,&quot;6&quot;,&quot;1&quot;,&quot;7&quot;,&quot;9&quot;]] <strong>Explanation:</strong>&nbsp;The input board is shown above and the only valid solution is shown below: <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0037.Sudoku%20Solver/images/250px-Sudoku-by-L2G-20050714_solution.svg.png" style="height:250px; width:250px" /> </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>board.length == 9</code></li> <li><code>board[i].length == 9</code></li> <li><code>board[i][j]</code> is a digit or <code>&#39;.&#39;</code>.</li> <li>It is <strong>guaranteed</strong> that the input board has only one solution.</li> </ul>
Array; Hash Table; Backtracking; Matrix
Python
class Solution: def solveSudoku(self, board: List[List[str]]) -> None: def dfs(k): nonlocal ok if k == len(t): ok = True return i, j = t[k] for v in range(9): if row[i][v] == col[j][v] == block[i // 3][j // 3][v] == False: row[i][v] = col[j][v] = block[i // 3][j // 3][v] = True board[i][j] = str(v + 1) dfs(k + 1) row[i][v] = col[j][v] = block[i // 3][j // 3][v] = False if ok: return row = [[False] * 9 for _ in range(9)] col = [[False] * 9 for _ in range(9)] block = [[[False] * 9 for _ in range(3)] for _ in range(3)] t = [] ok = False for i in range(9): for j in range(9): if board[i][j] == '.': t.append((i, j)) else: v = int(board[i][j]) - 1 row[i][v] = col[j][v] = block[i // 3][j // 3][v] = True dfs(0)
38
Count and Say
Medium
<p>The <strong>count-and-say</strong> sequence is a sequence of digit strings defined by the recursive formula:</p> <ul> <li><code>countAndSay(1) = &quot;1&quot;</code></li> <li><code>countAndSay(n)</code> is the run-length encoding of <code>countAndSay(n - 1)</code>.</li> </ul> <p><a href="http://en.wikipedia.org/wiki/Run-length_encoding" target="_blank">Run-length encoding</a> (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string <code>&quot;3322251&quot;</code> we replace <code>&quot;33&quot;</code> with <code>&quot;23&quot;</code>, replace <code>&quot;222&quot;</code> with <code>&quot;32&quot;</code>, replace <code>&quot;5&quot;</code> with <code>&quot;15&quot;</code> and replace <code>&quot;1&quot;</code> with <code>&quot;11&quot;</code>. Thus the compressed string becomes <code>&quot;23321511&quot;</code>.</p> <p>Given a positive integer <code>n</code>, return <em>the </em><code>n<sup>th</sup></code><em> element of the <strong>count-and-say</strong> sequence</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">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1211&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> countAndSay(1) = &quot;1&quot; countAndSay(2) = RLE of &quot;1&quot; = &quot;11&quot; countAndSay(3) = RLE of &quot;11&quot; = &quot;21&quot; countAndSay(4) = RLE of &quot;21&quot; = &quot;1211&quot; </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>This is the base case.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 30</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it iteratively?
String
C++
class Solution { public: string countAndSay(int n) { string s = "1"; while (--n) { string t = ""; for (int i = 0; i < s.size();) { int j = i; while (j < s.size() && s[j] == s[i]) ++j; t += to_string(j - i); t += s[i]; i = j; } s = t; } return s; } };
38
Count and Say
Medium
<p>The <strong>count-and-say</strong> sequence is a sequence of digit strings defined by the recursive formula:</p> <ul> <li><code>countAndSay(1) = &quot;1&quot;</code></li> <li><code>countAndSay(n)</code> is the run-length encoding of <code>countAndSay(n - 1)</code>.</li> </ul> <p><a href="http://en.wikipedia.org/wiki/Run-length_encoding" target="_blank">Run-length encoding</a> (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string <code>&quot;3322251&quot;</code> we replace <code>&quot;33&quot;</code> with <code>&quot;23&quot;</code>, replace <code>&quot;222&quot;</code> with <code>&quot;32&quot;</code>, replace <code>&quot;5&quot;</code> with <code>&quot;15&quot;</code> and replace <code>&quot;1&quot;</code> with <code>&quot;11&quot;</code>. Thus the compressed string becomes <code>&quot;23321511&quot;</code>.</p> <p>Given a positive integer <code>n</code>, return <em>the </em><code>n<sup>th</sup></code><em> element of the <strong>count-and-say</strong> sequence</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">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1211&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> countAndSay(1) = &quot;1&quot; countAndSay(2) = RLE of &quot;1&quot; = &quot;11&quot; countAndSay(3) = RLE of &quot;11&quot; = &quot;21&quot; countAndSay(4) = RLE of &quot;21&quot; = &quot;1211&quot; </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>This is the base case.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 30</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it iteratively?
String
C#
using System.Text; public class Solution { public string CountAndSay(int n) { var s = "1"; while (n > 1) { var sb = new StringBuilder(); var lastChar = '1'; var count = 0; foreach (var ch in s) { if (count > 0 && lastChar == ch) { ++count; } else { if (count > 0) { sb.Append(count); sb.Append(lastChar); } lastChar = ch; count = 1; } } if (count > 0) { sb.Append(count); sb.Append(lastChar); } s = sb.ToString(); --n; } return s; } }
38
Count and Say
Medium
<p>The <strong>count-and-say</strong> sequence is a sequence of digit strings defined by the recursive formula:</p> <ul> <li><code>countAndSay(1) = &quot;1&quot;</code></li> <li><code>countAndSay(n)</code> is the run-length encoding of <code>countAndSay(n - 1)</code>.</li> </ul> <p><a href="http://en.wikipedia.org/wiki/Run-length_encoding" target="_blank">Run-length encoding</a> (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string <code>&quot;3322251&quot;</code> we replace <code>&quot;33&quot;</code> with <code>&quot;23&quot;</code>, replace <code>&quot;222&quot;</code> with <code>&quot;32&quot;</code>, replace <code>&quot;5&quot;</code> with <code>&quot;15&quot;</code> and replace <code>&quot;1&quot;</code> with <code>&quot;11&quot;</code>. Thus the compressed string becomes <code>&quot;23321511&quot;</code>.</p> <p>Given a positive integer <code>n</code>, return <em>the </em><code>n<sup>th</sup></code><em> element of the <strong>count-and-say</strong> sequence</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">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1211&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> countAndSay(1) = &quot;1&quot; countAndSay(2) = RLE of &quot;1&quot; = &quot;11&quot; countAndSay(3) = RLE of &quot;11&quot; = &quot;21&quot; countAndSay(4) = RLE of &quot;21&quot; = &quot;1211&quot; </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>This is the base case.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 30</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it iteratively?
String
Go
func countAndSay(n int) string { s := "1" for k := 0; k < n-1; k++ { t := &strings.Builder{} i := 0 for i < len(s) { j := i for j < len(s) && s[j] == s[i] { j++ } t.WriteString(strconv.Itoa(j - i)) t.WriteByte(s[i]) i = j } s = t.String() } return s }
38
Count and Say
Medium
<p>The <strong>count-and-say</strong> sequence is a sequence of digit strings defined by the recursive formula:</p> <ul> <li><code>countAndSay(1) = &quot;1&quot;</code></li> <li><code>countAndSay(n)</code> is the run-length encoding of <code>countAndSay(n - 1)</code>.</li> </ul> <p><a href="http://en.wikipedia.org/wiki/Run-length_encoding" target="_blank">Run-length encoding</a> (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string <code>&quot;3322251&quot;</code> we replace <code>&quot;33&quot;</code> with <code>&quot;23&quot;</code>, replace <code>&quot;222&quot;</code> with <code>&quot;32&quot;</code>, replace <code>&quot;5&quot;</code> with <code>&quot;15&quot;</code> and replace <code>&quot;1&quot;</code> with <code>&quot;11&quot;</code>. Thus the compressed string becomes <code>&quot;23321511&quot;</code>.</p> <p>Given a positive integer <code>n</code>, return <em>the </em><code>n<sup>th</sup></code><em> element of the <strong>count-and-say</strong> sequence</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">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1211&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> countAndSay(1) = &quot;1&quot; countAndSay(2) = RLE of &quot;1&quot; = &quot;11&quot; countAndSay(3) = RLE of &quot;11&quot; = &quot;21&quot; countAndSay(4) = RLE of &quot;21&quot; = &quot;1211&quot; </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>This is the base case.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 30</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it iteratively?
String
Java
class Solution { public String countAndSay(int n) { String s = "1"; while (--n > 0) { StringBuilder t = new StringBuilder(); for (int i = 0; i < s.length();) { int j = i; while (j < s.length() && s.charAt(j) == s.charAt(i)) { ++j; } t.append((j - i) + ""); t.append(s.charAt(i)); i = j; } s = t.toString(); } return s; } }
38
Count and Say
Medium
<p>The <strong>count-and-say</strong> sequence is a sequence of digit strings defined by the recursive formula:</p> <ul> <li><code>countAndSay(1) = &quot;1&quot;</code></li> <li><code>countAndSay(n)</code> is the run-length encoding of <code>countAndSay(n - 1)</code>.</li> </ul> <p><a href="http://en.wikipedia.org/wiki/Run-length_encoding" target="_blank">Run-length encoding</a> (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string <code>&quot;3322251&quot;</code> we replace <code>&quot;33&quot;</code> with <code>&quot;23&quot;</code>, replace <code>&quot;222&quot;</code> with <code>&quot;32&quot;</code>, replace <code>&quot;5&quot;</code> with <code>&quot;15&quot;</code> and replace <code>&quot;1&quot;</code> with <code>&quot;11&quot;</code>. Thus the compressed string becomes <code>&quot;23321511&quot;</code>.</p> <p>Given a positive integer <code>n</code>, return <em>the </em><code>n<sup>th</sup></code><em> element of the <strong>count-and-say</strong> sequence</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">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1211&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> countAndSay(1) = &quot;1&quot; countAndSay(2) = RLE of &quot;1&quot; = &quot;11&quot; countAndSay(3) = RLE of &quot;11&quot; = &quot;21&quot; countAndSay(4) = RLE of &quot;21&quot; = &quot;1211&quot; </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>This is the base case.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 30</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it iteratively?
String
JavaScript
const countAndSay = function (n) { let s = '1'; for (let i = 2; i <= n; i++) { let count = 1, str = '', len = s.length; for (let j = 0; j < len; j++) { if (j < len - 1 && s[j] === s[j + 1]) { count++; } else { str += `${count}${s[j]}`; count = 1; } } s = str; } return s; };
38
Count and Say
Medium
<p>The <strong>count-and-say</strong> sequence is a sequence of digit strings defined by the recursive formula:</p> <ul> <li><code>countAndSay(1) = &quot;1&quot;</code></li> <li><code>countAndSay(n)</code> is the run-length encoding of <code>countAndSay(n - 1)</code>.</li> </ul> <p><a href="http://en.wikipedia.org/wiki/Run-length_encoding" target="_blank">Run-length encoding</a> (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string <code>&quot;3322251&quot;</code> we replace <code>&quot;33&quot;</code> with <code>&quot;23&quot;</code>, replace <code>&quot;222&quot;</code> with <code>&quot;32&quot;</code>, replace <code>&quot;5&quot;</code> with <code>&quot;15&quot;</code> and replace <code>&quot;1&quot;</code> with <code>&quot;11&quot;</code>. Thus the compressed string becomes <code>&quot;23321511&quot;</code>.</p> <p>Given a positive integer <code>n</code>, return <em>the </em><code>n<sup>th</sup></code><em> element of the <strong>count-and-say</strong> sequence</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">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1211&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> countAndSay(1) = &quot;1&quot; countAndSay(2) = RLE of &quot;1&quot; = &quot;11&quot; countAndSay(3) = RLE of &quot;11&quot; = &quot;21&quot; countAndSay(4) = RLE of &quot;21&quot; = &quot;1211&quot; </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>This is the base case.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 30</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it iteratively?
String
PHP
class Solution { /** * @param integer $n * @return string */ function countAndSay($n) { if ($n <= 0) { return ""; } $result = "1"; for ($i = 2; $i <= $n; $i++) { $count = 1; $say = ""; for ($j = 1; $j < strlen($result); $j++) { if ($result[$j] == $result[$j - 1]) { $count++; } else { $say .= $count . $result[$j - 1]; $count = 1; } } $say .= $count . $result[strlen($result) - 1]; $result = $say; } return $result; } }
38
Count and Say
Medium
<p>The <strong>count-and-say</strong> sequence is a sequence of digit strings defined by the recursive formula:</p> <ul> <li><code>countAndSay(1) = &quot;1&quot;</code></li> <li><code>countAndSay(n)</code> is the run-length encoding of <code>countAndSay(n - 1)</code>.</li> </ul> <p><a href="http://en.wikipedia.org/wiki/Run-length_encoding" target="_blank">Run-length encoding</a> (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string <code>&quot;3322251&quot;</code> we replace <code>&quot;33&quot;</code> with <code>&quot;23&quot;</code>, replace <code>&quot;222&quot;</code> with <code>&quot;32&quot;</code>, replace <code>&quot;5&quot;</code> with <code>&quot;15&quot;</code> and replace <code>&quot;1&quot;</code> with <code>&quot;11&quot;</code>. Thus the compressed string becomes <code>&quot;23321511&quot;</code>.</p> <p>Given a positive integer <code>n</code>, return <em>the </em><code>n<sup>th</sup></code><em> element of the <strong>count-and-say</strong> sequence</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">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1211&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> countAndSay(1) = &quot;1&quot; countAndSay(2) = RLE of &quot;1&quot; = &quot;11&quot; countAndSay(3) = RLE of &quot;11&quot; = &quot;21&quot; countAndSay(4) = RLE of &quot;21&quot; = &quot;1211&quot; </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>This is the base case.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 30</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it iteratively?
String
Python
class Solution: def countAndSay(self, n: int) -> str: s = '1' for _ in range(n - 1): i = 0 t = [] while i < len(s): j = i while j < len(s) and s[j] == s[i]: j += 1 t.append(str(j - i)) t.append(str(s[i])) i = j s = ''.join(t) return s
38
Count and Say
Medium
<p>The <strong>count-and-say</strong> sequence is a sequence of digit strings defined by the recursive formula:</p> <ul> <li><code>countAndSay(1) = &quot;1&quot;</code></li> <li><code>countAndSay(n)</code> is the run-length encoding of <code>countAndSay(n - 1)</code>.</li> </ul> <p><a href="http://en.wikipedia.org/wiki/Run-length_encoding" target="_blank">Run-length encoding</a> (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string <code>&quot;3322251&quot;</code> we replace <code>&quot;33&quot;</code> with <code>&quot;23&quot;</code>, replace <code>&quot;222&quot;</code> with <code>&quot;32&quot;</code>, replace <code>&quot;5&quot;</code> with <code>&quot;15&quot;</code> and replace <code>&quot;1&quot;</code> with <code>&quot;11&quot;</code>. Thus the compressed string becomes <code>&quot;23321511&quot;</code>.</p> <p>Given a positive integer <code>n</code>, return <em>the </em><code>n<sup>th</sup></code><em> element of the <strong>count-and-say</strong> sequence</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">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1211&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> countAndSay(1) = &quot;1&quot; countAndSay(2) = RLE of &quot;1&quot; = &quot;11&quot; countAndSay(3) = RLE of &quot;11&quot; = &quot;21&quot; countAndSay(4) = RLE of &quot;21&quot; = &quot;1211&quot; </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>This is the base case.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 30</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it iteratively?
String
Rust
use std::iter::once; impl Solution { pub fn count_and_say(n: i32) -> String { (1..n) .fold(vec![1], |curr, _| { let mut next = vec![]; let mut slow = 0; for fast in 0..=curr.len() { if fast == curr.len() || curr[slow] != curr[fast] { next.extend(once((fast - slow) as u8).chain(once(curr[slow]))); slow = fast; } } next }) .into_iter() .map(|digit| (digit + b'0') as char) .collect() } }
38
Count and Say
Medium
<p>The <strong>count-and-say</strong> sequence is a sequence of digit strings defined by the recursive formula:</p> <ul> <li><code>countAndSay(1) = &quot;1&quot;</code></li> <li><code>countAndSay(n)</code> is the run-length encoding of <code>countAndSay(n - 1)</code>.</li> </ul> <p><a href="http://en.wikipedia.org/wiki/Run-length_encoding" target="_blank">Run-length encoding</a> (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string <code>&quot;3322251&quot;</code> we replace <code>&quot;33&quot;</code> with <code>&quot;23&quot;</code>, replace <code>&quot;222&quot;</code> with <code>&quot;32&quot;</code>, replace <code>&quot;5&quot;</code> with <code>&quot;15&quot;</code> and replace <code>&quot;1&quot;</code> with <code>&quot;11&quot;</code>. Thus the compressed string becomes <code>&quot;23321511&quot;</code>.</p> <p>Given a positive integer <code>n</code>, return <em>the </em><code>n<sup>th</sup></code><em> element of the <strong>count-and-say</strong> sequence</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">n = 4</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1211&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> countAndSay(1) = &quot;1&quot; countAndSay(2) = RLE of &quot;1&quot; = &quot;11&quot; countAndSay(3) = RLE of &quot;11&quot; = &quot;21&quot; countAndSay(4) = RLE of &quot;21&quot; = &quot;1211&quot; </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 1</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;1&quot;</span></p> <p><strong>Explanation:</strong></p> <p>This is the base case.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 30</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it iteratively?
String
TypeScript
function countAndSay(n: number): string { let s = '1'; for (let i = 1; i < n; i++) { let t = ''; let cur = s[0]; let count = 1; for (let j = 1; j < s.length; j++) { if (s[j] !== cur) { t += `${count}${cur}`; cur = s[j]; count = 0; } count++; } t += `${count}${cur}`; s = t; } return s; }
39
Combination Sum
Medium
<p>Given an array of <strong>distinct</strong> integers <code>candidates</code> and a target integer <code>target</code>, return <em>a list of all <strong>unique combinations</strong> of </em><code>candidates</code><em> where the chosen numbers sum to </em><code>target</code><em>.</em> You may return the combinations in <strong>any order</strong>.</p> <p>The <strong>same</strong> number may be chosen from <code>candidates</code> an <strong>unlimited number of times</strong>. Two combinations are unique if the <span data-keyword="frequency-array">frequency</span> of at least one of the chosen numbers is different.</p> <p>The test cases are generated such that the number of unique combinations that sum up to <code>target</code> is less than <code>150</code> combinations for the given input.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,6,7], target = 7 <strong>Output:</strong> [[2,2,3],[7]] <strong>Explanation:</strong> 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,5], target = 8 <strong>Output:</strong> [[2,2,2,2],[2,3,3],[3,5]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> candidates = [2], target = 1 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= candidates.length &lt;= 30</code></li> <li><code>2 &lt;= candidates[i] &lt;= 40</code></li> <li>All elements of <code>candidates</code> are <strong>distinct</strong>.</li> <li><code>1 &lt;= target &lt;= 40</code></li> </ul>
Array; Backtracking
C++
class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); vector<vector<int>> ans; vector<int> t; function<void(int, int)> dfs = [&](int i, int s) { if (s == 0) { ans.emplace_back(t); return; } if (s < candidates[i]) { return; } for (int j = i; j < candidates.size(); ++j) { t.push_back(candidates[j]); dfs(j, s - candidates[j]); t.pop_back(); } }; dfs(0, target); return ans; } };
39
Combination Sum
Medium
<p>Given an array of <strong>distinct</strong> integers <code>candidates</code> and a target integer <code>target</code>, return <em>a list of all <strong>unique combinations</strong> of </em><code>candidates</code><em> where the chosen numbers sum to </em><code>target</code><em>.</em> You may return the combinations in <strong>any order</strong>.</p> <p>The <strong>same</strong> number may be chosen from <code>candidates</code> an <strong>unlimited number of times</strong>. Two combinations are unique if the <span data-keyword="frequency-array">frequency</span> of at least one of the chosen numbers is different.</p> <p>The test cases are generated such that the number of unique combinations that sum up to <code>target</code> is less than <code>150</code> combinations for the given input.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,6,7], target = 7 <strong>Output:</strong> [[2,2,3],[7]] <strong>Explanation:</strong> 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,5], target = 8 <strong>Output:</strong> [[2,2,2,2],[2,3,3],[3,5]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> candidates = [2], target = 1 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= candidates.length &lt;= 30</code></li> <li><code>2 &lt;= candidates[i] &lt;= 40</code></li> <li>All elements of <code>candidates</code> are <strong>distinct</strong>.</li> <li><code>1 &lt;= target &lt;= 40</code></li> </ul>
Array; Backtracking
C#
public class Solution { private List<IList<int>> ans = new List<IList<int>>(); private List<int> t = new List<int>(); private int[] candidates; public IList<IList<int>> CombinationSum(int[] candidates, int target) { Array.Sort(candidates); this.candidates = candidates; dfs(0, target); return ans; } private void dfs(int i, int s) { if (s == 0) { ans.Add(new List<int>(t)); return; } if (s < candidates[i]) { return; } for (int j = i; j < candidates.Length; ++j) { t.Add(candidates[j]); dfs(j, s - candidates[j]); t.RemoveAt(t.Count - 1); } } }
39
Combination Sum
Medium
<p>Given an array of <strong>distinct</strong> integers <code>candidates</code> and a target integer <code>target</code>, return <em>a list of all <strong>unique combinations</strong> of </em><code>candidates</code><em> where the chosen numbers sum to </em><code>target</code><em>.</em> You may return the combinations in <strong>any order</strong>.</p> <p>The <strong>same</strong> number may be chosen from <code>candidates</code> an <strong>unlimited number of times</strong>. Two combinations are unique if the <span data-keyword="frequency-array">frequency</span> of at least one of the chosen numbers is different.</p> <p>The test cases are generated such that the number of unique combinations that sum up to <code>target</code> is less than <code>150</code> combinations for the given input.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,6,7], target = 7 <strong>Output:</strong> [[2,2,3],[7]] <strong>Explanation:</strong> 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,5], target = 8 <strong>Output:</strong> [[2,2,2,2],[2,3,3],[3,5]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> candidates = [2], target = 1 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= candidates.length &lt;= 30</code></li> <li><code>2 &lt;= candidates[i] &lt;= 40</code></li> <li>All elements of <code>candidates</code> are <strong>distinct</strong>.</li> <li><code>1 &lt;= target &lt;= 40</code></li> </ul>
Array; Backtracking
Go
func combinationSum(candidates []int, target int) (ans [][]int) { sort.Ints(candidates) t := []int{} var dfs func(i, s int) dfs = func(i, s int) { if s == 0 { ans = append(ans, slices.Clone(t)) return } if s < candidates[i] { return } for j := i; j < len(candidates); j++ { t = append(t, candidates[j]) dfs(j, s-candidates[j]) t = t[:len(t)-1] } } dfs(0, target) return }
39
Combination Sum
Medium
<p>Given an array of <strong>distinct</strong> integers <code>candidates</code> and a target integer <code>target</code>, return <em>a list of all <strong>unique combinations</strong> of </em><code>candidates</code><em> where the chosen numbers sum to </em><code>target</code><em>.</em> You may return the combinations in <strong>any order</strong>.</p> <p>The <strong>same</strong> number may be chosen from <code>candidates</code> an <strong>unlimited number of times</strong>. Two combinations are unique if the <span data-keyword="frequency-array">frequency</span> of at least one of the chosen numbers is different.</p> <p>The test cases are generated such that the number of unique combinations that sum up to <code>target</code> is less than <code>150</code> combinations for the given input.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,6,7], target = 7 <strong>Output:</strong> [[2,2,3],[7]] <strong>Explanation:</strong> 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,5], target = 8 <strong>Output:</strong> [[2,2,2,2],[2,3,3],[3,5]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> candidates = [2], target = 1 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= candidates.length &lt;= 30</code></li> <li><code>2 &lt;= candidates[i] &lt;= 40</code></li> <li>All elements of <code>candidates</code> are <strong>distinct</strong>.</li> <li><code>1 &lt;= target &lt;= 40</code></li> </ul>
Array; Backtracking
Java
class Solution { private List<List<Integer>> ans = new ArrayList<>(); private List<Integer> t = new ArrayList<>(); private int[] candidates; public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); this.candidates = candidates; dfs(0, target); return ans; } private void dfs(int i, int s) { if (s == 0) { ans.add(new ArrayList(t)); return; } if (s < candidates[i]) { return; } for (int j = i; j < candidates.length; ++j) { t.add(candidates[j]); dfs(j, s - candidates[j]); t.remove(t.size() - 1); } } }
39
Combination Sum
Medium
<p>Given an array of <strong>distinct</strong> integers <code>candidates</code> and a target integer <code>target</code>, return <em>a list of all <strong>unique combinations</strong> of </em><code>candidates</code><em> where the chosen numbers sum to </em><code>target</code><em>.</em> You may return the combinations in <strong>any order</strong>.</p> <p>The <strong>same</strong> number may be chosen from <code>candidates</code> an <strong>unlimited number of times</strong>. Two combinations are unique if the <span data-keyword="frequency-array">frequency</span> of at least one of the chosen numbers is different.</p> <p>The test cases are generated such that the number of unique combinations that sum up to <code>target</code> is less than <code>150</code> combinations for the given input.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,6,7], target = 7 <strong>Output:</strong> [[2,2,3],[7]] <strong>Explanation:</strong> 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,5], target = 8 <strong>Output:</strong> [[2,2,2,2],[2,3,3],[3,5]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> candidates = [2], target = 1 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= candidates.length &lt;= 30</code></li> <li><code>2 &lt;= candidates[i] &lt;= 40</code></li> <li>All elements of <code>candidates</code> are <strong>distinct</strong>.</li> <li><code>1 &lt;= target &lt;= 40</code></li> </ul>
Array; Backtracking
PHP
class Solution { /** * @param integer[] $candidates * @param integer $target * @return integer[][] */ function combinationSum($candidates, $target) { $result = []; $currentCombination = []; $startIndex = 0; sort($candidates); $this->findCombinations($candidates, $target, $startIndex, $currentCombination, $result); return $result; } function findCombinations($candidates, $target, $startIndex, $currentCombination, &$result) { if ($target === 0) { $result[] = $currentCombination; return; } for ($i = $startIndex; $i < count($candidates); $i++) { $num = $candidates[$i]; if ($num > $target) { break; } $currentCombination[] = $num; $this->findCombinations($candidates, $target - $num, $i, $currentCombination, $result); array_pop($currentCombination); } } }
39
Combination Sum
Medium
<p>Given an array of <strong>distinct</strong> integers <code>candidates</code> and a target integer <code>target</code>, return <em>a list of all <strong>unique combinations</strong> of </em><code>candidates</code><em> where the chosen numbers sum to </em><code>target</code><em>.</em> You may return the combinations in <strong>any order</strong>.</p> <p>The <strong>same</strong> number may be chosen from <code>candidates</code> an <strong>unlimited number of times</strong>. Two combinations are unique if the <span data-keyword="frequency-array">frequency</span> of at least one of the chosen numbers is different.</p> <p>The test cases are generated such that the number of unique combinations that sum up to <code>target</code> is less than <code>150</code> combinations for the given input.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,6,7], target = 7 <strong>Output:</strong> [[2,2,3],[7]] <strong>Explanation:</strong> 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,5], target = 8 <strong>Output:</strong> [[2,2,2,2],[2,3,3],[3,5]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> candidates = [2], target = 1 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= candidates.length &lt;= 30</code></li> <li><code>2 &lt;= candidates[i] &lt;= 40</code></li> <li>All elements of <code>candidates</code> are <strong>distinct</strong>.</li> <li><code>1 &lt;= target &lt;= 40</code></li> </ul>
Array; Backtracking
Python
class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: def dfs(i: int, s: int): if s == 0: ans.append(t[:]) return if s < candidates[i]: return for j in range(i, len(candidates)): t.append(candidates[j]) dfs(j, s - candidates[j]) t.pop() candidates.sort() t = [] ans = [] dfs(0, target) return ans
39
Combination Sum
Medium
<p>Given an array of <strong>distinct</strong> integers <code>candidates</code> and a target integer <code>target</code>, return <em>a list of all <strong>unique combinations</strong> of </em><code>candidates</code><em> where the chosen numbers sum to </em><code>target</code><em>.</em> You may return the combinations in <strong>any order</strong>.</p> <p>The <strong>same</strong> number may be chosen from <code>candidates</code> an <strong>unlimited number of times</strong>. Two combinations are unique if the <span data-keyword="frequency-array">frequency</span> of at least one of the chosen numbers is different.</p> <p>The test cases are generated such that the number of unique combinations that sum up to <code>target</code> is less than <code>150</code> combinations for the given input.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,6,7], target = 7 <strong>Output:</strong> [[2,2,3],[7]] <strong>Explanation:</strong> 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,5], target = 8 <strong>Output:</strong> [[2,2,2,2],[2,3,3],[3,5]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> candidates = [2], target = 1 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= candidates.length &lt;= 30</code></li> <li><code>2 &lt;= candidates[i] &lt;= 40</code></li> <li>All elements of <code>candidates</code> are <strong>distinct</strong>.</li> <li><code>1 &lt;= target &lt;= 40</code></li> </ul>
Array; Backtracking
Rust
impl Solution { fn dfs(i: usize, s: i32, candidates: &Vec<i32>, t: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) { if s == 0 { ans.push(t.clone()); return; } if s < candidates[i] { return; } for j in i..candidates.len() { t.push(candidates[j]); Self::dfs(j, s - candidates[j], candidates, t, ans); t.pop(); } } pub fn combination_sum(mut candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> { candidates.sort(); let mut ans = Vec::new(); Self::dfs(0, target, &candidates, &mut vec![], &mut ans); ans } }
39
Combination Sum
Medium
<p>Given an array of <strong>distinct</strong> integers <code>candidates</code> and a target integer <code>target</code>, return <em>a list of all <strong>unique combinations</strong> of </em><code>candidates</code><em> where the chosen numbers sum to </em><code>target</code><em>.</em> You may return the combinations in <strong>any order</strong>.</p> <p>The <strong>same</strong> number may be chosen from <code>candidates</code> an <strong>unlimited number of times</strong>. Two combinations are unique if the <span data-keyword="frequency-array">frequency</span> of at least one of the chosen numbers is different.</p> <p>The test cases are generated such that the number of unique combinations that sum up to <code>target</code> is less than <code>150</code> combinations for the given input.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,6,7], target = 7 <strong>Output:</strong> [[2,2,3],[7]] <strong>Explanation:</strong> 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,3,5], target = 8 <strong>Output:</strong> [[2,2,2,2],[2,3,3],[3,5]] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> candidates = [2], target = 1 <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= candidates.length &lt;= 30</code></li> <li><code>2 &lt;= candidates[i] &lt;= 40</code></li> <li>All elements of <code>candidates</code> are <strong>distinct</strong>.</li> <li><code>1 &lt;= target &lt;= 40</code></li> </ul>
Array; Backtracking
TypeScript
function combinationSum(candidates: number[], target: number): number[][] { candidates.sort((a, b) => a - b); const ans: number[][] = []; const t: number[] = []; const dfs = (i: number, s: number) => { if (s === 0) { ans.push(t.slice()); return; } if (s < candidates[i]) { return; } for (let j = i; j < candidates.length; ++j) { t.push(candidates[j]); dfs(j, s - candidates[j]); t.pop(); } }; dfs(0, target); return ans; }
40
Combination Sum II
Medium
<p>Given a collection of candidate numbers (<code>candidates</code>) and a target number (<code>target</code>), find all unique combinations in <code>candidates</code>&nbsp;where the candidate numbers sum to <code>target</code>.</p> <p>Each number in <code>candidates</code>&nbsp;may only be used <strong>once</strong> in the combination.</p> <p><strong>Note:</strong>&nbsp;The solution set must not contain duplicate combinations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [10,1,2,7,6,1,5], target = 8 <strong>Output:</strong> [ [1,1,6], [1,2,5], [1,7], [2,6] ] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,5,2,1,2], target = 5 <strong>Output:</strong> [ [1,2,2], [5] ] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;candidates.length &lt;= 100</code></li> <li><code>1 &lt;=&nbsp;candidates[i] &lt;= 50</code></li> <li><code>1 &lt;= target &lt;= 30</code></li> </ul>
Array; Backtracking
C++
class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); vector<vector<int>> ans; vector<int> t; function<void(int, int)> dfs = [&](int i, int s) { if (s == 0) { ans.emplace_back(t); return; } if (i >= candidates.size() || s < candidates[i]) { return; } for (int j = i; j < candidates.size(); ++j) { if (j > i && candidates[j] == candidates[j - 1]) { continue; } t.emplace_back(candidates[j]); dfs(j + 1, s - candidates[j]); t.pop_back(); } }; dfs(0, target); return ans; } };
40
Combination Sum II
Medium
<p>Given a collection of candidate numbers (<code>candidates</code>) and a target number (<code>target</code>), find all unique combinations in <code>candidates</code>&nbsp;where the candidate numbers sum to <code>target</code>.</p> <p>Each number in <code>candidates</code>&nbsp;may only be used <strong>once</strong> in the combination.</p> <p><strong>Note:</strong>&nbsp;The solution set must not contain duplicate combinations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [10,1,2,7,6,1,5], target = 8 <strong>Output:</strong> [ [1,1,6], [1,2,5], [1,7], [2,6] ] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,5,2,1,2], target = 5 <strong>Output:</strong> [ [1,2,2], [5] ] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;candidates.length &lt;= 100</code></li> <li><code>1 &lt;=&nbsp;candidates[i] &lt;= 50</code></li> <li><code>1 &lt;= target &lt;= 30</code></li> </ul>
Array; Backtracking
C#
public class Solution { private List<IList<int>> ans = new List<IList<int>>(); private List<int> t = new List<int>(); private int[] candidates; public IList<IList<int>> CombinationSum2(int[] candidates, int target) { Array.Sort(candidates); this.candidates = candidates; dfs(0, target); return ans; } private void dfs(int i, int s) { if (s == 0) { ans.Add(new List<int>(t)); return; } if (i >= candidates.Length || s < candidates[i]) { return; } for (int j = i; j < candidates.Length; ++j) { if (j > i && candidates[j] == candidates[j - 1]) { continue; } t.Add(candidates[j]); dfs(j + 1, s - candidates[j]); t.RemoveAt(t.Count - 1); } } }
40
Combination Sum II
Medium
<p>Given a collection of candidate numbers (<code>candidates</code>) and a target number (<code>target</code>), find all unique combinations in <code>candidates</code>&nbsp;where the candidate numbers sum to <code>target</code>.</p> <p>Each number in <code>candidates</code>&nbsp;may only be used <strong>once</strong> in the combination.</p> <p><strong>Note:</strong>&nbsp;The solution set must not contain duplicate combinations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [10,1,2,7,6,1,5], target = 8 <strong>Output:</strong> [ [1,1,6], [1,2,5], [1,7], [2,6] ] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,5,2,1,2], target = 5 <strong>Output:</strong> [ [1,2,2], [5] ] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;candidates.length &lt;= 100</code></li> <li><code>1 &lt;=&nbsp;candidates[i] &lt;= 50</code></li> <li><code>1 &lt;= target &lt;= 30</code></li> </ul>
Array; Backtracking
Go
func combinationSum2(candidates []int, target int) (ans [][]int) { sort.Ints(candidates) t := []int{} var dfs func(i, s int) dfs = func(i, s int) { if s == 0 { ans = append(ans, slices.Clone(t)) return } if i >= len(candidates) || s < candidates[i] { return } for j := i; j < len(candidates); j++ { if j > i && candidates[j] == candidates[j-1] { continue } t = append(t, candidates[j]) dfs(j+1, s-candidates[j]) t = t[:len(t)-1] } } dfs(0, target) return }
40
Combination Sum II
Medium
<p>Given a collection of candidate numbers (<code>candidates</code>) and a target number (<code>target</code>), find all unique combinations in <code>candidates</code>&nbsp;where the candidate numbers sum to <code>target</code>.</p> <p>Each number in <code>candidates</code>&nbsp;may only be used <strong>once</strong> in the combination.</p> <p><strong>Note:</strong>&nbsp;The solution set must not contain duplicate combinations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [10,1,2,7,6,1,5], target = 8 <strong>Output:</strong> [ [1,1,6], [1,2,5], [1,7], [2,6] ] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,5,2,1,2], target = 5 <strong>Output:</strong> [ [1,2,2], [5] ] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;candidates.length &lt;= 100</code></li> <li><code>1 &lt;=&nbsp;candidates[i] &lt;= 50</code></li> <li><code>1 &lt;= target &lt;= 30</code></li> </ul>
Array; Backtracking
Java
class Solution { private List<List<Integer>> ans = new ArrayList<>(); private List<Integer> t = new ArrayList<>(); private int[] candidates; public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); this.candidates = candidates; dfs(0, target); return ans; } private void dfs(int i, int s) { if (s == 0) { ans.add(new ArrayList<>(t)); return; } if (i >= candidates.length || s < candidates[i]) { return; } for (int j = i; j < candidates.length; ++j) { if (j > i && candidates[j] == candidates[j - 1]) { continue; } t.add(candidates[j]); dfs(j + 1, s - candidates[j]); t.remove(t.size() - 1); } } }
40
Combination Sum II
Medium
<p>Given a collection of candidate numbers (<code>candidates</code>) and a target number (<code>target</code>), find all unique combinations in <code>candidates</code>&nbsp;where the candidate numbers sum to <code>target</code>.</p> <p>Each number in <code>candidates</code>&nbsp;may only be used <strong>once</strong> in the combination.</p> <p><strong>Note:</strong>&nbsp;The solution set must not contain duplicate combinations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [10,1,2,7,6,1,5], target = 8 <strong>Output:</strong> [ [1,1,6], [1,2,5], [1,7], [2,6] ] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,5,2,1,2], target = 5 <strong>Output:</strong> [ [1,2,2], [5] ] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;candidates.length &lt;= 100</code></li> <li><code>1 &lt;=&nbsp;candidates[i] &lt;= 50</code></li> <li><code>1 &lt;= target &lt;= 30</code></li> </ul>
Array; Backtracking
JavaScript
/** * @param {number[]} candidates * @param {number} target * @return {number[][]} */ var combinationSum2 = function (candidates, target) { candidates.sort((a, b) => a - b); const ans = []; const t = []; const dfs = (i, s) => { if (s === 0) { ans.push(t.slice()); return; } if (i >= candidates.length || s < candidates[i]) { return; } for (let j = i; j < candidates.length; ++j) { if (j > i && candidates[j] === candidates[j - 1]) { continue; } t.push(candidates[j]); dfs(j + 1, s - candidates[j]); t.pop(); } }; dfs(0, target); return ans; };
40
Combination Sum II
Medium
<p>Given a collection of candidate numbers (<code>candidates</code>) and a target number (<code>target</code>), find all unique combinations in <code>candidates</code>&nbsp;where the candidate numbers sum to <code>target</code>.</p> <p>Each number in <code>candidates</code>&nbsp;may only be used <strong>once</strong> in the combination.</p> <p><strong>Note:</strong>&nbsp;The solution set must not contain duplicate combinations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [10,1,2,7,6,1,5], target = 8 <strong>Output:</strong> [ [1,1,6], [1,2,5], [1,7], [2,6] ] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,5,2,1,2], target = 5 <strong>Output:</strong> [ [1,2,2], [5] ] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;candidates.length &lt;= 100</code></li> <li><code>1 &lt;=&nbsp;candidates[i] &lt;= 50</code></li> <li><code>1 &lt;= target &lt;= 30</code></li> </ul>
Array; Backtracking
PHP
class Solution { /** * @param integer[] $candidates * @param integer $target * @return integer[][] */ function combinationSum2($candidates, $target) { $result = []; $currentCombination = []; $startIndex = 0; sort($candidates); $this->findCombinations($candidates, $target, $startIndex, $currentCombination, $result); return $result; } function findCombinations($candidates, $target, $startIndex, $currentCombination, &$result) { if ($target === 0) { $result[] = $currentCombination; return; } for ($i = $startIndex; $i < count($candidates); $i++) { $num = $candidates[$i]; if ($num > $target) { break; } if ($i > $startIndex && $candidates[$i] === $candidates[$i - 1]) { continue; } $currentCombination[] = $num; $this->findCombinations($candidates, $target - $num, $i + 1, $currentCombination, $result); array_pop($currentCombination); } } }
40
Combination Sum II
Medium
<p>Given a collection of candidate numbers (<code>candidates</code>) and a target number (<code>target</code>), find all unique combinations in <code>candidates</code>&nbsp;where the candidate numbers sum to <code>target</code>.</p> <p>Each number in <code>candidates</code>&nbsp;may only be used <strong>once</strong> in the combination.</p> <p><strong>Note:</strong>&nbsp;The solution set must not contain duplicate combinations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [10,1,2,7,6,1,5], target = 8 <strong>Output:</strong> [ [1,1,6], [1,2,5], [1,7], [2,6] ] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,5,2,1,2], target = 5 <strong>Output:</strong> [ [1,2,2], [5] ] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;candidates.length &lt;= 100</code></li> <li><code>1 &lt;=&nbsp;candidates[i] &lt;= 50</code></li> <li><code>1 &lt;= target &lt;= 30</code></li> </ul>
Array; Backtracking
Python
class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: def dfs(i: int, s: int): if s == 0: ans.append(t[:]) return if i >= len(candidates) or s < candidates[i]: return for j in range(i, len(candidates)): if j > i and candidates[j] == candidates[j - 1]: continue t.append(candidates[j]) dfs(j + 1, s - candidates[j]) t.pop() candidates.sort() ans = [] t = [] dfs(0, target) return ans
40
Combination Sum II
Medium
<p>Given a collection of candidate numbers (<code>candidates</code>) and a target number (<code>target</code>), find all unique combinations in <code>candidates</code>&nbsp;where the candidate numbers sum to <code>target</code>.</p> <p>Each number in <code>candidates</code>&nbsp;may only be used <strong>once</strong> in the combination.</p> <p><strong>Note:</strong>&nbsp;The solution set must not contain duplicate combinations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [10,1,2,7,6,1,5], target = 8 <strong>Output:</strong> [ [1,1,6], [1,2,5], [1,7], [2,6] ] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,5,2,1,2], target = 5 <strong>Output:</strong> [ [1,2,2], [5] ] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;candidates.length &lt;= 100</code></li> <li><code>1 &lt;=&nbsp;candidates[i] &lt;= 50</code></li> <li><code>1 &lt;= target &lt;= 30</code></li> </ul>
Array; Backtracking
Rust
impl Solution { fn dfs(i: usize, s: i32, candidates: &Vec<i32>, t: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) { if s == 0 { ans.push(t.clone()); return; } if i >= candidates.len() || s < candidates[i] { return; } for j in i..candidates.len() { if j > i && candidates[j] == candidates[j - 1] { continue; } t.push(candidates[j]); Self::dfs(j + 1, s - candidates[j], candidates, t, ans); t.pop(); } } pub fn combination_sum2(mut candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> { candidates.sort(); let mut ans = Vec::new(); Self::dfs(0, target, &candidates, &mut vec![], &mut ans); ans } }
40
Combination Sum II
Medium
<p>Given a collection of candidate numbers (<code>candidates</code>) and a target number (<code>target</code>), find all unique combinations in <code>candidates</code>&nbsp;where the candidate numbers sum to <code>target</code>.</p> <p>Each number in <code>candidates</code>&nbsp;may only be used <strong>once</strong> in the combination.</p> <p><strong>Note:</strong>&nbsp;The solution set must not contain duplicate combinations.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> candidates = [10,1,2,7,6,1,5], target = 8 <strong>Output:</strong> [ [1,1,6], [1,2,5], [1,7], [2,6] ] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> candidates = [2,5,2,1,2], target = 5 <strong>Output:</strong> [ [1,2,2], [5] ] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;=&nbsp;candidates.length &lt;= 100</code></li> <li><code>1 &lt;=&nbsp;candidates[i] &lt;= 50</code></li> <li><code>1 &lt;= target &lt;= 30</code></li> </ul>
Array; Backtracking
TypeScript
function combinationSum2(candidates: number[], target: number): number[][] { candidates.sort((a, b) => a - b); const ans: number[][] = []; const t: number[] = []; const dfs = (i: number, s: number) => { if (s === 0) { ans.push(t.slice()); return; } if (i >= candidates.length || s < candidates[i]) { return; } for (let j = i; j < candidates.length; j++) { if (j > i && candidates[j] === candidates[j - 1]) { continue; } t.push(candidates[j]); dfs(j + 1, s - candidates[j]); t.pop(); } }; dfs(0, target); return ans; }
41
First Missing Positive
Hard
<p>Given an unsorted integer array <code>nums</code>. Return the <em>smallest positive integer</em> that is <em>not present</em> in <code>nums</code>.</p> <p>You must implement an algorithm that runs in <code>O(n)</code> time and uses <code>O(1)</code> auxiliary space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,0] <strong>Output:</strong> 3 <strong>Explanation:</strong> The numbers in the range [1,2] are all in the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1 is in the array but 2 is missing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,8,9,11,12] <strong>Output:</strong> 1 <strong>Explanation:</strong> The smallest positive integer 1 is missing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
C
int firstMissingPositive(int* nums, int numsSize) { for (int i = 0; i < numsSize; ++i) { while (nums[i] > 0 && nums[i] <= numsSize && nums[i] != nums[nums[i] - 1]) { int j = nums[i] - 1; int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } } for (int i = 0; i < numsSize; ++i) { if (nums[i] != i + 1) { return i + 1; } } return numsSize + 1; }
41
First Missing Positive
Hard
<p>Given an unsorted integer array <code>nums</code>. Return the <em>smallest positive integer</em> that is <em>not present</em> in <code>nums</code>.</p> <p>You must implement an algorithm that runs in <code>O(n)</code> time and uses <code>O(1)</code> auxiliary space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,0] <strong>Output:</strong> 3 <strong>Explanation:</strong> The numbers in the range [1,2] are all in the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1 is in the array but 2 is missing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,8,9,11,12] <strong>Output:</strong> 1 <strong>Explanation:</strong> The smallest positive integer 1 is missing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
C++
class Solution { public: int firstMissingPositive(vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; ++i) { while (nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i] - 1]) { swap(nums[i], nums[nums[i] - 1]); } } for (int i = 0; i < n; ++i) { if (nums[i] != i + 1) { return i + 1; } } return n + 1; } };
41
First Missing Positive
Hard
<p>Given an unsorted integer array <code>nums</code>. Return the <em>smallest positive integer</em> that is <em>not present</em> in <code>nums</code>.</p> <p>You must implement an algorithm that runs in <code>O(n)</code> time and uses <code>O(1)</code> auxiliary space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,0] <strong>Output:</strong> 3 <strong>Explanation:</strong> The numbers in the range [1,2] are all in the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1 is in the array but 2 is missing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,8,9,11,12] <strong>Output:</strong> 1 <strong>Explanation:</strong> The smallest positive integer 1 is missing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
C#
public class Solution { public int FirstMissingPositive(int[] nums) { int n = nums.Length; for (int i = 0; i < n; ++i) { while (nums[i] >= 1 && nums[i] <= n && nums[i] != nums[nums[i] - 1]) { Swap(nums, i, nums[i] - 1); } } for (int i = 0; i < n; ++i) { if (i + 1 != nums[i]) { return i + 1; } } return n + 1; } private void Swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } }
41
First Missing Positive
Hard
<p>Given an unsorted integer array <code>nums</code>. Return the <em>smallest positive integer</em> that is <em>not present</em> in <code>nums</code>.</p> <p>You must implement an algorithm that runs in <code>O(n)</code> time and uses <code>O(1)</code> auxiliary space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,0] <strong>Output:</strong> 3 <strong>Explanation:</strong> The numbers in the range [1,2] are all in the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1 is in the array but 2 is missing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,8,9,11,12] <strong>Output:</strong> 1 <strong>Explanation:</strong> The smallest positive integer 1 is missing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
Go
func firstMissingPositive(nums []int) int { n := len(nums) for i := range nums { for 0 < nums[i] && nums[i] <= n && nums[i] != nums[nums[i]-1] { nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i] } } for i, x := range nums { if x != i+1 { return i + 1 } } return n + 1 }
41
First Missing Positive
Hard
<p>Given an unsorted integer array <code>nums</code>. Return the <em>smallest positive integer</em> that is <em>not present</em> in <code>nums</code>.</p> <p>You must implement an algorithm that runs in <code>O(n)</code> time and uses <code>O(1)</code> auxiliary space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,0] <strong>Output:</strong> 3 <strong>Explanation:</strong> The numbers in the range [1,2] are all in the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1 is in the array but 2 is missing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,8,9,11,12] <strong>Output:</strong> 1 <strong>Explanation:</strong> The smallest positive integer 1 is missing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
Java
class Solution { public int firstMissingPositive(int[] nums) { int n = nums.length; for (int i = 0; i < n; ++i) { while (nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i] - 1]) { swap(nums, i, nums[i] - 1); } } for (int i = 0; i < n; ++i) { if (nums[i] != i + 1) { return i + 1; } } return n + 1; } private void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } }
41
First Missing Positive
Hard
<p>Given an unsorted integer array <code>nums</code>. Return the <em>smallest positive integer</em> that is <em>not present</em> in <code>nums</code>.</p> <p>You must implement an algorithm that runs in <code>O(n)</code> time and uses <code>O(1)</code> auxiliary space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,0] <strong>Output:</strong> 3 <strong>Explanation:</strong> The numbers in the range [1,2] are all in the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1 is in the array but 2 is missing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,8,9,11,12] <strong>Output:</strong> 1 <strong>Explanation:</strong> The smallest positive integer 1 is missing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
PHP
class Solution { /** * @param Integer[] $nums * @return Integer */ function firstMissingPositive($nums) { $n = count($nums); for ($i = 0; $i < $n; $i++) { while ($nums[$i] >= 1 && $nums[$i] <= $n && $nums[$i] != $nums[$nums[$i] - 1]) { $j = $nums[$i] - 1; $t = $nums[$i]; $nums[$i] = $nums[$j]; $nums[$j] = $t; } } for ($i = 0; $i < $n; $i++) { if ($nums[$i] != $i + 1) { return $i + 1; } } return $n + 1; } }
41
First Missing Positive
Hard
<p>Given an unsorted integer array <code>nums</code>. Return the <em>smallest positive integer</em> that is <em>not present</em> in <code>nums</code>.</p> <p>You must implement an algorithm that runs in <code>O(n)</code> time and uses <code>O(1)</code> auxiliary space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,0] <strong>Output:</strong> 3 <strong>Explanation:</strong> The numbers in the range [1,2] are all in the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1 is in the array but 2 is missing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,8,9,11,12] <strong>Output:</strong> 1 <strong>Explanation:</strong> The smallest positive integer 1 is missing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
Python
class Solution: def firstMissingPositive(self, nums: List[int]) -> int: n = len(nums) for i in range(n): while 1 <= nums[i] <= n and nums[i] != nums[nums[i] - 1]: j = nums[i] - 1 nums[i], nums[j] = nums[j], nums[i] for i in range(n): if nums[i] != i + 1: return i + 1 return n + 1
41
First Missing Positive
Hard
<p>Given an unsorted integer array <code>nums</code>. Return the <em>smallest positive integer</em> that is <em>not present</em> in <code>nums</code>.</p> <p>You must implement an algorithm that runs in <code>O(n)</code> time and uses <code>O(1)</code> auxiliary space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,0] <strong>Output:</strong> 3 <strong>Explanation:</strong> The numbers in the range [1,2] are all in the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1 is in the array but 2 is missing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,8,9,11,12] <strong>Output:</strong> 1 <strong>Explanation:</strong> The smallest positive integer 1 is missing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
Rust
impl Solution { pub fn first_missing_positive(mut nums: Vec<i32>) -> i32 { let n = nums.len(); for i in 0..n { while nums[i] > 0 && nums[i] <= n as i32 && nums[i] != nums[nums[i] as usize - 1] { let j = nums[i] as usize - 1; nums.swap(i, j); } } for i in 0..n { if nums[i] != (i + 1) as i32 { return (i + 1) as i32; } } return (n + 1) as i32; } }
41
First Missing Positive
Hard
<p>Given an unsorted integer array <code>nums</code>. Return the <em>smallest positive integer</em> that is <em>not present</em> in <code>nums</code>.</p> <p>You must implement an algorithm that runs in <code>O(n)</code> time and uses <code>O(1)</code> auxiliary space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,0] <strong>Output:</strong> 3 <strong>Explanation:</strong> The numbers in the range [1,2] are all in the array. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [3,4,-1,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 1 is in the array but 2 is missing. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [7,8,9,11,12] <strong>Output:</strong> 1 <strong>Explanation:</strong> The smallest positive integer 1 is missing. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Array; Hash Table
TypeScript
function firstMissingPositive(nums: number[]): number { const n = nums.length; for (let i = 0; i < n; i++) { while (nums[i] >= 1 && nums[i] <= n && nums[i] !== nums[nums[i] - 1]) { const j = nums[i] - 1; [nums[i], nums[j]] = [nums[j], nums[i]]; } } for (let i = 0; i < n; i++) { if (nums[i] !== i + 1) { return i + 1; } } return n + 1; }
42
Trapping Rain Water
Hard
<p>Given <code>n</code> non-negative integers representing an elevation map where the width of each bar is <code>1</code>, compute how much water it can trap after raining.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0042.Trapping%20Rain%20Water/images/rainwatertrap.png" style="width: 412px; height: 161px;" /> <pre> <strong>Input:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [4,2,0,3,2,5] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Array; Two Pointers; Dynamic Programming; Monotonic Stack
C++
class Solution { public: int trap(vector<int>& height) { int n = height.size(); int left[n], right[n]; left[0] = height[0]; right[n - 1] = height[n - 1]; for (int i = 1; i < n; ++i) { left[i] = max(left[i - 1], height[i]); right[n - i - 1] = max(right[n - i], height[n - i - 1]); } int ans = 0; for (int i = 0; i < n; ++i) { ans += min(left[i], right[i]) - height[i]; } return ans; } };
42
Trapping Rain Water
Hard
<p>Given <code>n</code> non-negative integers representing an elevation map where the width of each bar is <code>1</code>, compute how much water it can trap after raining.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0042.Trapping%20Rain%20Water/images/rainwatertrap.png" style="width: 412px; height: 161px;" /> <pre> <strong>Input:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [4,2,0,3,2,5] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Array; Two Pointers; Dynamic Programming; Monotonic Stack
C#
public class Solution { public int Trap(int[] height) { int n = height.Length; int[] left = new int[n]; int[] right = new int[n]; left[0] = height[0]; right[n - 1] = height[n - 1]; for (int i = 1; i < n; ++i) { left[i] = Math.Max(left[i - 1], height[i]); right[n - i - 1] = Math.Max(right[n - i], height[n - i - 1]); } int ans = 0; for (int i = 0; i < n; ++i) { ans += Math.Min(left[i], right[i]) - height[i]; } return ans; } }
42
Trapping Rain Water
Hard
<p>Given <code>n</code> non-negative integers representing an elevation map where the width of each bar is <code>1</code>, compute how much water it can trap after raining.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0042.Trapping%20Rain%20Water/images/rainwatertrap.png" style="width: 412px; height: 161px;" /> <pre> <strong>Input:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [4,2,0,3,2,5] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Array; Two Pointers; Dynamic Programming; Monotonic Stack
Go
func trap(height []int) (ans int) { n := len(height) left := make([]int, n) right := make([]int, n) left[0], right[n-1] = height[0], height[n-1] for i := 1; i < n; i++ { left[i] = max(left[i-1], height[i]) right[n-i-1] = max(right[n-i], height[n-i-1]) } for i, h := range height { ans += min(left[i], right[i]) - h } return }
42
Trapping Rain Water
Hard
<p>Given <code>n</code> non-negative integers representing an elevation map where the width of each bar is <code>1</code>, compute how much water it can trap after raining.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0042.Trapping%20Rain%20Water/images/rainwatertrap.png" style="width: 412px; height: 161px;" /> <pre> <strong>Input:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [4,2,0,3,2,5] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Array; Two Pointers; Dynamic Programming; Monotonic Stack
Java
class Solution { public int trap(int[] height) { int n = height.length; int[] left = new int[n]; int[] right = new int[n]; left[0] = height[0]; right[n - 1] = height[n - 1]; for (int i = 1; i < n; ++i) { left[i] = Math.max(left[i - 1], height[i]); right[n - i - 1] = Math.max(right[n - i], height[n - i - 1]); } int ans = 0; for (int i = 0; i < n; ++i) { ans += Math.min(left[i], right[i]) - height[i]; } return ans; } }
42
Trapping Rain Water
Hard
<p>Given <code>n</code> non-negative integers representing an elevation map where the width of each bar is <code>1</code>, compute how much water it can trap after raining.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0042.Trapping%20Rain%20Water/images/rainwatertrap.png" style="width: 412px; height: 161px;" /> <pre> <strong>Input:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [4,2,0,3,2,5] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Array; Two Pointers; Dynamic Programming; Monotonic Stack
PHP
class Solution { /** * @param integer[] $height * @return integer */ function trap($height) { $n = count($height); if ($n == 0) { return 0; } $left = 0; $right = $n - 1; $leftMax = 0; $rightMax = 0; $ans = 0; while ($left < $right) { if ($height[$left] < $height[$right]) { if ($height[$left] > $leftMax) { $leftMax = $height[$left]; } else { $ans += $leftMax - $height[$left]; } $left++; } else { if ($height[$right] > $rightMax) { $rightMax = $height[$right]; } else { $ans += $rightMax - $height[$right]; } $right--; } } return $ans; } }
42
Trapping Rain Water
Hard
<p>Given <code>n</code> non-negative integers representing an elevation map where the width of each bar is <code>1</code>, compute how much water it can trap after raining.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0042.Trapping%20Rain%20Water/images/rainwatertrap.png" style="width: 412px; height: 161px;" /> <pre> <strong>Input:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [4,2,0,3,2,5] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Array; Two Pointers; Dynamic Programming; Monotonic Stack
Python
class Solution: def trap(self, height: List[int]) -> int: n = len(height) left = [height[0]] * n right = [height[-1]] * n for i in range(1, n): left[i] = max(left[i - 1], height[i]) right[n - i - 1] = max(right[n - i], height[n - i - 1]) return sum(min(l, r) - h for l, r, h in zip(left, right, height))
42
Trapping Rain Water
Hard
<p>Given <code>n</code> non-negative integers representing an elevation map where the width of each bar is <code>1</code>, compute how much water it can trap after raining.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0042.Trapping%20Rain%20Water/images/rainwatertrap.png" style="width: 412px; height: 161px;" /> <pre> <strong>Input:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [4,2,0,3,2,5] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Array; Two Pointers; Dynamic Programming; Monotonic Stack
Rust
impl Solution { #[allow(dead_code)] pub fn trap(height: Vec<i32>) -> i32 { let n = height.len(); let mut left: Vec<i32> = vec![0; n]; let mut right: Vec<i32> = vec![0; n]; left[0] = height[0]; right[n - 1] = height[n - 1]; // Initialize the left & right vector for i in 1..n { left[i] = std::cmp::max(left[i - 1], height[i]); right[n - i - 1] = std::cmp::max(right[n - i], height[n - i - 1]); } let mut ans = 0; // Calculate the ans for i in 0..n { ans += std::cmp::min(left[i], right[i]) - height[i]; } ans } }
42
Trapping Rain Water
Hard
<p>Given <code>n</code> non-negative integers representing an elevation map where the width of each bar is <code>1</code>, compute how much water it can trap after raining.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0042.Trapping%20Rain%20Water/images/rainwatertrap.png" style="width: 412px; height: 161px;" /> <pre> <strong>Input:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1] <strong>Output:</strong> 6 <strong>Explanation:</strong> The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [4,2,0,3,2,5] <strong>Output:</strong> 9 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li> </ul>
Stack; Array; Two Pointers; Dynamic Programming; Monotonic Stack
TypeScript
function trap(height: number[]): number { const n = height.length; const left: number[] = new Array(n).fill(height[0]); const right: number[] = new Array(n).fill(height[n - 1]); for (let i = 1; i < n; ++i) { left[i] = Math.max(left[i - 1], height[i]); right[n - i - 1] = Math.max(right[n - i], height[n - i - 1]); } let ans = 0; for (let i = 0; i < n; ++i) { ans += Math.min(left[i], right[i]) - height[i]; } return ans; }
43
Multiply Strings
Medium
<p>Given two non-negative integers <code>num1</code> and <code>num2</code> represented as strings, return the product of <code>num1</code> and <code>num2</code>, also represented as a string.</p> <p><strong>Note:</strong>&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num1 = "2", num2 = "3" <strong>Output:</strong> "6" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num1 = "123", num2 = "456" <strong>Output:</strong> "56088" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li> <li><code>num1</code> and <code>num2</code> consist of digits only.</li> <li>Both <code>num1</code> and <code>num2</code>&nbsp;do not contain any leading zero, except the number <code>0</code> itself.</li> </ul>
Math; String; Simulation
C++
class Solution { public: string multiply(string num1, string num2) { if (num1 == "0" || num2 == "0") { return "0"; } int m = num1.size(), n = num2.size(); vector<int> arr(m + n); for (int i = m - 1; i >= 0; --i) { int a = num1[i] - '0'; for (int j = n - 1; j >= 0; --j) { int b = num2[j] - '0'; arr[i + j + 1] += a * b; } } for (int i = arr.size() - 1; i; --i) { arr[i - 1] += arr[i] / 10; arr[i] %= 10; } int i = arr[0] ? 0 : 1; string ans; for (; i < arr.size(); ++i) { ans += '0' + arr[i]; } return ans; } };
43
Multiply Strings
Medium
<p>Given two non-negative integers <code>num1</code> and <code>num2</code> represented as strings, return the product of <code>num1</code> and <code>num2</code>, also represented as a string.</p> <p><strong>Note:</strong>&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num1 = "2", num2 = "3" <strong>Output:</strong> "6" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num1 = "123", num2 = "456" <strong>Output:</strong> "56088" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li> <li><code>num1</code> and <code>num2</code> consist of digits only.</li> <li>Both <code>num1</code> and <code>num2</code>&nbsp;do not contain any leading zero, except the number <code>0</code> itself.</li> </ul>
Math; String; Simulation
C#
public class Solution { public string Multiply(string num1, string num2) { if (num1 == "0" || num2 == "0") { return "0"; } int m = num1.Length; int n = num2.Length; int[] arr = new int[m + n]; for (int i = m - 1; i >= 0; i--) { int a = num1[i] - '0'; for (int j = n - 1; j >= 0; j--) { int b = num2[j] - '0'; arr[i + j + 1] += a * b; } } for (int i = arr.Length - 1; i > 0; i--) { arr[i - 1] += arr[i] / 10; arr[i] %= 10; } int index = 0; while (index < arr.Length && arr[index] == 0) { index++; } StringBuilder ans = new StringBuilder(); for (; index < arr.Length; index++) { ans.Append(arr[index]); } return ans.ToString(); } }
43
Multiply Strings
Medium
<p>Given two non-negative integers <code>num1</code> and <code>num2</code> represented as strings, return the product of <code>num1</code> and <code>num2</code>, also represented as a string.</p> <p><strong>Note:</strong>&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num1 = "2", num2 = "3" <strong>Output:</strong> "6" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num1 = "123", num2 = "456" <strong>Output:</strong> "56088" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li> <li><code>num1</code> and <code>num2</code> consist of digits only.</li> <li>Both <code>num1</code> and <code>num2</code>&nbsp;do not contain any leading zero, except the number <code>0</code> itself.</li> </ul>
Math; String; Simulation
Go
func multiply(num1 string, num2 string) string { if num1 == "0" || num2 == "0" { return "0" } m, n := len(num1), len(num2) arr := make([]int, m+n) for i := m - 1; i >= 0; i-- { a := int(num1[i] - '0') for j := n - 1; j >= 0; j-- { b := int(num2[j] - '0') arr[i+j+1] += a * b } } for i := len(arr) - 1; i > 0; i-- { arr[i-1] += arr[i] / 10 arr[i] %= 10 } i := 0 if arr[0] == 0 { i = 1 } ans := []byte{} for ; i < len(arr); i++ { ans = append(ans, byte('0'+arr[i])) } return string(ans) }
43
Multiply Strings
Medium
<p>Given two non-negative integers <code>num1</code> and <code>num2</code> represented as strings, return the product of <code>num1</code> and <code>num2</code>, also represented as a string.</p> <p><strong>Note:</strong>&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num1 = "2", num2 = "3" <strong>Output:</strong> "6" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num1 = "123", num2 = "456" <strong>Output:</strong> "56088" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li> <li><code>num1</code> and <code>num2</code> consist of digits only.</li> <li>Both <code>num1</code> and <code>num2</code>&nbsp;do not contain any leading zero, except the number <code>0</code> itself.</li> </ul>
Math; String; Simulation
Java
class Solution { public String multiply(String num1, String num2) { if ("0".equals(num1) || "0".equals(num2)) { return "0"; } int m = num1.length(), n = num2.length(); int[] arr = new int[m + n]; for (int i = m - 1; i >= 0; --i) { int a = num1.charAt(i) - '0'; for (int j = n - 1; j >= 0; --j) { int b = num2.charAt(j) - '0'; arr[i + j + 1] += a * b; } } for (int i = arr.length - 1; i > 0; --i) { arr[i - 1] += arr[i] / 10; arr[i] %= 10; } int i = arr[0] == 0 ? 1 : 0; StringBuilder ans = new StringBuilder(); for (; i < arr.length; ++i) { ans.append(arr[i]); } return ans.toString(); } }
43
Multiply Strings
Medium
<p>Given two non-negative integers <code>num1</code> and <code>num2</code> represented as strings, return the product of <code>num1</code> and <code>num2</code>, also represented as a string.</p> <p><strong>Note:</strong>&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> num1 = "2", num2 = "3" <strong>Output:</strong> "6" </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> num1 = "123", num2 = "456" <strong>Output:</strong> "56088" </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li> <li><code>num1</code> and <code>num2</code> consist of digits only.</li> <li>Both <code>num1</code> and <code>num2</code>&nbsp;do not contain any leading zero, except the number <code>0</code> itself.</li> </ul>
Math; String; Simulation
JavaScript
/** * @param {string} num1 * @param {string} num2 * @return {string} */ var multiply = function (num1, num2) { if (num1 === '0' || num2 === '0') return '0'; const result = Array(num1.length + num2.length).fill(0); const code_0 = '0'.charCodeAt(0); const num1_len = num1.length; const num2_len = num2.length; for (let i = 0; i < num1_len; ++i) { const multiplier_1 = num1.charCodeAt(num1_len - i - 1) - code_0; for (let j = 0; j < num2_len; ++j) { const multiplier_2 = num2.charCodeAt(num2_len - j - 1) - code_0; result[i + j] += multiplier_1 * multiplier_2; } } result.reduce((carry, value, index) => { const sum = carry + value; result[index] = sum % 10; return (sum / 10) | 0; }, 0); return result .slice(0, result.findLastIndex(d => d !== 0) + 1) .reverse() .join(''); };