id
int64
1
3.65k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
216
Combination Sum III
Medium
<p>Find all valid combinations of <code>k</code> numbers that sum up to <code>n</code> such that the following conditions are true:</p> <ul> <li>Only numbers <code>1</code> through <code>9</code> are used.</li> <li>Each number is used <strong>at most once</strong>.</li> </ul> <p>Return <em>a list of all possible valid combinations</em>. The list must not contain the same combination twice, and the combinations may be returned in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 7 <strong>Output:</strong> [[1,2,4]] <strong>Explanation:</strong> 1 + 2 + 4 = 7 There are no other valid combinations.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 9 <strong>Output:</strong> [[1,2,6],[1,3,5],[2,3,4]] <strong>Explanation:</strong> 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> k = 4, n = 1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no valid combinations. Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 &gt; 1, there are no valid combination. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= k &lt;= 9</code></li> <li><code>1 &lt;= n &lt;= 60</code></li> </ul>
Array; Backtracking
Rust
impl Solution { #[allow(dead_code)] pub fn combination_sum3(k: i32, n: i32) -> Vec<Vec<i32>> { let mut ret = Vec::new(); let mut candidates = (1..=9).collect(); let mut cur_vec = Vec::new(); Self::dfs(n, k, 0, 0, &mut cur_vec, &mut candidates, &mut ret); ret } #[allow(dead_code)] fn dfs( target: i32, length: i32, cur_index: usize, cur_sum: i32, cur_vec: &mut Vec<i32>, candidates: &Vec<i32>, ans: &mut Vec<Vec<i32>>, ) { if cur_sum > target || cur_vec.len() > (length as usize) { // No answer for this return; } if cur_sum == target && cur_vec.len() == (length as usize) { // We get an answer ans.push(cur_vec.clone()); return; } for i in cur_index..candidates.len() { cur_vec.push(candidates[i]); Self::dfs( target, length, i + 1, cur_sum + candidates[i], cur_vec, candidates, ans, ); cur_vec.pop().unwrap(); } } }
216
Combination Sum III
Medium
<p>Find all valid combinations of <code>k</code> numbers that sum up to <code>n</code> such that the following conditions are true:</p> <ul> <li>Only numbers <code>1</code> through <code>9</code> are used.</li> <li>Each number is used <strong>at most once</strong>.</li> </ul> <p>Return <em>a list of all possible valid combinations</em>. The list must not contain the same combination twice, and the combinations may be returned in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 7 <strong>Output:</strong> [[1,2,4]] <strong>Explanation:</strong> 1 + 2 + 4 = 7 There are no other valid combinations.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> k = 3, n = 9 <strong>Output:</strong> [[1,2,6],[1,3,5],[2,3,4]] <strong>Explanation:</strong> 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> k = 4, n = 1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no valid combinations. Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 &gt; 1, there are no valid combination. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= k &lt;= 9</code></li> <li><code>1 &lt;= n &lt;= 60</code></li> </ul>
Array; Backtracking
TypeScript
function combinationSum3(k: number, n: number): number[][] { const ans: number[][] = []; const t: number[] = []; const dfs = (i: number, s: number) => { if (s === 0) { if (t.length === k) { ans.push(t.slice()); } return; } if (i > 9 || i > s || t.length >= k) { return; } t.push(i); dfs(i + 1, s - i); t.pop(); dfs(i + 1, s); }; dfs(1, n); return ans; }
217
Contains Duplicate
Easy
<p>Given an integer array <code>nums</code>, return <code>true</code> if any value appears <strong>at least twice</strong> in the array, and return <code>false</code> if every element is distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The element 1 occurs at the indices 0 and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>All elements are distinct.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,3,3,4,3,2,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sorting
C
int cmp(const void* a, const void* b) { return *(int*) a - *(int*) b; } bool containsDuplicate(int* nums, int numsSize) { qsort(nums, numsSize, sizeof(int), cmp); for (int i = 1; i < numsSize; i++) { if (nums[i - 1] == nums[i]) { return 1; } } return 0; }
217
Contains Duplicate
Easy
<p>Given an integer array <code>nums</code>, return <code>true</code> if any value appears <strong>at least twice</strong> in the array, and return <code>false</code> if every element is distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The element 1 occurs at the indices 0 and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>All elements are distinct.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,3,3,4,3,2,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sorting
C++
class Solution { public: bool containsDuplicate(vector<int>& nums) { sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size() - 1; ++i) { if (nums[i] == nums[i + 1]) { return true; } } return false; } };
217
Contains Duplicate
Easy
<p>Given an integer array <code>nums</code>, return <code>true</code> if any value appears <strong>at least twice</strong> in the array, and return <code>false</code> if every element is distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The element 1 occurs at the indices 0 and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>All elements are distinct.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,3,3,4,3,2,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sorting
C#
public class Solution { public bool ContainsDuplicate(int[] nums) { return nums.Distinct().Count() < nums.Length; } }
217
Contains Duplicate
Easy
<p>Given an integer array <code>nums</code>, return <code>true</code> if any value appears <strong>at least twice</strong> in the array, and return <code>false</code> if every element is distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The element 1 occurs at the indices 0 and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>All elements are distinct.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,3,3,4,3,2,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sorting
Go
func containsDuplicate(nums []int) bool { sort.Ints(nums) for i, v := range nums[1:] { if v == nums[i] { return true } } return false }
217
Contains Duplicate
Easy
<p>Given an integer array <code>nums</code>, return <code>true</code> if any value appears <strong>at least twice</strong> in the array, and return <code>false</code> if every element is distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The element 1 occurs at the indices 0 and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>All elements are distinct.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,3,3,4,3,2,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sorting
Java
class Solution { public boolean containsDuplicate(int[] nums) { Arrays.sort(nums); for (int i = 0; i < nums.length - 1; ++i) { if (nums[i] == nums[i + 1]) { return true; } } return false; } }
217
Contains Duplicate
Easy
<p>Given an integer array <code>nums</code>, return <code>true</code> if any value appears <strong>at least twice</strong> in the array, and return <code>false</code> if every element is distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The element 1 occurs at the indices 0 and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>All elements are distinct.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,3,3,4,3,2,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sorting
JavaScript
/** * @param {number[]} nums * @return {boolean} */ var containsDuplicate = function (nums) { return new Set(nums).size !== nums.length; };
217
Contains Duplicate
Easy
<p>Given an integer array <code>nums</code>, return <code>true</code> if any value appears <strong>at least twice</strong> in the array, and return <code>false</code> if every element is distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The element 1 occurs at the indices 0 and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>All elements are distinct.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,3,3,4,3,2,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sorting
PHP
class Solution { /** * @param Integer[] $nums * @return Boolean */ function containsDuplicate($nums) { $numsUnique = array_unique($nums); return count($nums) != count($numsUnique); } }
217
Contains Duplicate
Easy
<p>Given an integer array <code>nums</code>, return <code>true</code> if any value appears <strong>at least twice</strong> in the array, and return <code>false</code> if every element is distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The element 1 occurs at the indices 0 and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>All elements are distinct.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,3,3,4,3,2,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sorting
Python
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return any(a == b for a, b in pairwise(sorted(nums)))
217
Contains Duplicate
Easy
<p>Given an integer array <code>nums</code>, return <code>true</code> if any value appears <strong>at least twice</strong> in the array, and return <code>false</code> if every element is distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The element 1 occurs at the indices 0 and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>All elements are distinct.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,3,3,4,3,2,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sorting
Rust
impl Solution { pub fn contains_duplicate(mut nums: Vec<i32>) -> bool { nums.sort(); let n = nums.len(); for i in 1..n { if nums[i - 1] == nums[i] { return true; } } false } }
217
Contains Duplicate
Easy
<p>Given an integer array <code>nums</code>, return <code>true</code> if any value appears <strong>at least twice</strong> in the array, and return <code>false</code> if every element is distinct.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,1]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>The element 1 occurs at the indices 0 and 3.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>All elements are distinct.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,3,3,4,3,2,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Hash Table; Sorting
TypeScript
function containsDuplicate(nums: number[]): boolean { nums.sort((a, b) => a - b); const n = nums.length; for (let i = 1; i < n; i++) { if (nums[i - 1] === nums[i]) { return true; } } return false; }
218
The Skyline Problem
Hard
<p>A city&#39;s <strong>skyline</strong> is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return <em>the <strong>skyline</strong> formed by these buildings collectively</em>.</p> <p>The geometric information of each building is given in the array <code>buildings</code> where <code>buildings[i] = [left<sub>i</sub>, right<sub>i</sub>, height<sub>i</sub>]</code>:</p> <ul> <li><code>left<sub>i</sub></code> is the x coordinate of the left edge of the <code>i<sup>th</sup></code> building.</li> <li><code>right<sub>i</sub></code> is the x coordinate of the right edge of the <code>i<sup>th</sup></code> building.</li> <li><code>height<sub>i</sub></code> is the height of the <code>i<sup>th</sup></code> building.</li> </ul> <p>You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height <code>0</code>.</p> <p>The <strong>skyline</strong> should be represented as a list of &quot;key points&quot; <strong>sorted by their x-coordinate</strong> in the form <code>[[x<sub>1</sub>,y<sub>1</sub>],[x<sub>2</sub>,y<sub>2</sub>],...]</code>. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate <code>0</code> and is used to mark the skyline&#39;s termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline&#39;s contour.</p> <p><b>Note:</b> There must be no consecutive horizontal lines of equal height in the output skyline. For instance, <code>[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]</code> is not acceptable; the three lines of height 5 should be merged into one in the final output as such: <code>[...,[2 3],[4 5],[12 7],...]</code></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0218.The%20Skyline%20Problem/images/merged.jpg" style="width: 800px; height: 331px;" /> <pre> <strong>Input:</strong> buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]] <strong>Output:</strong> [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]] <strong>Explanation:</strong> Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> buildings = [[0,2,3],[2,5,3]] <strong>Output:</strong> [[0,3],[5,0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= buildings.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= height<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li> <li><code>buildings</code> is sorted by <code>left<sub>i</sub></code> in&nbsp;non-decreasing order.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Divide and Conquer; Ordered Set; Line Sweep; Heap (Priority Queue)
C++
class Solution { public: vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { set<int> poss; map<int, int> m; for (auto v : buildings) { poss.insert(v[0]); poss.insert(v[1]); } int i = 0; for (int pos : poss) m.insert(pair<int, int>(pos, i++)); vector<int> highs(m.size(), 0); for (auto v : buildings) { const int b = m[v[0]], e = m[v[1]]; for (int i = b; i < e; ++i) highs[i] = max(highs[i], v[2]); } vector<pair<int, int>> res; vector<int> mm(poss.begin(), poss.end()); for (int i = 0; i < highs.size(); ++i) { if (highs[i] != highs[i + 1]) res.push_back(pair<int, int>(mm[i], highs[i])); else { const int start = i; res.push_back(pair<int, int>(mm[start], highs[i])); while (highs[i] == highs[i + 1]) ++i; } } return res; } };
218
The Skyline Problem
Hard
<p>A city&#39;s <strong>skyline</strong> is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return <em>the <strong>skyline</strong> formed by these buildings collectively</em>.</p> <p>The geometric information of each building is given in the array <code>buildings</code> where <code>buildings[i] = [left<sub>i</sub>, right<sub>i</sub>, height<sub>i</sub>]</code>:</p> <ul> <li><code>left<sub>i</sub></code> is the x coordinate of the left edge of the <code>i<sup>th</sup></code> building.</li> <li><code>right<sub>i</sub></code> is the x coordinate of the right edge of the <code>i<sup>th</sup></code> building.</li> <li><code>height<sub>i</sub></code> is the height of the <code>i<sup>th</sup></code> building.</li> </ul> <p>You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height <code>0</code>.</p> <p>The <strong>skyline</strong> should be represented as a list of &quot;key points&quot; <strong>sorted by their x-coordinate</strong> in the form <code>[[x<sub>1</sub>,y<sub>1</sub>],[x<sub>2</sub>,y<sub>2</sub>],...]</code>. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate <code>0</code> and is used to mark the skyline&#39;s termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline&#39;s contour.</p> <p><b>Note:</b> There must be no consecutive horizontal lines of equal height in the output skyline. For instance, <code>[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]</code> is not acceptable; the three lines of height 5 should be merged into one in the final output as such: <code>[...,[2 3],[4 5],[12 7],...]</code></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0218.The%20Skyline%20Problem/images/merged.jpg" style="width: 800px; height: 331px;" /> <pre> <strong>Input:</strong> buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]] <strong>Output:</strong> [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]] <strong>Explanation:</strong> Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> buildings = [[0,2,3],[2,5,3]] <strong>Output:</strong> [[0,3],[5,0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= buildings.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= height<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li> <li><code>buildings</code> is sorted by <code>left<sub>i</sub></code> in&nbsp;non-decreasing order.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Divide and Conquer; Ordered Set; Line Sweep; Heap (Priority Queue)
Go
type Matrix struct{ left, right, height int } type Queue []Matrix func (q Queue) Len() int { return len(q) } func (q Queue) Top() Matrix { return q[0] } func (q Queue) Swap(i, j int) { q[i], q[j] = q[j], q[i] } func (q Queue) Less(i, j int) bool { return q[i].height > q[j].height } func (q *Queue) Push(x any) { *q = append(*q, x.(Matrix)) } func (q *Queue) Pop() any { old, x := *q, (*q)[len(*q)-1] *q = old[:len(old)-1] return x } func getSkyline(buildings [][]int) [][]int { skys, lines, pq := make([][]int, 0), make([]int, 0), &Queue{} heap.Init(pq) for _, v := range buildings { lines = append(lines, v[0], v[1]) } sort.Ints(lines) city, n := 0, len(buildings) for _, line := range lines { // 将所有符合条件的矩形加入队列 for ; city < n && buildings[city][0] <= line && buildings[city][1] > line; city++ { v := Matrix{left: buildings[city][0], right: buildings[city][1], height: buildings[city][2]} heap.Push(pq, v) } // 从队列移除不符合条件的矩形 for pq.Len() > 0 && pq.Top().right <= line { heap.Pop(pq) } high := 0 // 队列为空说明是最右侧建筑物的终点,其轮廓点为 (line, 0) if pq.Len() != 0 { high = pq.Top().height } // 如果该点高度和前一个轮廓点一样的话,直接忽略 if len(skys) > 0 && skys[len(skys)-1][1] == high { continue } skys = append(skys, []int{line, high}) } return skys }
218
The Skyline Problem
Hard
<p>A city&#39;s <strong>skyline</strong> is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return <em>the <strong>skyline</strong> formed by these buildings collectively</em>.</p> <p>The geometric information of each building is given in the array <code>buildings</code> where <code>buildings[i] = [left<sub>i</sub>, right<sub>i</sub>, height<sub>i</sub>]</code>:</p> <ul> <li><code>left<sub>i</sub></code> is the x coordinate of the left edge of the <code>i<sup>th</sup></code> building.</li> <li><code>right<sub>i</sub></code> is the x coordinate of the right edge of the <code>i<sup>th</sup></code> building.</li> <li><code>height<sub>i</sub></code> is the height of the <code>i<sup>th</sup></code> building.</li> </ul> <p>You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height <code>0</code>.</p> <p>The <strong>skyline</strong> should be represented as a list of &quot;key points&quot; <strong>sorted by their x-coordinate</strong> in the form <code>[[x<sub>1</sub>,y<sub>1</sub>],[x<sub>2</sub>,y<sub>2</sub>],...]</code>. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate <code>0</code> and is used to mark the skyline&#39;s termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline&#39;s contour.</p> <p><b>Note:</b> There must be no consecutive horizontal lines of equal height in the output skyline. For instance, <code>[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]</code> is not acceptable; the three lines of height 5 should be merged into one in the final output as such: <code>[...,[2 3],[4 5],[12 7],...]</code></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0218.The%20Skyline%20Problem/images/merged.jpg" style="width: 800px; height: 331px;" /> <pre> <strong>Input:</strong> buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]] <strong>Output:</strong> [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]] <strong>Explanation:</strong> Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> buildings = [[0,2,3],[2,5,3]] <strong>Output:</strong> [[0,3],[5,0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= buildings.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= height<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li> <li><code>buildings</code> is sorted by <code>left<sub>i</sub></code> in&nbsp;non-decreasing order.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Divide and Conquer; Ordered Set; Line Sweep; Heap (Priority Queue)
Python
from queue import PriorityQueue class Solution: def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]: skys, lines, pq = [], [], PriorityQueue() for build in buildings: lines.extend([build[0], build[1]]) lines.sort() city, n = 0, len(buildings) for line in lines: while city < n and buildings[city][0] <= line: pq.put([-buildings[city][2], buildings[city][0], buildings[city][1]]) city += 1 while not pq.empty() and pq.queue[0][2] <= line: pq.get() high = 0 if not pq.empty(): high = -pq.queue[0][0] if len(skys) > 0 and skys[-1][1] == high: continue skys.append([line, high]) return skys
218
The Skyline Problem
Hard
<p>A city&#39;s <strong>skyline</strong> is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return <em>the <strong>skyline</strong> formed by these buildings collectively</em>.</p> <p>The geometric information of each building is given in the array <code>buildings</code> where <code>buildings[i] = [left<sub>i</sub>, right<sub>i</sub>, height<sub>i</sub>]</code>:</p> <ul> <li><code>left<sub>i</sub></code> is the x coordinate of the left edge of the <code>i<sup>th</sup></code> building.</li> <li><code>right<sub>i</sub></code> is the x coordinate of the right edge of the <code>i<sup>th</sup></code> building.</li> <li><code>height<sub>i</sub></code> is the height of the <code>i<sup>th</sup></code> building.</li> </ul> <p>You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height <code>0</code>.</p> <p>The <strong>skyline</strong> should be represented as a list of &quot;key points&quot; <strong>sorted by their x-coordinate</strong> in the form <code>[[x<sub>1</sub>,y<sub>1</sub>],[x<sub>2</sub>,y<sub>2</sub>],...]</code>. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate <code>0</code> and is used to mark the skyline&#39;s termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline&#39;s contour.</p> <p><b>Note:</b> There must be no consecutive horizontal lines of equal height in the output skyline. For instance, <code>[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]</code> is not acceptable; the three lines of height 5 should be merged into one in the final output as such: <code>[...,[2 3],[4 5],[12 7],...]</code></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0218.The%20Skyline%20Problem/images/merged.jpg" style="width: 800px; height: 331px;" /> <pre> <strong>Input:</strong> buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]] <strong>Output:</strong> [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]] <strong>Explanation:</strong> Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> buildings = [[0,2,3],[2,5,3]] <strong>Output:</strong> [[0,3],[5,0]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= buildings.length &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li> <li><code>1 &lt;= height<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li> <li><code>buildings</code> is sorted by <code>left<sub>i</sub></code> in&nbsp;non-decreasing order.</li> </ul>
Binary Indexed Tree; Segment Tree; Array; Divide and Conquer; Ordered Set; Line Sweep; Heap (Priority Queue)
Rust
impl Solution { pub fn get_skyline(buildings: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut skys: Vec<Vec<i32>> = vec![]; let mut lines = vec![]; for building in buildings.iter() { lines.push(building[0]); lines.push(building[1]); } lines.sort_unstable(); let mut pq = std::collections::BinaryHeap::new(); let (mut city, n) = (0, buildings.len()); for line in lines { while city < n && buildings[city][0] <= line && buildings[city][1] > line { pq.push((buildings[city][2], buildings[city][1])); city += 1; } while !pq.is_empty() && pq.peek().unwrap().1 <= line { pq.pop(); } let mut high = 0; if !pq.is_empty() { high = pq.peek().unwrap().0; } if !skys.is_empty() && skys.last().unwrap()[1] == high { continue; } skys.push(vec![line, high]); } skys } }
219
Contains Duplicate II
Easy
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if there are two <strong>distinct indices</strong> </em><code>i</code><em> and </em><code>j</code><em> in the array such that </em><code>nums[i] == nums[j]</code><em> and </em><code>abs(i - j) &lt;= k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], k = 3 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,1,1], k = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2 <strong>Output:</strong> false </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>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Sliding Window
C++
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int, int> d; for (int i = 0; i < nums.size(); ++i) { if (d.count(nums[i]) && i - d[nums[i]] <= k) { return true; } d[nums[i]] = i; } return false; } };
219
Contains Duplicate II
Easy
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if there are two <strong>distinct indices</strong> </em><code>i</code><em> and </em><code>j</code><em> in the array such that </em><code>nums[i] == nums[j]</code><em> and </em><code>abs(i - j) &lt;= k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], k = 3 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,1,1], k = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2 <strong>Output:</strong> false </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>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Sliding Window
C#
public class Solution { public bool ContainsNearbyDuplicate(int[] nums, int k) { var d = new Dictionary<int, int>(); for (int i = 0; i < nums.Length; ++i) { if (d.ContainsKey(nums[i]) && i - d[nums[i]] <= k) { return true; } d[nums[i]] = i; } return false; } }
219
Contains Duplicate II
Easy
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if there are two <strong>distinct indices</strong> </em><code>i</code><em> and </em><code>j</code><em> in the array such that </em><code>nums[i] == nums[j]</code><em> and </em><code>abs(i - j) &lt;= k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], k = 3 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,1,1], k = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2 <strong>Output:</strong> false </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>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Sliding Window
Go
func containsNearbyDuplicate(nums []int, k int) bool { d := map[int]int{} for i, x := range nums { if j, ok := d[x]; ok && i-j <= k { return true } d[x] = i } return false }
219
Contains Duplicate II
Easy
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if there are two <strong>distinct indices</strong> </em><code>i</code><em> and </em><code>j</code><em> in the array such that </em><code>nums[i] == nums[j]</code><em> and </em><code>abs(i - j) &lt;= k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], k = 3 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,1,1], k = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2 <strong>Output:</strong> false </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>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Sliding Window
Java
class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { Map<Integer, Integer> d = new HashMap<>(); for (int i = 0; i < nums.length; ++i) { if (i - d.getOrDefault(nums[i], -1000000) <= k) { return true; } d.put(nums[i], i); } return false; } }
219
Contains Duplicate II
Easy
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if there are two <strong>distinct indices</strong> </em><code>i</code><em> and </em><code>j</code><em> in the array such that </em><code>nums[i] == nums[j]</code><em> and </em><code>abs(i - j) &lt;= k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], k = 3 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,1,1], k = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2 <strong>Output:</strong> false </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>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Sliding Window
JavaScript
/** * @param {number[]} nums * @param {number} k * @return {boolean} */ var containsNearbyDuplicate = function (nums, k) { const d = new Map(); for (let i = 0; i < nums.length; ++i) { if (d.has(nums[i]) && i - d.get(nums[i]) <= k) { return true; } d.set(nums[i], i); } return false; };
219
Contains Duplicate II
Easy
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if there are two <strong>distinct indices</strong> </em><code>i</code><em> and </em><code>j</code><em> in the array such that </em><code>nums[i] == nums[j]</code><em> and </em><code>abs(i - j) &lt;= k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], k = 3 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,1,1], k = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2 <strong>Output:</strong> false </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>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Sliding Window
PHP
class Solution { /** * @param Integer[] $nums * @param Integer $k * @return Boolean */ function containsNearbyDuplicate($nums, $k) { $d = []; for ($i = 0; $i < count($nums); ++$i) { if (array_key_exists($nums[$i], $d) && $i - $d[$nums[$i]] <= $k) { return true; } $d[$nums[$i]] = $i; } return false; } }
219
Contains Duplicate II
Easy
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if there are two <strong>distinct indices</strong> </em><code>i</code><em> and </em><code>j</code><em> in the array such that </em><code>nums[i] == nums[j]</code><em> and </em><code>abs(i - j) &lt;= k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], k = 3 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,1,1], k = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2 <strong>Output:</strong> false </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>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Sliding Window
Python
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: d = {} for i, x in enumerate(nums): if x in d and i - d[x] <= k: return True d[x] = i return False
219
Contains Duplicate II
Easy
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if there are two <strong>distinct indices</strong> </em><code>i</code><em> and </em><code>j</code><em> in the array such that </em><code>nums[i] == nums[j]</code><em> and </em><code>abs(i - j) &lt;= k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], k = 3 <strong>Output:</strong> true </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,1,1], k = 1 <strong>Output:</strong> true </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2 <strong>Output:</strong> false </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>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; Sliding Window
TypeScript
function containsNearbyDuplicate(nums: number[], k: number): boolean { const d: Map<number, number> = new Map(); for (let i = 0; i < nums.length; ++i) { if (d.has(nums[i]) && i - d.get(nums[i])! <= k) { return true; } d.set(nums[i], i); } return false; }
220
Contains Duplicate III
Hard
<p>You are given an integer array <code>nums</code> and two integers <code>indexDiff</code> and <code>valueDiff</code>.</p> <p>Find a pair of indices <code>(i, j)</code> such that:</p> <ul> <li><code>i != j</code>,</li> <li><code>abs(i - j) &lt;= indexDiff</code>.</li> <li><code>abs(nums[i] - nums[j]) &lt;= valueDiff</code>, and</li> </ul> <p>Return <code>true</code><em> if such pair exists or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], indexDiff = 3, valueDiff = 0 <strong>Output:</strong> true <strong>Explanation:</strong> We can choose (i, j) = (0, 3). We satisfy the three conditions: i != j --&gt; 0 != 3 abs(i - j) &lt;= indexDiff --&gt; abs(0 - 3) &lt;= 3 abs(nums[i] - nums[j]) &lt;= valueDiff --&gt; abs(1 - 1) &lt;= 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3 <strong>Output:</strong> false <strong>Explanation:</strong> After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= indexDiff &lt;= nums.length</code></li> <li><code>0 &lt;= valueDiff &lt;= 10<sup>9</sup></code></li> </ul>
Array; Bucket Sort; Ordered Set; Sorting; Sliding Window
C++
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int indexDiff, int valueDiff) { set<long> s; for (int i = 0; i < nums.size(); ++i) { auto it = s.lower_bound((long) nums[i] - valueDiff); if (it != s.end() && *it <= (long) nums[i] + valueDiff) return true; s.insert((long) nums[i]); if (i >= indexDiff) s.erase((long) nums[i - indexDiff]); } return false; } };
220
Contains Duplicate III
Hard
<p>You are given an integer array <code>nums</code> and two integers <code>indexDiff</code> and <code>valueDiff</code>.</p> <p>Find a pair of indices <code>(i, j)</code> such that:</p> <ul> <li><code>i != j</code>,</li> <li><code>abs(i - j) &lt;= indexDiff</code>.</li> <li><code>abs(nums[i] - nums[j]) &lt;= valueDiff</code>, and</li> </ul> <p>Return <code>true</code><em> if such pair exists or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], indexDiff = 3, valueDiff = 0 <strong>Output:</strong> true <strong>Explanation:</strong> We can choose (i, j) = (0, 3). We satisfy the three conditions: i != j --&gt; 0 != 3 abs(i - j) &lt;= indexDiff --&gt; abs(0 - 3) &lt;= 3 abs(nums[i] - nums[j]) &lt;= valueDiff --&gt; abs(1 - 1) &lt;= 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3 <strong>Output:</strong> false <strong>Explanation:</strong> After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= indexDiff &lt;= nums.length</code></li> <li><code>0 &lt;= valueDiff &lt;= 10<sup>9</sup></code></li> </ul>
Array; Bucket Sort; Ordered Set; Sorting; Sliding Window
C#
public class Solution { public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t) { if (k <= 0 || t < 0) return false; var index = new SortedList<int, object>(); for (int i = 0; i < nums.Length; ++i) { if (index.ContainsKey(nums[i])) { return true; } index.Add(nums[i], null); var j = index.IndexOfKey(nums[i]); if (j > 0 && (long)nums[i] - index.Keys[j - 1] <= t) { return true; } if (j < index.Count - 1 && (long)index.Keys[j + 1] - nums[i] <= t) { return true; } if (index.Count > k) { index.Remove(nums[i - k]); } } return false; } }
220
Contains Duplicate III
Hard
<p>You are given an integer array <code>nums</code> and two integers <code>indexDiff</code> and <code>valueDiff</code>.</p> <p>Find a pair of indices <code>(i, j)</code> such that:</p> <ul> <li><code>i != j</code>,</li> <li><code>abs(i - j) &lt;= indexDiff</code>.</li> <li><code>abs(nums[i] - nums[j]) &lt;= valueDiff</code>, and</li> </ul> <p>Return <code>true</code><em> if such pair exists or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], indexDiff = 3, valueDiff = 0 <strong>Output:</strong> true <strong>Explanation:</strong> We can choose (i, j) = (0, 3). We satisfy the three conditions: i != j --&gt; 0 != 3 abs(i - j) &lt;= indexDiff --&gt; abs(0 - 3) &lt;= 3 abs(nums[i] - nums[j]) &lt;= valueDiff --&gt; abs(1 - 1) &lt;= 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3 <strong>Output:</strong> false <strong>Explanation:</strong> After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= indexDiff &lt;= nums.length</code></li> <li><code>0 &lt;= valueDiff &lt;= 10<sup>9</sup></code></li> </ul>
Array; Bucket Sort; Ordered Set; Sorting; Sliding Window
Go
func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { n := len(nums) left, right := 0, 0 rbt := redblacktree.NewWithIntComparator() for right < n { cur := nums[right] right++ if p, ok := rbt.Floor(cur); ok && cur-p.Key.(int) <= t { return true } if p, ok := rbt.Ceiling(cur); ok && p.Key.(int)-cur <= t { return true } rbt.Put(cur, struct{}{}) if right-left > k { rbt.Remove(nums[left]) left++ } } return false }
220
Contains Duplicate III
Hard
<p>You are given an integer array <code>nums</code> and two integers <code>indexDiff</code> and <code>valueDiff</code>.</p> <p>Find a pair of indices <code>(i, j)</code> such that:</p> <ul> <li><code>i != j</code>,</li> <li><code>abs(i - j) &lt;= indexDiff</code>.</li> <li><code>abs(nums[i] - nums[j]) &lt;= valueDiff</code>, and</li> </ul> <p>Return <code>true</code><em> if such pair exists or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], indexDiff = 3, valueDiff = 0 <strong>Output:</strong> true <strong>Explanation:</strong> We can choose (i, j) = (0, 3). We satisfy the three conditions: i != j --&gt; 0 != 3 abs(i - j) &lt;= indexDiff --&gt; abs(0 - 3) &lt;= 3 abs(nums[i] - nums[j]) &lt;= valueDiff --&gt; abs(1 - 1) &lt;= 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3 <strong>Output:</strong> false <strong>Explanation:</strong> After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= indexDiff &lt;= nums.length</code></li> <li><code>0 &lt;= valueDiff &lt;= 10<sup>9</sup></code></li> </ul>
Array; Bucket Sort; Ordered Set; Sorting; Sliding Window
Java
class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int indexDiff, int valueDiff) { TreeSet<Long> ts = new TreeSet<>(); for (int i = 0; i < nums.length; ++i) { Long x = ts.ceiling((long) nums[i] - (long) valueDiff); if (x != null && x <= (long) nums[i] + (long) valueDiff) { return true; } ts.add((long) nums[i]); if (i >= indexDiff) { ts.remove((long) nums[i - indexDiff]); } } return false; } }
220
Contains Duplicate III
Hard
<p>You are given an integer array <code>nums</code> and two integers <code>indexDiff</code> and <code>valueDiff</code>.</p> <p>Find a pair of indices <code>(i, j)</code> such that:</p> <ul> <li><code>i != j</code>,</li> <li><code>abs(i - j) &lt;= indexDiff</code>.</li> <li><code>abs(nums[i] - nums[j]) &lt;= valueDiff</code>, and</li> </ul> <p>Return <code>true</code><em> if such pair exists or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], indexDiff = 3, valueDiff = 0 <strong>Output:</strong> true <strong>Explanation:</strong> We can choose (i, j) = (0, 3). We satisfy the three conditions: i != j --&gt; 0 != 3 abs(i - j) &lt;= indexDiff --&gt; abs(0 - 3) &lt;= 3 abs(nums[i] - nums[j]) &lt;= valueDiff --&gt; abs(1 - 1) &lt;= 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3 <strong>Output:</strong> false <strong>Explanation:</strong> After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= indexDiff &lt;= nums.length</code></li> <li><code>0 &lt;= valueDiff &lt;= 10<sup>9</sup></code></li> </ul>
Array; Bucket Sort; Ordered Set; Sorting; Sliding Window
Python
class Solution: def containsNearbyAlmostDuplicate( self, nums: List[int], indexDiff: int, valueDiff: int ) -> bool: s = SortedSet() for i, v in enumerate(nums): j = s.bisect_left(v - valueDiff) if j < len(s) and s[j] <= v + valueDiff: return True s.add(v) if i >= indexDiff: s.remove(nums[i - indexDiff]) return False
220
Contains Duplicate III
Hard
<p>You are given an integer array <code>nums</code> and two integers <code>indexDiff</code> and <code>valueDiff</code>.</p> <p>Find a pair of indices <code>(i, j)</code> such that:</p> <ul> <li><code>i != j</code>,</li> <li><code>abs(i - j) &lt;= indexDiff</code>.</li> <li><code>abs(nums[i] - nums[j]) &lt;= valueDiff</code>, and</li> </ul> <p>Return <code>true</code><em> if such pair exists or </em><code>false</code><em> otherwise</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1], indexDiff = 3, valueDiff = 0 <strong>Output:</strong> true <strong>Explanation:</strong> We can choose (i, j) = (0, 3). We satisfy the three conditions: i != j --&gt; 0 != 3 abs(i - j) &lt;= indexDiff --&gt; abs(0 - 3) &lt;= 3 abs(nums[i] - nums[j]) &lt;= valueDiff --&gt; abs(1 - 1) &lt;= 0 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3 <strong>Output:</strong> false <strong>Explanation:</strong> After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= indexDiff &lt;= nums.length</code></li> <li><code>0 &lt;= valueDiff &lt;= 10<sup>9</sup></code></li> </ul>
Array; Bucket Sort; Ordered Set; Sorting; Sliding Window
TypeScript
function containsNearbyAlmostDuplicate( nums: number[], indexDiff: number, valueDiff: number, ): boolean { const ts = new TreeSet<number>(); for (let i = 0; i < nums.length; ++i) { const x = ts.ceil(nums[i] - valueDiff); if (x != null && x <= nums[i] + valueDiff) { return true; } ts.add(nums[i]); if (i >= indexDiff) { ts.delete(nums[i - indexDiff]); } } return false; } type Compare<T> = (lhs: T, rhs: T) => number; class RBTreeNode<T = number> { data: T; count: number; left: RBTreeNode<T> | null; right: RBTreeNode<T> | null; parent: RBTreeNode<T> | null; color: number; constructor(data: T) { this.data = data; this.left = this.right = this.parent = null; this.color = 0; this.count = 1; } sibling(): RBTreeNode<T> | null { if (!this.parent) return null; // sibling null if no parent return this.isOnLeft() ? this.parent.right : this.parent.left; } isOnLeft(): boolean { return this === this.parent!.left; } hasRedChild(): boolean { return ( Boolean(this.left && this.left.color === 0) || Boolean(this.right && this.right.color === 0) ); } } class RBTree<T> { root: RBTreeNode<T> | null; lt: (l: T, r: T) => boolean; constructor(compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0)) { this.root = null; this.lt = (l: T, r: T) => compare(l, r) < 0; } rotateLeft(pt: RBTreeNode<T>): void { const right = pt.right!; pt.right = right.left; if (pt.right) pt.right.parent = pt; right.parent = pt.parent; if (!pt.parent) this.root = right; else if (pt === pt.parent.left) pt.parent.left = right; else pt.parent.right = right; right.left = pt; pt.parent = right; } rotateRight(pt: RBTreeNode<T>): void { const left = pt.left!; pt.left = left.right; if (pt.left) pt.left.parent = pt; left.parent = pt.parent; if (!pt.parent) this.root = left; else if (pt === pt.parent.left) pt.parent.left = left; else pt.parent.right = left; left.right = pt; pt.parent = left; } swapColor(p1: RBTreeNode<T>, p2: RBTreeNode<T>): void { const tmp = p1.color; p1.color = p2.color; p2.color = tmp; } swapData(p1: RBTreeNode<T>, p2: RBTreeNode<T>): void { const tmp = p1.data; p1.data = p2.data; p2.data = tmp; } fixAfterInsert(pt: RBTreeNode<T>): void { let parent = null; let grandParent = null; while (pt !== this.root && pt.color !== 1 && pt.parent?.color === 0) { parent = pt.parent; grandParent = pt.parent.parent; /* Case : A Parent of pt is left child of Grand-parent of pt */ if (parent === grandParent?.left) { const uncle = grandParent.right; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if (uncle && uncle.color === 0) { grandParent.color = 0; parent.color = 1; uncle.color = 1; pt = grandParent; } else { /* Case : 2 pt is right child of its parent Left-rotation required */ if (pt === parent.right) { this.rotateLeft(parent); pt = parent; parent = pt.parent; } /* Case : 3 pt is left child of its parent Right-rotation required */ this.rotateRight(grandParent); this.swapColor(parent!, grandParent); pt = parent!; } } else { /* Case : B Parent of pt is right child of Grand-parent of pt */ const uncle = grandParent!.left; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if (uncle != null && uncle.color === 0) { grandParent!.color = 0; parent.color = 1; uncle.color = 1; pt = grandParent!; } else { /* Case : 2 pt is left child of its parent Right-rotation required */ if (pt === parent.left) { this.rotateRight(parent); pt = parent; parent = pt.parent; } /* Case : 3 pt is right child of its parent Left-rotation required */ this.rotateLeft(grandParent!); this.swapColor(parent!, grandParent!); pt = parent!; } } } this.root!.color = 1; } delete(val: T): boolean { const node = this.find(val); if (!node) return false; node.count--; if (!node.count) this.deleteNode(node); return true; } deleteAll(val: T): boolean { const node = this.find(val); if (!node) return false; this.deleteNode(node); return true; } deleteNode(v: RBTreeNode<T>): void { const u = BSTreplace(v); // True when u and v are both black const uvBlack = (u === null || u.color === 1) && v.color === 1; const parent = v.parent!; if (!u) { // u is null therefore v is leaf if (v === this.root) this.root = null; // v is root, making root null else { if (uvBlack) { // u and v both black // v is leaf, fix double black at v this.fixDoubleBlack(v); } else { // u or v is red if (v.sibling()) { // sibling is not null, make it red" v.sibling()!.color = 0; } } // delete v from the tree if (v.isOnLeft()) parent.left = null; else parent.right = null; } return; } if (!v.left || !v.right) { // v has 1 child if (v === this.root) { // v is root, assign the value of u to v, and delete u v.data = u.data; v.left = v.right = null; } else { // Detach v from tree and move u up if (v.isOnLeft()) parent.left = u; else parent.right = u; u.parent = parent; if (uvBlack) this.fixDoubleBlack(u); // u and v both black, fix double black at u else u.color = 1; // u or v red, color u black } return; } // v has 2 children, swap data with successor and recurse this.swapData(u, v); this.deleteNode(u); // find node that replaces a deleted node in BST function BSTreplace(x: RBTreeNode<T>): RBTreeNode<T> | null { // when node have 2 children if (x.left && x.right) return successor(x.right); // when leaf if (!x.left && !x.right) return null; // when single child return x.left ?? x.right; } // find node that do not have a left child // in the subtree of the given node function successor(x: RBTreeNode<T>): RBTreeNode<T> { let temp = x; while (temp.left) temp = temp.left; return temp; } } fixDoubleBlack(x: RBTreeNode<T>): void { if (x === this.root) return; // Reached root const sibling = x.sibling(); const parent = x.parent!; if (!sibling) { // No sibiling, double black pushed up this.fixDoubleBlack(parent); } else { if (sibling.color === 0) { // Sibling red parent.color = 0; sibling.color = 1; if (sibling.isOnLeft()) this.rotateRight(parent); // left case else this.rotateLeft(parent); // right case this.fixDoubleBlack(x); } else { // Sibling black if (sibling.hasRedChild()) { // at least 1 red children if (sibling.left && sibling.left.color === 0) { if (sibling.isOnLeft()) { // left left sibling.left.color = sibling.color; sibling.color = parent.color; this.rotateRight(parent); } else { // right left sibling.left.color = parent.color; this.rotateRight(sibling); this.rotateLeft(parent); } } else { if (sibling.isOnLeft()) { // left right sibling.right!.color = parent.color; this.rotateLeft(sibling); this.rotateRight(parent); } else { // right right sibling.right!.color = sibling.color; sibling.color = parent.color; this.rotateLeft(parent); } } parent.color = 1; } else { // 2 black children sibling.color = 0; if (parent.color === 1) this.fixDoubleBlack(parent); else parent.color = 1; } } } } insert(data: T): boolean { // search for a position to insert let parent = this.root; while (parent) { if (this.lt(data, parent.data)) { if (!parent.left) break; else parent = parent.left; } else if (this.lt(parent.data, data)) { if (!parent.right) break; else parent = parent.right; } else break; } // insert node into parent const node = new RBTreeNode(data); if (!parent) this.root = node; else if (this.lt(node.data, parent.data)) parent.left = node; else if (this.lt(parent.data, node.data)) parent.right = node; else { parent.count++; return false; } node.parent = parent; this.fixAfterInsert(node); return true; } find(data: T): RBTreeNode<T> | null { let p = this.root; while (p) { if (this.lt(data, p.data)) { p = p.left; } else if (this.lt(p.data, data)) { p = p.right; } else break; } return p ?? null; } *inOrder(root: RBTreeNode<T> = this.root!): Generator<T, undefined, void> { if (!root) return; for (const v of this.inOrder(root.left!)) yield v; yield root.data; for (const v of this.inOrder(root.right!)) yield v; } *reverseInOrder(root: RBTreeNode<T> = this.root!): Generator<T, undefined, void> { if (!root) return; for (const v of this.reverseInOrder(root.right!)) yield v; yield root.data; for (const v of this.reverseInOrder(root.left!)) yield v; } } class TreeSet<T = number> { _size: number; tree: RBTree<T>; compare: Compare<T>; constructor( collection: T[] | Compare<T> = [], compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0), ) { if (typeof collection === 'function') { compare = collection; collection = []; } this._size = 0; this.compare = compare; this.tree = new RBTree(compare); for (const val of collection) this.add(val); } size(): number { return this._size; } has(val: T): boolean { return !!this.tree.find(val); } add(val: T): boolean { const successful = this.tree.insert(val); this._size += successful ? 1 : 0; return successful; } delete(val: T): boolean { const deleted = this.tree.deleteAll(val); this._size -= deleted ? 1 : 0; return deleted; } ceil(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(p.data, val) >= 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } floor(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(val, p.data) >= 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } higher(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(val, p.data) < 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } lower(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(p.data, val) < 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } first(): T | undefined { return this.tree.inOrder().next().value; } last(): T | undefined { return this.tree.reverseInOrder().next().value; } shift(): T | undefined { const first = this.first(); if (first === undefined) return undefined; this.delete(first); return first; } pop(): T | undefined { const last = this.last(); if (last === undefined) return undefined; this.delete(last); return last; } *[Symbol.iterator](): Generator<T, void, void> { for (const val of this.values()) yield val; } *keys(): Generator<T, void, void> { for (const val of this.values()) yield val; } *values(): Generator<T, undefined, void> { for (const val of this.tree.inOrder()) yield val; return undefined; } /** * Return a generator for reverse order traversing the set */ *rvalues(): Generator<T, undefined, void> { for (const val of this.tree.reverseInOrder()) yield val; return undefined; } } class TreeMultiSet<T = number> { _size: number; tree: RBTree<T>; compare: Compare<T>; constructor( collection: T[] | Compare<T> = [], compare: Compare<T> = (l: T, r: T) => (l < r ? -1 : l > r ? 1 : 0), ) { if (typeof collection === 'function') { compare = collection; collection = []; } this._size = 0; this.compare = compare; this.tree = new RBTree(compare); for (const val of collection) this.add(val); } size(): number { return this._size; } has(val: T): boolean { return !!this.tree.find(val); } add(val: T): boolean { const successful = this.tree.insert(val); this._size++; return successful; } delete(val: T): boolean { const successful = this.tree.delete(val); if (!successful) return false; this._size--; return true; } count(val: T): number { const node = this.tree.find(val); return node ? node.count : 0; } ceil(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(p.data, val) >= 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } floor(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(val, p.data) >= 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } higher(val: T): T | undefined { let p = this.tree.root; let higher = null; while (p) { if (this.compare(val, p.data) < 0) { higher = p; p = p.left; } else { p = p.right; } } return higher?.data; } lower(val: T): T | undefined { let p = this.tree.root; let lower = null; while (p) { if (this.compare(p.data, val) < 0) { lower = p; p = p.right; } else { p = p.left; } } return lower?.data; } first(): T | undefined { return this.tree.inOrder().next().value; } last(): T | undefined { return this.tree.reverseInOrder().next().value; } shift(): T | undefined { const first = this.first(); if (first === undefined) return undefined; this.delete(first); return first; } pop(): T | undefined { const last = this.last(); if (last === undefined) return undefined; this.delete(last); return last; } *[Symbol.iterator](): Generator<T, void, void> { yield* this.values(); } *keys(): Generator<T, void, void> { for (const val of this.values()) yield val; } *values(): Generator<T, undefined, void> { for (const val of this.tree.inOrder()) { let count = this.count(val); while (count--) yield val; } return undefined; } /** * Return a generator for reverse order traversing the multi-set */ *rvalues(): Generator<T, undefined, void> { for (const val of this.tree.reverseInOrder()) { let count = this.count(val); while (count--) yield val; } return undefined; } }
221
Maximal Square
Medium
<p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, <em>find the largest square containing only</em> <code>1</code>&#39;s <em>and return its area</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0221.Maximal%20Square/images/max1grid.jpg" style="width: 400px; height: 319px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0221.Maximal%20Square/images/max2grid.jpg" style="width: 165px; height: 165px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 300</code></li> <li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Array; Dynamic Programming; Matrix
C++
class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { int m = matrix.size(), n = matrix[0].size(); vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); int mx = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (matrix[i][j] == '1') { dp[i + 1][j + 1] = min(min(dp[i][j + 1], dp[i + 1][j]), dp[i][j]) + 1; mx = max(mx, dp[i + 1][j + 1]); } } } return mx * mx; } };
221
Maximal Square
Medium
<p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, <em>find the largest square containing only</em> <code>1</code>&#39;s <em>and return its area</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0221.Maximal%20Square/images/max1grid.jpg" style="width: 400px; height: 319px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0221.Maximal%20Square/images/max2grid.jpg" style="width: 165px; height: 165px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 300</code></li> <li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Array; Dynamic Programming; Matrix
C#
public class Solution { public int MaximalSquare(char[][] matrix) { int m = matrix.Length, n = matrix[0].Length; var dp = new int[m + 1, n + 1]; int mx = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (matrix[i][j] == '1') { dp[i + 1, j + 1] = Math.Min(Math.Min(dp[i, j + 1], dp[i + 1, j]), dp[i, j]) + 1; mx = Math.Max(mx, dp[i + 1, j + 1]); } } } return mx * mx; } }
221
Maximal Square
Medium
<p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, <em>find the largest square containing only</em> <code>1</code>&#39;s <em>and return its area</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0221.Maximal%20Square/images/max1grid.jpg" style="width: 400px; height: 319px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0221.Maximal%20Square/images/max2grid.jpg" style="width: 165px; height: 165px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 300</code></li> <li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Array; Dynamic Programming; Matrix
Go
func maximalSquare(matrix [][]byte) int { m, n := len(matrix), len(matrix[0]) dp := make([][]int, m+1) for i := 0; i <= m; i++ { dp[i] = make([]int, n+1) } mx := 0 for i := 0; i < m; i++ { for j := 0; j < n; j++ { if matrix[i][j] == '1' { dp[i+1][j+1] = min(min(dp[i][j+1], dp[i+1][j]), dp[i][j]) + 1 mx = max(mx, dp[i+1][j+1]) } } } return mx * mx }
221
Maximal Square
Medium
<p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, <em>find the largest square containing only</em> <code>1</code>&#39;s <em>and return its area</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0221.Maximal%20Square/images/max1grid.jpg" style="width: 400px; height: 319px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0221.Maximal%20Square/images/max2grid.jpg" style="width: 165px; height: 165px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 300</code></li> <li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Array; Dynamic Programming; Matrix
Java
class Solution { public int maximalSquare(char[][] matrix) { int m = matrix.length, n = matrix[0].length; int[][] dp = new int[m + 1][n + 1]; int mx = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (matrix[i][j] == '1') { dp[i + 1][j + 1] = Math.min(Math.min(dp[i][j + 1], dp[i + 1][j]), dp[i][j]) + 1; mx = Math.max(mx, dp[i + 1][j + 1]); } } } return mx * mx; } }
221
Maximal Square
Medium
<p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, <em>find the largest square containing only</em> <code>1</code>&#39;s <em>and return its area</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0221.Maximal%20Square/images/max1grid.jpg" style="width: 400px; height: 319px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 4 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0221.Maximal%20Square/images/max2grid.jpg" style="width: 165px; height: 165px;" /> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;]] <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> matrix = [[&quot;0&quot;]] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == matrix.length</code></li> <li><code>n == matrix[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 300</code></li> <li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li> </ul>
Array; Dynamic Programming; Matrix
Python
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m, n = len(matrix), len(matrix[0]) dp = [[0] * (n + 1) for _ in range(m + 1)] mx = 0 for i in range(m): for j in range(n): if matrix[i][j] == '1': dp[i + 1][j + 1] = min(dp[i][j + 1], dp[i + 1][j], dp[i][j]) + 1 mx = max(mx, dp[i + 1][j + 1]) return mx * mx
222
Count Complete Tree Nodes
Easy
<p>Given the <code>root</code> of a <strong>complete</strong> binary tree, return the number of the nodes in the tree.</p> <p>According to <strong><a href="http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees" target="_blank">Wikipedia</a></strong>, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between <code>1</code> and <code>2<sup>h</sup></code> nodes inclusive at the last level <code>h</code>.</p> <p>Design an algorithm that runs in less than&nbsp;<code data-stringify-type="code">O(n)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0222.Count%20Complete%20Tree%20Nodes/images/complete.jpg" style="width: 372px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6] <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 5 * 10<sup>4</sup></code></li> <li>The tree is guaranteed to be <strong>complete</strong>.</li> </ul>
Bit Manipulation; Tree; Binary Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int countNodes(TreeNode* root) { if (!root) { return 0; } return 1 + countNodes(root->left) + countNodes(root->right); } };
222
Count Complete Tree Nodes
Easy
<p>Given the <code>root</code> of a <strong>complete</strong> binary tree, return the number of the nodes in the tree.</p> <p>According to <strong><a href="http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees" target="_blank">Wikipedia</a></strong>, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between <code>1</code> and <code>2<sup>h</sup></code> nodes inclusive at the last level <code>h</code>.</p> <p>Design an algorithm that runs in less than&nbsp;<code data-stringify-type="code">O(n)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0222.Count%20Complete%20Tree%20Nodes/images/complete.jpg" style="width: 372px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6] <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 5 * 10<sup>4</sup></code></li> <li>The tree is guaranteed to be <strong>complete</strong>.</li> </ul>
Bit Manipulation; Tree; Binary Search; Binary Tree
C#
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { public int CountNodes(TreeNode root) { if (root == null) { return 0; } return 1 + CountNodes(root.left) + CountNodes(root.right); } }
222
Count Complete Tree Nodes
Easy
<p>Given the <code>root</code> of a <strong>complete</strong> binary tree, return the number of the nodes in the tree.</p> <p>According to <strong><a href="http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees" target="_blank">Wikipedia</a></strong>, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between <code>1</code> and <code>2<sup>h</sup></code> nodes inclusive at the last level <code>h</code>.</p> <p>Design an algorithm that runs in less than&nbsp;<code data-stringify-type="code">O(n)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0222.Count%20Complete%20Tree%20Nodes/images/complete.jpg" style="width: 372px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6] <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 5 * 10<sup>4</sup></code></li> <li>The tree is guaranteed to be <strong>complete</strong>.</li> </ul>
Bit Manipulation; Tree; Binary Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func countNodes(root *TreeNode) int { if root == nil { return 0 } return 1 + countNodes(root.Left) + countNodes(root.Right) }
222
Count Complete Tree Nodes
Easy
<p>Given the <code>root</code> of a <strong>complete</strong> binary tree, return the number of the nodes in the tree.</p> <p>According to <strong><a href="http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees" target="_blank">Wikipedia</a></strong>, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between <code>1</code> and <code>2<sup>h</sup></code> nodes inclusive at the last level <code>h</code>.</p> <p>Design an algorithm that runs in less than&nbsp;<code data-stringify-type="code">O(n)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0222.Count%20Complete%20Tree%20Nodes/images/complete.jpg" style="width: 372px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6] <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 5 * 10<sup>4</sup></code></li> <li>The tree is guaranteed to be <strong>complete</strong>.</li> </ul>
Bit Manipulation; Tree; Binary Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int countNodes(TreeNode root) { if (root == null) { return 0; } return 1 + countNodes(root.left) + countNodes(root.right); } }
222
Count Complete Tree Nodes
Easy
<p>Given the <code>root</code> of a <strong>complete</strong> binary tree, return the number of the nodes in the tree.</p> <p>According to <strong><a href="http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees" target="_blank">Wikipedia</a></strong>, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between <code>1</code> and <code>2<sup>h</sup></code> nodes inclusive at the last level <code>h</code>.</p> <p>Design an algorithm that runs in less than&nbsp;<code data-stringify-type="code">O(n)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0222.Count%20Complete%20Tree%20Nodes/images/complete.jpg" style="width: 372px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6] <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 5 * 10<sup>4</sup></code></li> <li>The tree is guaranteed to be <strong>complete</strong>.</li> </ul>
Bit Manipulation; Tree; Binary Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {number} */ var countNodes = function (root) { if (!root) { return 0; } return 1 + countNodes(root.left) + countNodes(root.right); };
222
Count Complete Tree Nodes
Easy
<p>Given the <code>root</code> of a <strong>complete</strong> binary tree, return the number of the nodes in the tree.</p> <p>According to <strong><a href="http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees" target="_blank">Wikipedia</a></strong>, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between <code>1</code> and <code>2<sup>h</sup></code> nodes inclusive at the last level <code>h</code>.</p> <p>Design an algorithm that runs in less than&nbsp;<code data-stringify-type="code">O(n)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0222.Count%20Complete%20Tree%20Nodes/images/complete.jpg" style="width: 372px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6] <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 5 * 10<sup>4</sup></code></li> <li>The tree is guaranteed to be <strong>complete</strong>.</li> </ul>
Bit Manipulation; Tree; Binary Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: if root is None: return 0 return 1 + self.countNodes(root.left) + self.countNodes(root.right)
222
Count Complete Tree Nodes
Easy
<p>Given the <code>root</code> of a <strong>complete</strong> binary tree, return the number of the nodes in the tree.</p> <p>According to <strong><a href="http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees" target="_blank">Wikipedia</a></strong>, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between <code>1</code> and <code>2<sup>h</sup></code> nodes inclusive at the last level <code>h</code>.</p> <p>Design an algorithm that runs in less than&nbsp;<code data-stringify-type="code">O(n)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0222.Count%20Complete%20Tree%20Nodes/images/complete.jpg" style="width: 372px; height: 302px;" /> <pre> <strong>Input:</strong> root = [1,2,3,4,5,6] <strong>Output:</strong> 6 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> 0 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 5 * 10<sup>4</sup></code></li> <li>The tree is guaranteed to be <strong>complete</strong>.</li> </ul>
Bit Manipulation; Tree; Binary Search; Binary Tree
Rust
use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn count_nodes(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { if let Some(node) = root { let node = node.borrow(); let left = Self::depth(&node.left); let right = Self::depth(&node.right); if left == right { Self::count_nodes(node.right.clone()) + (1 << left) } else { Self::count_nodes(node.left.clone()) + (1 << right) } } else { 0 } } fn depth(root: &Option<Rc<RefCell<TreeNode>>>) -> i32 { if let Some(node) = root { Self::depth(&node.borrow().left) + 1 } else { 0 } } }
223
Rectangle Area
Medium
<p>Given the coordinates of two <strong>rectilinear</strong> rectangles in a 2D plane, return <em>the total area covered by the two rectangles</em>.</p> <p>The first rectangle is defined by its <strong>bottom-left</strong> corner <code>(ax1, ay1)</code> and its <strong>top-right</strong> corner <code>(ax2, ay2)</code>.</p> <p>The second rectangle is defined by its <strong>bottom-left</strong> corner <code>(bx1, by1)</code> and its <strong>top-right</strong> corner <code>(bx2, by2)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="Rectangle Area" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0223.Rectangle%20Area/images/rectangle-plane.png" style="width: 700px; height: 365px;" /> <pre> <strong>Input:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2 <strong>Output:</strong> 45 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 <strong>Output:</strong> 16 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>4</sup> &lt;= ax1 &lt;= ax2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= ay1 &lt;= ay2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= bx1 &lt;= bx2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= by1 &lt;= by2 &lt;= 10<sup>4</sup></code></li> </ul>
Geometry; Math
C++
class Solution { public: int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { int a = (ax2 - ax1) * (ay2 - ay1); int b = (bx2 - bx1) * (by2 - by1); int width = min(ax2, bx2) - max(ax1, bx1); int height = min(ay2, by2) - max(ay1, by1); return a + b - max(height, 0) * max(width, 0); } };
223
Rectangle Area
Medium
<p>Given the coordinates of two <strong>rectilinear</strong> rectangles in a 2D plane, return <em>the total area covered by the two rectangles</em>.</p> <p>The first rectangle is defined by its <strong>bottom-left</strong> corner <code>(ax1, ay1)</code> and its <strong>top-right</strong> corner <code>(ax2, ay2)</code>.</p> <p>The second rectangle is defined by its <strong>bottom-left</strong> corner <code>(bx1, by1)</code> and its <strong>top-right</strong> corner <code>(bx2, by2)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="Rectangle Area" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0223.Rectangle%20Area/images/rectangle-plane.png" style="width: 700px; height: 365px;" /> <pre> <strong>Input:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2 <strong>Output:</strong> 45 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 <strong>Output:</strong> 16 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>4</sup> &lt;= ax1 &lt;= ax2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= ay1 &lt;= ay2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= bx1 &lt;= bx2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= by1 &lt;= by2 &lt;= 10<sup>4</sup></code></li> </ul>
Geometry; Math
C#
public class Solution { public int ComputeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { int a = (ax2 - ax1) * (ay2 - ay1); int b = (bx2 - bx1) * (by2 - by1); int width = Math.Min(ax2, bx2) - Math.Max(ax1, bx1); int height = Math.Min(ay2, by2) - Math.Max(ay1, by1); return a + b - Math.Max(height, 0) * Math.Max(width, 0); } }
223
Rectangle Area
Medium
<p>Given the coordinates of two <strong>rectilinear</strong> rectangles in a 2D plane, return <em>the total area covered by the two rectangles</em>.</p> <p>The first rectangle is defined by its <strong>bottom-left</strong> corner <code>(ax1, ay1)</code> and its <strong>top-right</strong> corner <code>(ax2, ay2)</code>.</p> <p>The second rectangle is defined by its <strong>bottom-left</strong> corner <code>(bx1, by1)</code> and its <strong>top-right</strong> corner <code>(bx2, by2)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="Rectangle Area" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0223.Rectangle%20Area/images/rectangle-plane.png" style="width: 700px; height: 365px;" /> <pre> <strong>Input:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2 <strong>Output:</strong> 45 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 <strong>Output:</strong> 16 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>4</sup> &lt;= ax1 &lt;= ax2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= ay1 &lt;= ay2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= bx1 &lt;= bx2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= by1 &lt;= by2 &lt;= 10<sup>4</sup></code></li> </ul>
Geometry; Math
Go
func computeArea(ax1 int, ay1 int, ax2 int, ay2 int, bx1 int, by1 int, bx2 int, by2 int) int { a := (ax2 - ax1) * (ay2 - ay1) b := (bx2 - bx1) * (by2 - by1) width := min(ax2, bx2) - max(ax1, bx1) height := min(ay2, by2) - max(ay1, by1) return a + b - max(height, 0)*max(width, 0) }
223
Rectangle Area
Medium
<p>Given the coordinates of two <strong>rectilinear</strong> rectangles in a 2D plane, return <em>the total area covered by the two rectangles</em>.</p> <p>The first rectangle is defined by its <strong>bottom-left</strong> corner <code>(ax1, ay1)</code> and its <strong>top-right</strong> corner <code>(ax2, ay2)</code>.</p> <p>The second rectangle is defined by its <strong>bottom-left</strong> corner <code>(bx1, by1)</code> and its <strong>top-right</strong> corner <code>(bx2, by2)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="Rectangle Area" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0223.Rectangle%20Area/images/rectangle-plane.png" style="width: 700px; height: 365px;" /> <pre> <strong>Input:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2 <strong>Output:</strong> 45 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 <strong>Output:</strong> 16 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>4</sup> &lt;= ax1 &lt;= ax2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= ay1 &lt;= ay2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= bx1 &lt;= bx2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= by1 &lt;= by2 &lt;= 10<sup>4</sup></code></li> </ul>
Geometry; Math
Java
class Solution { public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { int a = (ax2 - ax1) * (ay2 - ay1); int b = (bx2 - bx1) * (by2 - by1); int width = Math.min(ax2, bx2) - Math.max(ax1, bx1); int height = Math.min(ay2, by2) - Math.max(ay1, by1); return a + b - Math.max(height, 0) * Math.max(width, 0); } }
223
Rectangle Area
Medium
<p>Given the coordinates of two <strong>rectilinear</strong> rectangles in a 2D plane, return <em>the total area covered by the two rectangles</em>.</p> <p>The first rectangle is defined by its <strong>bottom-left</strong> corner <code>(ax1, ay1)</code> and its <strong>top-right</strong> corner <code>(ax2, ay2)</code>.</p> <p>The second rectangle is defined by its <strong>bottom-left</strong> corner <code>(bx1, by1)</code> and its <strong>top-right</strong> corner <code>(bx2, by2)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="Rectangle Area" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0223.Rectangle%20Area/images/rectangle-plane.png" style="width: 700px; height: 365px;" /> <pre> <strong>Input:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2 <strong>Output:</strong> 45 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 <strong>Output:</strong> 16 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>4</sup> &lt;= ax1 &lt;= ax2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= ay1 &lt;= ay2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= bx1 &lt;= bx2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= by1 &lt;= by2 &lt;= 10<sup>4</sup></code></li> </ul>
Geometry; Math
Python
class Solution: def computeArea( self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int, ) -> int: a = (ax2 - ax1) * (ay2 - ay1) b = (bx2 - bx1) * (by2 - by1) width = min(ax2, bx2) - max(ax1, bx1) height = min(ay2, by2) - max(ay1, by1) return a + b - max(height, 0) * max(width, 0)
223
Rectangle Area
Medium
<p>Given the coordinates of two <strong>rectilinear</strong> rectangles in a 2D plane, return <em>the total area covered by the two rectangles</em>.</p> <p>The first rectangle is defined by its <strong>bottom-left</strong> corner <code>(ax1, ay1)</code> and its <strong>top-right</strong> corner <code>(ax2, ay2)</code>.</p> <p>The second rectangle is defined by its <strong>bottom-left</strong> corner <code>(bx1, by1)</code> and its <strong>top-right</strong> corner <code>(bx2, by2)</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="Rectangle Area" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0223.Rectangle%20Area/images/rectangle-plane.png" style="width: 700px; height: 365px;" /> <pre> <strong>Input:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2 <strong>Output:</strong> 45 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 <strong>Output:</strong> 16 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>4</sup> &lt;= ax1 &lt;= ax2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= ay1 &lt;= ay2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= bx1 &lt;= bx2 &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>4</sup> &lt;= by1 &lt;= by2 &lt;= 10<sup>4</sup></code></li> </ul>
Geometry; Math
TypeScript
function computeArea( ax1: number, ay1: number, ax2: number, ay2: number, bx1: number, by1: number, bx2: number, by2: number, ): number { const a = (ax2 - ax1) * (ay2 - ay1); const b = (bx2 - bx1) * (by2 - by1); const width = Math.min(ax2, bx2) - Math.max(ax1, bx1); const height = Math.min(ay2, by2) - Math.max(ay1, by1); return a + b - Math.max(width, 0) * Math.max(height, 0); }
224
Basic Calculator
Hard
<p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p> <p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1 + 1&quot; <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot; 2-1 + 2 &quot; <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;(1+(4+5+2)-3)+(6+8)&quot; <strong>Output:</strong> 23 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of digits, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li> <li><code>s</code> represents a valid expression.</li> <li><code>&#39;+&#39;</code> is <strong>not</strong> used as a unary operation (i.e., <code>&quot;+1&quot;</code> and <code>&quot;+(2 + 3)&quot;</code> is invalid).</li> <li><code>&#39;-&#39;</code> could be used as a unary operation (i.e., <code>&quot;-1&quot;</code> and <code>&quot;-(2 + 3)&quot;</code> is valid).</li> <li>There will be no two consecutive operators in the input.</li> <li>Every number and running calculation will fit in a signed 32-bit integer.</li> </ul>
Stack; Recursion; Math; String
C++
class Solution { public: int calculate(string s) { stack<int> stk; int ans = 0, sign = 1; int n = s.size(); for (int i = 0; i < n; ++i) { if (isdigit(s[i])) { int x = 0; int j = i; while (j < n && isdigit(s[j])) { x = x * 10 + (s[j] - '0'); ++j; } ans += sign * x; i = j - 1; } else if (s[i] == '+') { sign = 1; } else if (s[i] == '-') { sign = -1; } else if (s[i] == '(') { stk.push(ans); stk.push(sign); ans = 0; sign = 1; } else if (s[i] == ')') { ans *= stk.top(); stk.pop(); ans += stk.top(); stk.pop(); } } return ans; } };
224
Basic Calculator
Hard
<p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p> <p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1 + 1&quot; <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot; 2-1 + 2 &quot; <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;(1+(4+5+2)-3)+(6+8)&quot; <strong>Output:</strong> 23 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of digits, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li> <li><code>s</code> represents a valid expression.</li> <li><code>&#39;+&#39;</code> is <strong>not</strong> used as a unary operation (i.e., <code>&quot;+1&quot;</code> and <code>&quot;+(2 + 3)&quot;</code> is invalid).</li> <li><code>&#39;-&#39;</code> could be used as a unary operation (i.e., <code>&quot;-1&quot;</code> and <code>&quot;-(2 + 3)&quot;</code> is valid).</li> <li>There will be no two consecutive operators in the input.</li> <li>Every number and running calculation will fit in a signed 32-bit integer.</li> </ul>
Stack; Recursion; Math; String
C#
public class Solution { public int Calculate(string s) { var stk = new Stack<int>(); int sign = 1; int n = s.Length; int ans = 0; for (int i = 0; i < n; ++i) { if (s[i] == ' ') { continue; } if (s[i] == '+') { sign = 1; } else if (s[i] == '-') { sign = -1; } else if (s[i] == '(') { stk.Push(ans); stk.Push(sign); ans = 0; sign = 1; } else if (s[i] == ')') { ans *= stk.Pop(); ans += stk.Pop(); } else { int num = 0; while (i < n && char.IsDigit(s[i])) { num = num * 10 + s[i] - '0'; ++i; } --i; ans += sign * num; } } return ans; } }
224
Basic Calculator
Hard
<p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p> <p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1 + 1&quot; <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot; 2-1 + 2 &quot; <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;(1+(4+5+2)-3)+(6+8)&quot; <strong>Output:</strong> 23 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of digits, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li> <li><code>s</code> represents a valid expression.</li> <li><code>&#39;+&#39;</code> is <strong>not</strong> used as a unary operation (i.e., <code>&quot;+1&quot;</code> and <code>&quot;+(2 + 3)&quot;</code> is invalid).</li> <li><code>&#39;-&#39;</code> could be used as a unary operation (i.e., <code>&quot;-1&quot;</code> and <code>&quot;-(2 + 3)&quot;</code> is valid).</li> <li>There will be no two consecutive operators in the input.</li> <li>Every number and running calculation will fit in a signed 32-bit integer.</li> </ul>
Stack; Recursion; Math; String
Go
func calculate(s string) (ans int) { stk := []int{} sign := 1 n := len(s) for i := 0; i < n; i++ { switch s[i] { case ' ': case '+': sign = 1 case '-': sign = -1 case '(': stk = append(stk, ans) stk = append(stk, sign) ans, sign = 0, 1 case ')': ans *= stk[len(stk)-1] stk = stk[:len(stk)-1] ans += stk[len(stk)-1] stk = stk[:len(stk)-1] default: x := 0 j := i for ; j < n && '0' <= s[j] && s[j] <= '9'; j++ { x = x*10 + int(s[j]-'0') } ans += sign * x i = j - 1 } } return }
224
Basic Calculator
Hard
<p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p> <p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1 + 1&quot; <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot; 2-1 + 2 &quot; <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;(1+(4+5+2)-3)+(6+8)&quot; <strong>Output:</strong> 23 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of digits, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li> <li><code>s</code> represents a valid expression.</li> <li><code>&#39;+&#39;</code> is <strong>not</strong> used as a unary operation (i.e., <code>&quot;+1&quot;</code> and <code>&quot;+(2 + 3)&quot;</code> is invalid).</li> <li><code>&#39;-&#39;</code> could be used as a unary operation (i.e., <code>&quot;-1&quot;</code> and <code>&quot;-(2 + 3)&quot;</code> is valid).</li> <li>There will be no two consecutive operators in the input.</li> <li>Every number and running calculation will fit in a signed 32-bit integer.</li> </ul>
Stack; Recursion; Math; String
Java
class Solution { public int calculate(String s) { Deque<Integer> stk = new ArrayDeque<>(); int sign = 1; int ans = 0; int n = s.length(); for (int i = 0; i < n; ++i) { char c = s.charAt(i); if (Character.isDigit(c)) { int j = i; int x = 0; while (j < n && Character.isDigit(s.charAt(j))) { x = x * 10 + s.charAt(j) - '0'; j++; } ans += sign * x; i = j - 1; } else if (c == '+') { sign = 1; } else if (c == '-') { sign = -1; } else if (c == '(') { stk.push(ans); stk.push(sign); ans = 0; sign = 1; } else if (c == ')') { ans = stk.pop() * ans + stk.pop(); } } return ans; } }
224
Basic Calculator
Hard
<p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p> <p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1 + 1&quot; <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot; 2-1 + 2 &quot; <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;(1+(4+5+2)-3)+(6+8)&quot; <strong>Output:</strong> 23 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of digits, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li> <li><code>s</code> represents a valid expression.</li> <li><code>&#39;+&#39;</code> is <strong>not</strong> used as a unary operation (i.e., <code>&quot;+1&quot;</code> and <code>&quot;+(2 + 3)&quot;</code> is invalid).</li> <li><code>&#39;-&#39;</code> could be used as a unary operation (i.e., <code>&quot;-1&quot;</code> and <code>&quot;-(2 + 3)&quot;</code> is valid).</li> <li>There will be no two consecutive operators in the input.</li> <li>Every number and running calculation will fit in a signed 32-bit integer.</li> </ul>
Stack; Recursion; Math; String
Python
class Solution: def calculate(self, s: str) -> int: stk = [] ans, sign = 0, 1 i, n = 0, len(s) while i < n: if s[i].isdigit(): x = 0 j = i while j < n and s[j].isdigit(): x = x * 10 + int(s[j]) j += 1 ans += sign * x i = j - 1 elif s[i] == "+": sign = 1 elif s[i] == "-": sign = -1 elif s[i] == "(": stk.append(ans) stk.append(sign) ans, sign = 0, 1 elif s[i] == ")": ans = stk.pop() * ans + stk.pop() i += 1 return ans
224
Basic Calculator
Hard
<p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p> <p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;1 + 1&quot; <strong>Output:</strong> 2 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot; 2-1 + 2 &quot; <strong>Output:</strong> 3 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;(1+(4+5+2)-3)+(6+8)&quot; <strong>Output:</strong> 23 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of digits, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li> <li><code>s</code> represents a valid expression.</li> <li><code>&#39;+&#39;</code> is <strong>not</strong> used as a unary operation (i.e., <code>&quot;+1&quot;</code> and <code>&quot;+(2 + 3)&quot;</code> is invalid).</li> <li><code>&#39;-&#39;</code> could be used as a unary operation (i.e., <code>&quot;-1&quot;</code> and <code>&quot;-(2 + 3)&quot;</code> is valid).</li> <li>There will be no two consecutive operators in the input.</li> <li>Every number and running calculation will fit in a signed 32-bit integer.</li> </ul>
Stack; Recursion; Math; String
TypeScript
function calculate(s: string): number { const stk: number[] = []; let sign = 1; let ans = 0; const n = s.length; for (let i = 0; i < n; ++i) { if (s[i] === ' ') { continue; } if (s[i] === '+') { sign = 1; } else if (s[i] === '-') { sign = -1; } else if (s[i] === '(') { stk.push(ans); stk.push(sign); ans = 0; sign = 1; } else if (s[i] === ')') { ans *= stk.pop() as number; ans += stk.pop() as number; } else { let x = 0; let j = i; for (; j < n && !isNaN(Number(s[j])) && s[j] !== ' '; ++j) { x = x * 10 + (s[j].charCodeAt(0) - '0'.charCodeAt(0)); } ans += sign * x; i = j - 1; } } return ans; }
225
Implement Stack using Queues
Easy
<p>Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (<code>push</code>, <code>top</code>, <code>pop</code>, and <code>empty</code>).</p> <p>Implement the <code>MyStack</code> class:</p> <ul> <li><code>void push(int x)</code> Pushes element x to the top of the stack.</li> <li><code>int pop()</code> Removes the element on the top of the stack and returns it.</li> <li><code>int top()</code> Returns the element on the top of the stack.</li> <li><code>boolean empty()</code> Returns <code>true</code> if the stack is empty, <code>false</code> otherwise.</li> </ul> <p><b>Notes:</b></p> <ul> <li>You must use <strong>only</strong> standard operations of a queue, which means that only <code>push to back</code>, <code>peek/pop from front</code>, <code>size</code> and <code>is empty</code> operations are valid.</li> <li>Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue&#39;s standard operations.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyStack&quot;, &quot;push&quot;, &quot;push&quot;, &quot;top&quot;, &quot;pop&quot;, &quot;empty&quot;] [[], [1], [2], [], [], []] <strong>Output</strong> [null, null, null, 2, 2, false] <strong>Explanation</strong> MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 9</code></li> <li>At most <code>100</code> calls will be made to <code>push</code>, <code>pop</code>, <code>top</code>, and <code>empty</code>.</li> <li>All the calls to <code>pop</code> and <code>top</code> are valid.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you implement the stack using only one queue?</p>
Stack; Design; Queue
C++
class MyStack { public: MyStack() { } void push(int x) { q2.push(x); while (!q1.empty()) { q2.push(q1.front()); q1.pop(); } swap(q1, q2); } int pop() { int x = q1.front(); q1.pop(); return x; } int top() { return q1.front(); } bool empty() { return q1.empty(); } private: queue<int> q1; queue<int> q2; }; /** * Your MyStack object will be instantiated and called as such: * MyStack* obj = new MyStack(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->top(); * bool param_4 = obj->empty(); */
225
Implement Stack using Queues
Easy
<p>Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (<code>push</code>, <code>top</code>, <code>pop</code>, and <code>empty</code>).</p> <p>Implement the <code>MyStack</code> class:</p> <ul> <li><code>void push(int x)</code> Pushes element x to the top of the stack.</li> <li><code>int pop()</code> Removes the element on the top of the stack and returns it.</li> <li><code>int top()</code> Returns the element on the top of the stack.</li> <li><code>boolean empty()</code> Returns <code>true</code> if the stack is empty, <code>false</code> otherwise.</li> </ul> <p><b>Notes:</b></p> <ul> <li>You must use <strong>only</strong> standard operations of a queue, which means that only <code>push to back</code>, <code>peek/pop from front</code>, <code>size</code> and <code>is empty</code> operations are valid.</li> <li>Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue&#39;s standard operations.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyStack&quot;, &quot;push&quot;, &quot;push&quot;, &quot;top&quot;, &quot;pop&quot;, &quot;empty&quot;] [[], [1], [2], [], [], []] <strong>Output</strong> [null, null, null, 2, 2, false] <strong>Explanation</strong> MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 9</code></li> <li>At most <code>100</code> calls will be made to <code>push</code>, <code>pop</code>, <code>top</code>, and <code>empty</code>.</li> <li>All the calls to <code>pop</code> and <code>top</code> are valid.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you implement the stack using only one queue?</p>
Stack; Design; Queue
Go
type MyStack struct { q1 []int q2 []int } func Constructor() MyStack { return MyStack{} } func (this *MyStack) Push(x int) { this.q2 = append(this.q2, x) for len(this.q1) > 0 { this.q2 = append(this.q2, this.q1[0]) this.q1 = this.q1[1:] } this.q1, this.q2 = this.q2, this.q1 } func (this *MyStack) Pop() int { x := this.q1[0] this.q1 = this.q1[1:] return x } func (this *MyStack) Top() int { return this.q1[0] } func (this *MyStack) Empty() bool { return len(this.q1) == 0 } /** * Your MyStack object will be instantiated and called as such: * obj := Constructor(); * obj.Push(x); * param_2 := obj.Pop(); * param_3 := obj.Top(); * param_4 := obj.Empty(); */
225
Implement Stack using Queues
Easy
<p>Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (<code>push</code>, <code>top</code>, <code>pop</code>, and <code>empty</code>).</p> <p>Implement the <code>MyStack</code> class:</p> <ul> <li><code>void push(int x)</code> Pushes element x to the top of the stack.</li> <li><code>int pop()</code> Removes the element on the top of the stack and returns it.</li> <li><code>int top()</code> Returns the element on the top of the stack.</li> <li><code>boolean empty()</code> Returns <code>true</code> if the stack is empty, <code>false</code> otherwise.</li> </ul> <p><b>Notes:</b></p> <ul> <li>You must use <strong>only</strong> standard operations of a queue, which means that only <code>push to back</code>, <code>peek/pop from front</code>, <code>size</code> and <code>is empty</code> operations are valid.</li> <li>Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue&#39;s standard operations.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyStack&quot;, &quot;push&quot;, &quot;push&quot;, &quot;top&quot;, &quot;pop&quot;, &quot;empty&quot;] [[], [1], [2], [], [], []] <strong>Output</strong> [null, null, null, 2, 2, false] <strong>Explanation</strong> MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 9</code></li> <li>At most <code>100</code> calls will be made to <code>push</code>, <code>pop</code>, <code>top</code>, and <code>empty</code>.</li> <li>All the calls to <code>pop</code> and <code>top</code> are valid.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you implement the stack using only one queue?</p>
Stack; Design; Queue
Java
class MyStack { private Deque<Integer> q1 = new ArrayDeque<>(); private Deque<Integer> q2 = new ArrayDeque<>(); public MyStack() { } public void push(int x) { q2.offer(x); while (!q1.isEmpty()) { q2.offer(q1.poll()); } Deque<Integer> q = q1; q1 = q2; q2 = q; } public int pop() { return q1.poll(); } public int top() { return q1.peek(); } public boolean empty() { return q1.isEmpty(); } } /** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * boolean param_4 = obj.empty(); */
225
Implement Stack using Queues
Easy
<p>Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (<code>push</code>, <code>top</code>, <code>pop</code>, and <code>empty</code>).</p> <p>Implement the <code>MyStack</code> class:</p> <ul> <li><code>void push(int x)</code> Pushes element x to the top of the stack.</li> <li><code>int pop()</code> Removes the element on the top of the stack and returns it.</li> <li><code>int top()</code> Returns the element on the top of the stack.</li> <li><code>boolean empty()</code> Returns <code>true</code> if the stack is empty, <code>false</code> otherwise.</li> </ul> <p><b>Notes:</b></p> <ul> <li>You must use <strong>only</strong> standard operations of a queue, which means that only <code>push to back</code>, <code>peek/pop from front</code>, <code>size</code> and <code>is empty</code> operations are valid.</li> <li>Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue&#39;s standard operations.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyStack&quot;, &quot;push&quot;, &quot;push&quot;, &quot;top&quot;, &quot;pop&quot;, &quot;empty&quot;] [[], [1], [2], [], [], []] <strong>Output</strong> [null, null, null, 2, 2, false] <strong>Explanation</strong> MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 9</code></li> <li>At most <code>100</code> calls will be made to <code>push</code>, <code>pop</code>, <code>top</code>, and <code>empty</code>.</li> <li>All the calls to <code>pop</code> and <code>top</code> are valid.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you implement the stack using only one queue?</p>
Stack; Design; Queue
Python
class MyStack: def __init__(self): self.q1 = deque() self.q2 = deque() def push(self, x: int) -> None: self.q2.append(x) while self.q1: self.q2.append(self.q1.popleft()) self.q1, self.q2 = self.q2, self.q1 def pop(self) -> int: return self.q1.popleft() def top(self) -> int: return self.q1[0] def empty(self) -> bool: return len(self.q1) == 0 # Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty()
225
Implement Stack using Queues
Easy
<p>Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (<code>push</code>, <code>top</code>, <code>pop</code>, and <code>empty</code>).</p> <p>Implement the <code>MyStack</code> class:</p> <ul> <li><code>void push(int x)</code> Pushes element x to the top of the stack.</li> <li><code>int pop()</code> Removes the element on the top of the stack and returns it.</li> <li><code>int top()</code> Returns the element on the top of the stack.</li> <li><code>boolean empty()</code> Returns <code>true</code> if the stack is empty, <code>false</code> otherwise.</li> </ul> <p><b>Notes:</b></p> <ul> <li>You must use <strong>only</strong> standard operations of a queue, which means that only <code>push to back</code>, <code>peek/pop from front</code>, <code>size</code> and <code>is empty</code> operations are valid.</li> <li>Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue&#39;s standard operations.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyStack&quot;, &quot;push&quot;, &quot;push&quot;, &quot;top&quot;, &quot;pop&quot;, &quot;empty&quot;] [[], [1], [2], [], [], []] <strong>Output</strong> [null, null, null, 2, 2, false] <strong>Explanation</strong> MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 9</code></li> <li>At most <code>100</code> calls will be made to <code>push</code>, <code>pop</code>, <code>top</code>, and <code>empty</code>.</li> <li>All the calls to <code>pop</code> and <code>top</code> are valid.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you implement the stack using only one queue?</p>
Stack; Design; Queue
Rust
use std::collections::VecDeque; struct MyStack { /// There could only be two status at all time /// 1. One contains N elements, the other is empty /// 2. One contains N - 1 elements, the other contains exactly 1 element q_1: VecDeque<i32>, q_2: VecDeque<i32>, // Either 1 or 2, originally begins from 1 index: i32, } impl MyStack { fn new() -> Self { Self { q_1: VecDeque::new(), q_2: VecDeque::new(), index: 1, } } fn move_data(&mut self) { // Always move from q1 to q2 assert!(self.q_2.len() == 1); while !self.q_1.is_empty() { self.q_2.push_back(self.q_1.pop_front().unwrap()); } let tmp = self.q_1.clone(); self.q_1 = self.q_2.clone(); self.q_2 = tmp; } fn push(&mut self, x: i32) { self.q_2.push_back(x); self.move_data(); } fn pop(&mut self) -> i32 { self.q_1.pop_front().unwrap() } fn top(&mut self) -> i32 { *self.q_1.front().unwrap() } fn empty(&self) -> bool { self.q_1.is_empty() } }
225
Implement Stack using Queues
Easy
<p>Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (<code>push</code>, <code>top</code>, <code>pop</code>, and <code>empty</code>).</p> <p>Implement the <code>MyStack</code> class:</p> <ul> <li><code>void push(int x)</code> Pushes element x to the top of the stack.</li> <li><code>int pop()</code> Removes the element on the top of the stack and returns it.</li> <li><code>int top()</code> Returns the element on the top of the stack.</li> <li><code>boolean empty()</code> Returns <code>true</code> if the stack is empty, <code>false</code> otherwise.</li> </ul> <p><b>Notes:</b></p> <ul> <li>You must use <strong>only</strong> standard operations of a queue, which means that only <code>push to back</code>, <code>peek/pop from front</code>, <code>size</code> and <code>is empty</code> operations are valid.</li> <li>Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue&#39;s standard operations.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyStack&quot;, &quot;push&quot;, &quot;push&quot;, &quot;top&quot;, &quot;pop&quot;, &quot;empty&quot;] [[], [1], [2], [], [], []] <strong>Output</strong> [null, null, null, 2, 2, false] <strong>Explanation</strong> MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 9</code></li> <li>At most <code>100</code> calls will be made to <code>push</code>, <code>pop</code>, <code>top</code>, and <code>empty</code>.</li> <li>All the calls to <code>pop</code> and <code>top</code> are valid.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you implement the stack using only one queue?</p>
Stack; Design; Queue
TypeScript
class MyStack { q1: number[] = []; q2: number[] = []; constructor() {} push(x: number): void { this.q2.push(x); while (this.q1.length) { this.q2.push(this.q1.shift()!); } [this.q1, this.q2] = [this.q2, this.q1]; } pop(): number { return this.q1.shift()!; } top(): number { return this.q1[0]; } empty(): boolean { return this.q1.length === 0; } } /** * Your MyStack object will be instantiated and called as such: * var obj = new MyStack() * obj.push(x) * var param_2 = obj.pop() * var param_3 = obj.top() * var param_4 = obj.empty() */
226
Invert Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, invert the tree, and return <em>its root</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert1-tree.jpg" style="width: 500px; height: 165px;" /> <pre> <strong>Input:</strong> root = [4,2,7,1,3,6,9] <strong>Output:</strong> [4,7,2,9,6,3,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert2-tree.jpg" style="width: 500px; height: 120px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [2,3,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* invertTree(TreeNode* root) { if (!root) { return root; } TreeNode* l = invertTree(root->left); TreeNode* r = invertTree(root->right); root->left = r; root->right = l; return root; } };
226
Invert Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, invert the tree, and return <em>its root</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert1-tree.jpg" style="width: 500px; height: 165px;" /> <pre> <strong>Input:</strong> root = [4,2,7,1,3,6,9] <strong>Output:</strong> [4,7,2,9,6,3,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert2-tree.jpg" style="width: 500px; height: 120px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [2,3,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
C#
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { public TreeNode InvertTree(TreeNode root) { if (root == null) { return null; } TreeNode l = InvertTree(root.left); TreeNode r = InvertTree(root.right); root.left = r; root.right = l; return root; } }
226
Invert Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, invert the tree, and return <em>its root</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert1-tree.jpg" style="width: 500px; height: 165px;" /> <pre> <strong>Input:</strong> root = [4,2,7,1,3,6,9] <strong>Output:</strong> [4,7,2,9,6,3,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert2-tree.jpg" style="width: 500px; height: 120px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [2,3,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func invertTree(root *TreeNode) *TreeNode { if root == nil { return root } l, r := invertTree(root.Left), invertTree(root.Right) root.Left, root.Right = r, l return root }
226
Invert Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, invert the tree, and return <em>its root</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert1-tree.jpg" style="width: 500px; height: 165px;" /> <pre> <strong>Input:</strong> root = [4,2,7,1,3,6,9] <strong>Output:</strong> [4,7,2,9,6,3,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert2-tree.jpg" style="width: 500px; height: 120px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [2,3,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } TreeNode l = invertTree(root.left); TreeNode r = invertTree(root.right); root.left = r; root.right = l; return root; } }
226
Invert Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, invert the tree, and return <em>its root</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert1-tree.jpg" style="width: 500px; height: 165px;" /> <pre> <strong>Input:</strong> root = [4,2,7,1,3,6,9] <strong>Output:</strong> [4,7,2,9,6,3,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert2-tree.jpg" style="width: 500px; height: 120px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [2,3,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {TreeNode} */ var invertTree = function (root) { if (!root) { return root; } const l = invertTree(root.left); const r = invertTree(root.right); root.left = r; root.right = l; return root; };
226
Invert Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, invert the tree, and return <em>its root</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert1-tree.jpg" style="width: 500px; height: 165px;" /> <pre> <strong>Input:</strong> root = [4,2,7,1,3,6,9] <strong>Output:</strong> [4,7,2,9,6,3,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert2-tree.jpg" style="width: 500px; height: 120px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [2,3,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root is None: return None l, r = self.invertTree(root.left), self.invertTree(root.right) root.left, root.right = r, l return root
226
Invert Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, invert the tree, and return <em>its root</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert1-tree.jpg" style="width: 500px; height: 165px;" /> <pre> <strong>Input:</strong> root = [4,2,7,1,3,6,9] <strong>Output:</strong> [4,7,2,9,6,3,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert2-tree.jpg" style="width: 500px; height: 120px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [2,3,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn invert_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> { if let Some(node) = root.clone() { let mut node = node.borrow_mut(); let left = node.left.take(); let right = node.right.take(); node.left = Self::invert_tree(right); node.right = Self::invert_tree(left); } root } }
226
Invert Binary Tree
Easy
<p>Given the <code>root</code> of a binary tree, invert the tree, and return <em>its root</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert1-tree.jpg" style="width: 500px; height: 165px;" /> <pre> <strong>Input:</strong> root = [4,2,7,1,3,6,9] <strong>Output:</strong> [4,7,2,9,6,3,1] </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0226.Invert%20Binary%20Tree/images/invert2-tree.jpg" style="width: 500px; height: 120px;" /> <pre> <strong>Input:</strong> root = [2,1,3] <strong>Output:</strong> [2,3,1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> root = [] <strong>Output:</strong> [] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li> <li><code>-100 &lt;= Node.val &lt;= 100</code></li> </ul>
Tree; Depth-First Search; Breadth-First Search; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function invertTree(root: TreeNode | null): TreeNode | null { if (!root) { return root; } const l = invertTree(root.left); const r = invertTree(root.right); root.left = r; root.right = l; return root; }
227
Basic Calculator II
Medium
<p>Given a string <code>s</code> which represents an expression, <em>evaluate this expression and return its value</em>.&nbsp;</p> <p>The integer division should truncate toward zero.</p> <p>You may assume that the given expression is always valid. All intermediate results will be in the range of <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>.</p> <p><strong>Note:</strong> You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "3+2*2" <strong>Output:</strong> 7 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = " 3/2 " <strong>Output:</strong> 1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> s = " 3+5 / 2 " <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of integers and operators <code>(&#39;+&#39;, &#39;-&#39;, &#39;*&#39;, &#39;/&#39;)</code> separated by some number of spaces.</li> <li><code>s</code> represents <strong>a valid expression</strong>.</li> <li>All the integers in the expression are non-negative integers in the range <code>[0, 2<sup>31</sup> - 1]</code>.</li> <li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit integer</strong>.</li> </ul>
Stack; Math; String
C++
class Solution { public: int calculate(string s) { int v = 0, n = s.size(); char sign = '+'; stack<int> stk; for (int i = 0; i < n; ++i) { char c = s[i]; if (isdigit(c)) v = v * 10 + (c - '0'); if (i == n - 1 || c == '+' || c == '-' || c == '*' || c == '/') { if (sign == '+') stk.push(v); else if (sign == '-') stk.push(-v); else if (sign == '*') { int t = stk.top(); stk.pop(); stk.push(t * v); } else { int t = stk.top(); stk.pop(); stk.push(t / v); } sign = c; v = 0; } } int ans = 0; while (!stk.empty()) { ans += stk.top(); stk.pop(); } return ans; } };
227
Basic Calculator II
Medium
<p>Given a string <code>s</code> which represents an expression, <em>evaluate this expression and return its value</em>.&nbsp;</p> <p>The integer division should truncate toward zero.</p> <p>You may assume that the given expression is always valid. All intermediate results will be in the range of <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>.</p> <p><strong>Note:</strong> You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "3+2*2" <strong>Output:</strong> 7 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = " 3/2 " <strong>Output:</strong> 1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> s = " 3+5 / 2 " <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of integers and operators <code>(&#39;+&#39;, &#39;-&#39;, &#39;*&#39;, &#39;/&#39;)</code> separated by some number of spaces.</li> <li><code>s</code> represents <strong>a valid expression</strong>.</li> <li>All the integers in the expression are non-negative integers in the range <code>[0, 2<sup>31</sup> - 1]</code>.</li> <li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit integer</strong>.</li> </ul>
Stack; Math; String
C#
using System.Collections.Generic; using System.Linq; struct Element { public char Op; public int Number; public Element(char op, int number) { Op = op; Number = number; } } public class Solution { public int Calculate(string s) { var stack = new Stack<Element>(); var readingNumber = false; var number = 0; var op = '+'; foreach (var ch in ((IEnumerable<char>)s).Concat(Enumerable.Repeat('+', 1))) { if (ch >= '0' && ch <= '9') { if (!readingNumber) { readingNumber = true; number = 0; } number = (number * 10) + (ch - '0'); } else if (ch != ' ') { readingNumber = false; if (op == '+' || op == '-') { if (stack.Count == 2) { var prev = stack.Pop(); var first = stack.Pop(); if (prev.Op == '+') { stack.Push(new Element(first.Op, first.Number + prev.Number)); } else // '-' { stack.Push(new Element(first.Op, first.Number - prev.Number)); } } stack.Push(new Element(op, number)); } else { var prev = stack.Pop(); if (op == '*') { stack.Push(new Element(prev.Op, prev.Number * number)); } else // '/' { stack.Push(new Element(prev.Op, prev.Number / number)); } } op = ch; } } if (stack.Count == 2) { var second = stack.Pop(); var first = stack.Pop(); if (second.Op == '+') { stack.Push(new Element(first.Op, first.Number + second.Number)); } else // '-' { stack.Push(new Element(first.Op, first.Number - second.Number)); } } return stack.Peek().Number; } }
227
Basic Calculator II
Medium
<p>Given a string <code>s</code> which represents an expression, <em>evaluate this expression and return its value</em>.&nbsp;</p> <p>The integer division should truncate toward zero.</p> <p>You may assume that the given expression is always valid. All intermediate results will be in the range of <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>.</p> <p><strong>Note:</strong> You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "3+2*2" <strong>Output:</strong> 7 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = " 3/2 " <strong>Output:</strong> 1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> s = " 3+5 / 2 " <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of integers and operators <code>(&#39;+&#39;, &#39;-&#39;, &#39;*&#39;, &#39;/&#39;)</code> separated by some number of spaces.</li> <li><code>s</code> represents <strong>a valid expression</strong>.</li> <li>All the integers in the expression are non-negative integers in the range <code>[0, 2<sup>31</sup> - 1]</code>.</li> <li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit integer</strong>.</li> </ul>
Stack; Math; String
Go
func calculate(s string) int { sign := '+' stk := []int{} v := 0 for i, c := range s { digit := '0' <= c && c <= '9' if digit { v = v*10 + int(c-'0') } if i == len(s)-1 || !digit && c != ' ' { switch sign { case '+': stk = append(stk, v) case '-': stk = append(stk, -v) case '*': stk[len(stk)-1] *= v case '/': stk[len(stk)-1] /= v } sign = c v = 0 } } ans := 0 for _, v := range stk { ans += v } return ans }
227
Basic Calculator II
Medium
<p>Given a string <code>s</code> which represents an expression, <em>evaluate this expression and return its value</em>.&nbsp;</p> <p>The integer division should truncate toward zero.</p> <p>You may assume that the given expression is always valid. All intermediate results will be in the range of <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>.</p> <p><strong>Note:</strong> You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "3+2*2" <strong>Output:</strong> 7 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = " 3/2 " <strong>Output:</strong> 1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> s = " 3+5 / 2 " <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of integers and operators <code>(&#39;+&#39;, &#39;-&#39;, &#39;*&#39;, &#39;/&#39;)</code> separated by some number of spaces.</li> <li><code>s</code> represents <strong>a valid expression</strong>.</li> <li>All the integers in the expression are non-negative integers in the range <code>[0, 2<sup>31</sup> - 1]</code>.</li> <li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit integer</strong>.</li> </ul>
Stack; Math; String
Java
class Solution { public int calculate(String s) { Deque<Integer> stk = new ArrayDeque<>(); char sign = '+'; int v = 0; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if (Character.isDigit(c)) { v = v * 10 + (c - '0'); } if (i == s.length() - 1 || c == '+' || c == '-' || c == '*' || c == '/') { if (sign == '+') { stk.push(v); } else if (sign == '-') { stk.push(-v); } else if (sign == '*') { stk.push(stk.pop() * v); } else { stk.push(stk.pop() / v); } sign = c; v = 0; } } int ans = 0; while (!stk.isEmpty()) { ans += stk.pop(); } return ans; } }
227
Basic Calculator II
Medium
<p>Given a string <code>s</code> which represents an expression, <em>evaluate this expression and return its value</em>.&nbsp;</p> <p>The integer division should truncate toward zero.</p> <p>You may assume that the given expression is always valid. All intermediate results will be in the range of <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>.</p> <p><strong>Note:</strong> You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "3+2*2" <strong>Output:</strong> 7 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = " 3/2 " <strong>Output:</strong> 1 </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> s = " 3+5 / 2 " <strong>Output:</strong> 5 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of integers and operators <code>(&#39;+&#39;, &#39;-&#39;, &#39;*&#39;, &#39;/&#39;)</code> separated by some number of spaces.</li> <li><code>s</code> represents <strong>a valid expression</strong>.</li> <li>All the integers in the expression are non-negative integers in the range <code>[0, 2<sup>31</sup> - 1]</code>.</li> <li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit integer</strong>.</li> </ul>
Stack; Math; String
Python
class Solution: def calculate(self, s: str) -> int: v, n = 0, len(s) sign = '+' stk = [] for i, c in enumerate(s): if c.isdigit(): v = v * 10 + int(c) if i == n - 1 or c in '+-*/': match sign: case '+': stk.append(v) case '-': stk.append(-v) case '*': stk.append(stk.pop() * v) case '/': stk.append(int(stk.pop() / v)) sign = c v = 0 return sum(stk)
228
Summary Ranges
Easy
<p>You are given a <strong>sorted unique</strong> integer array <code>nums</code>.</p> <p>A <strong>range</strong> <code>[a,b]</code> is the set of all integers from <code>a</code> to <code>b</code> (inclusive).</p> <p>Return <em>the <strong>smallest sorted</strong> list of ranges that <strong>cover all the numbers in the array exactly</strong></em>. That is, each element of <code>nums</code> is covered by exactly one of the ranges, and there is no integer <code>x</code> such that <code>x</code> is in one of the ranges but not in <code>nums</code>.</p> <p>Each range <code>[a,b]</code> in the list should be output as:</p> <ul> <li><code>&quot;a-&gt;b&quot;</code> if <code>a != b</code></li> <li><code>&quot;a&quot;</code> if <code>a == b</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,4,5,7] <strong>Output:</strong> [&quot;0-&gt;2&quot;,&quot;4-&gt;5&quot;,&quot;7&quot;] <strong>Explanation:</strong> The ranges are: [0,2] --&gt; &quot;0-&gt;2&quot; [4,5] --&gt; &quot;4-&gt;5&quot; [7,7] --&gt; &quot;7&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,2,3,4,6,8,9] <strong>Output:</strong> [&quot;0&quot;,&quot;2-&gt;4&quot;,&quot;6&quot;,&quot;8-&gt;9&quot;] <strong>Explanation:</strong> The ranges are: [0,0] --&gt; &quot;0&quot; [2,4] --&gt; &quot;2-&gt;4&quot; [6,6] --&gt; &quot;6&quot; [8,9] --&gt; &quot;8-&gt;9&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 20</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>All the values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is sorted in ascending order.</li> </ul>
Array
C++
class Solution { public: vector<string> summaryRanges(vector<int>& nums) { vector<string> ans; auto f = [&](int i, int j) { return i == j ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[j]); }; for (int i = 0, j, n = nums.size(); i < n; i = j + 1) { j = i; while (j + 1 < n && nums[j + 1] == nums[j] + 1) { ++j; } ans.emplace_back(f(i, j)); } return ans; } };
228
Summary Ranges
Easy
<p>You are given a <strong>sorted unique</strong> integer array <code>nums</code>.</p> <p>A <strong>range</strong> <code>[a,b]</code> is the set of all integers from <code>a</code> to <code>b</code> (inclusive).</p> <p>Return <em>the <strong>smallest sorted</strong> list of ranges that <strong>cover all the numbers in the array exactly</strong></em>. That is, each element of <code>nums</code> is covered by exactly one of the ranges, and there is no integer <code>x</code> such that <code>x</code> is in one of the ranges but not in <code>nums</code>.</p> <p>Each range <code>[a,b]</code> in the list should be output as:</p> <ul> <li><code>&quot;a-&gt;b&quot;</code> if <code>a != b</code></li> <li><code>&quot;a&quot;</code> if <code>a == b</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,4,5,7] <strong>Output:</strong> [&quot;0-&gt;2&quot;,&quot;4-&gt;5&quot;,&quot;7&quot;] <strong>Explanation:</strong> The ranges are: [0,2] --&gt; &quot;0-&gt;2&quot; [4,5] --&gt; &quot;4-&gt;5&quot; [7,7] --&gt; &quot;7&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,2,3,4,6,8,9] <strong>Output:</strong> [&quot;0&quot;,&quot;2-&gt;4&quot;,&quot;6&quot;,&quot;8-&gt;9&quot;] <strong>Explanation:</strong> The ranges are: [0,0] --&gt; &quot;0&quot; [2,4] --&gt; &quot;2-&gt;4&quot; [6,6] --&gt; &quot;6&quot; [8,9] --&gt; &quot;8-&gt;9&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 20</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>All the values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is sorted in ascending order.</li> </ul>
Array
C#
public class Solution { public IList<string> SummaryRanges(int[] nums) { var ans = new List<string>(); for (int i = 0, j = 0, n = nums.Length; i < n; i = j + 1) { j = i; while (j + 1 < n && nums[j + 1] == nums[j] + 1) { ++j; } ans.Add(f(nums, i, j)); } return ans; } public string f(int[] nums, int i, int j) { return i == j ? nums[i].ToString() : string.Format("{0}->{1}", nums[i], nums[j]); } }
228
Summary Ranges
Easy
<p>You are given a <strong>sorted unique</strong> integer array <code>nums</code>.</p> <p>A <strong>range</strong> <code>[a,b]</code> is the set of all integers from <code>a</code> to <code>b</code> (inclusive).</p> <p>Return <em>the <strong>smallest sorted</strong> list of ranges that <strong>cover all the numbers in the array exactly</strong></em>. That is, each element of <code>nums</code> is covered by exactly one of the ranges, and there is no integer <code>x</code> such that <code>x</code> is in one of the ranges but not in <code>nums</code>.</p> <p>Each range <code>[a,b]</code> in the list should be output as:</p> <ul> <li><code>&quot;a-&gt;b&quot;</code> if <code>a != b</code></li> <li><code>&quot;a&quot;</code> if <code>a == b</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,4,5,7] <strong>Output:</strong> [&quot;0-&gt;2&quot;,&quot;4-&gt;5&quot;,&quot;7&quot;] <strong>Explanation:</strong> The ranges are: [0,2] --&gt; &quot;0-&gt;2&quot; [4,5] --&gt; &quot;4-&gt;5&quot; [7,7] --&gt; &quot;7&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,2,3,4,6,8,9] <strong>Output:</strong> [&quot;0&quot;,&quot;2-&gt;4&quot;,&quot;6&quot;,&quot;8-&gt;9&quot;] <strong>Explanation:</strong> The ranges are: [0,0] --&gt; &quot;0&quot; [2,4] --&gt; &quot;2-&gt;4&quot; [6,6] --&gt; &quot;6&quot; [8,9] --&gt; &quot;8-&gt;9&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 20</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>All the values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is sorted in ascending order.</li> </ul>
Array
Go
func summaryRanges(nums []int) (ans []string) { f := func(i, j int) string { if i == j { return strconv.Itoa(nums[i]) } return strconv.Itoa(nums[i]) + "->" + strconv.Itoa(nums[j]) } for i, j, n := 0, 0, len(nums); i < n; i = j + 1 { j = i for j+1 < n && nums[j+1] == nums[j]+1 { j++ } ans = append(ans, f(i, j)) } return }
228
Summary Ranges
Easy
<p>You are given a <strong>sorted unique</strong> integer array <code>nums</code>.</p> <p>A <strong>range</strong> <code>[a,b]</code> is the set of all integers from <code>a</code> to <code>b</code> (inclusive).</p> <p>Return <em>the <strong>smallest sorted</strong> list of ranges that <strong>cover all the numbers in the array exactly</strong></em>. That is, each element of <code>nums</code> is covered by exactly one of the ranges, and there is no integer <code>x</code> such that <code>x</code> is in one of the ranges but not in <code>nums</code>.</p> <p>Each range <code>[a,b]</code> in the list should be output as:</p> <ul> <li><code>&quot;a-&gt;b&quot;</code> if <code>a != b</code></li> <li><code>&quot;a&quot;</code> if <code>a == b</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,4,5,7] <strong>Output:</strong> [&quot;0-&gt;2&quot;,&quot;4-&gt;5&quot;,&quot;7&quot;] <strong>Explanation:</strong> The ranges are: [0,2] --&gt; &quot;0-&gt;2&quot; [4,5] --&gt; &quot;4-&gt;5&quot; [7,7] --&gt; &quot;7&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,2,3,4,6,8,9] <strong>Output:</strong> [&quot;0&quot;,&quot;2-&gt;4&quot;,&quot;6&quot;,&quot;8-&gt;9&quot;] <strong>Explanation:</strong> The ranges are: [0,0] --&gt; &quot;0&quot; [2,4] --&gt; &quot;2-&gt;4&quot; [6,6] --&gt; &quot;6&quot; [8,9] --&gt; &quot;8-&gt;9&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 20</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>All the values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is sorted in ascending order.</li> </ul>
Array
Java
class Solution { public List<String> summaryRanges(int[] nums) { List<String> ans = new ArrayList<>(); for (int i = 0, j, n = nums.length; i < n; i = j + 1) { j = i; while (j + 1 < n && nums[j + 1] == nums[j] + 1) { ++j; } ans.add(f(nums, i, j)); } return ans; } private String f(int[] nums, int i, int j) { return i == j ? nums[i] + "" : String.format("%d->%d", nums[i], nums[j]); } }
228
Summary Ranges
Easy
<p>You are given a <strong>sorted unique</strong> integer array <code>nums</code>.</p> <p>A <strong>range</strong> <code>[a,b]</code> is the set of all integers from <code>a</code> to <code>b</code> (inclusive).</p> <p>Return <em>the <strong>smallest sorted</strong> list of ranges that <strong>cover all the numbers in the array exactly</strong></em>. That is, each element of <code>nums</code> is covered by exactly one of the ranges, and there is no integer <code>x</code> such that <code>x</code> is in one of the ranges but not in <code>nums</code>.</p> <p>Each range <code>[a,b]</code> in the list should be output as:</p> <ul> <li><code>&quot;a-&gt;b&quot;</code> if <code>a != b</code></li> <li><code>&quot;a&quot;</code> if <code>a == b</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,4,5,7] <strong>Output:</strong> [&quot;0-&gt;2&quot;,&quot;4-&gt;5&quot;,&quot;7&quot;] <strong>Explanation:</strong> The ranges are: [0,2] --&gt; &quot;0-&gt;2&quot; [4,5] --&gt; &quot;4-&gt;5&quot; [7,7] --&gt; &quot;7&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,2,3,4,6,8,9] <strong>Output:</strong> [&quot;0&quot;,&quot;2-&gt;4&quot;,&quot;6&quot;,&quot;8-&gt;9&quot;] <strong>Explanation:</strong> The ranges are: [0,0] --&gt; &quot;0&quot; [2,4] --&gt; &quot;2-&gt;4&quot; [6,6] --&gt; &quot;6&quot; [8,9] --&gt; &quot;8-&gt;9&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 20</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>All the values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is sorted in ascending order.</li> </ul>
Array
Python
class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: def f(i: int, j: int) -> str: return str(nums[i]) if i == j else f'{nums[i]}->{nums[j]}' i = 0 n = len(nums) ans = [] while i < n: j = i while j + 1 < n and nums[j + 1] == nums[j] + 1: j += 1 ans.append(f(i, j)) i = j + 1 return ans
228
Summary Ranges
Easy
<p>You are given a <strong>sorted unique</strong> integer array <code>nums</code>.</p> <p>A <strong>range</strong> <code>[a,b]</code> is the set of all integers from <code>a</code> to <code>b</code> (inclusive).</p> <p>Return <em>the <strong>smallest sorted</strong> list of ranges that <strong>cover all the numbers in the array exactly</strong></em>. That is, each element of <code>nums</code> is covered by exactly one of the ranges, and there is no integer <code>x</code> such that <code>x</code> is in one of the ranges but not in <code>nums</code>.</p> <p>Each range <code>[a,b]</code> in the list should be output as:</p> <ul> <li><code>&quot;a-&gt;b&quot;</code> if <code>a != b</code></li> <li><code>&quot;a&quot;</code> if <code>a == b</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,4,5,7] <strong>Output:</strong> [&quot;0-&gt;2&quot;,&quot;4-&gt;5&quot;,&quot;7&quot;] <strong>Explanation:</strong> The ranges are: [0,2] --&gt; &quot;0-&gt;2&quot; [4,5] --&gt; &quot;4-&gt;5&quot; [7,7] --&gt; &quot;7&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,2,3,4,6,8,9] <strong>Output:</strong> [&quot;0&quot;,&quot;2-&gt;4&quot;,&quot;6&quot;,&quot;8-&gt;9&quot;] <strong>Explanation:</strong> The ranges are: [0,0] --&gt; &quot;0&quot; [2,4] --&gt; &quot;2-&gt;4&quot; [6,6] --&gt; &quot;6&quot; [8,9] --&gt; &quot;8-&gt;9&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 20</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>All the values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is sorted in ascending order.</li> </ul>
Array
Rust
impl Solution { #[allow(dead_code)] pub fn summary_ranges(nums: Vec<i32>) -> Vec<String> { if nums.is_empty() { return vec![]; } let mut ret = Vec::new(); let mut start = nums[0]; let mut prev = nums[0]; let mut current = 0; let n = nums.len(); for i in 1..n { current = nums[i]; if current != prev + 1 { if start == prev { ret.push(start.to_string()); } else { ret.push(start.to_string() + "->" + &prev.to_string()); } start = current; prev = current; } else { prev = current; } } if start == prev { ret.push(start.to_string()); } else { ret.push(start.to_string() + "->" + &prev.to_string()); } ret } }
228
Summary Ranges
Easy
<p>You are given a <strong>sorted unique</strong> integer array <code>nums</code>.</p> <p>A <strong>range</strong> <code>[a,b]</code> is the set of all integers from <code>a</code> to <code>b</code> (inclusive).</p> <p>Return <em>the <strong>smallest sorted</strong> list of ranges that <strong>cover all the numbers in the array exactly</strong></em>. That is, each element of <code>nums</code> is covered by exactly one of the ranges, and there is no integer <code>x</code> such that <code>x</code> is in one of the ranges but not in <code>nums</code>.</p> <p>Each range <code>[a,b]</code> in the list should be output as:</p> <ul> <li><code>&quot;a-&gt;b&quot;</code> if <code>a != b</code></li> <li><code>&quot;a&quot;</code> if <code>a == b</code></li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,2,4,5,7] <strong>Output:</strong> [&quot;0-&gt;2&quot;,&quot;4-&gt;5&quot;,&quot;7&quot;] <strong>Explanation:</strong> The ranges are: [0,2] --&gt; &quot;0-&gt;2&quot; [4,5] --&gt; &quot;4-&gt;5&quot; [7,7] --&gt; &quot;7&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,2,3,4,6,8,9] <strong>Output:</strong> [&quot;0&quot;,&quot;2-&gt;4&quot;,&quot;6&quot;,&quot;8-&gt;9&quot;] <strong>Explanation:</strong> The ranges are: [0,0] --&gt; &quot;0&quot; [2,4] --&gt; &quot;2-&gt;4&quot; [6,6] --&gt; &quot;6&quot; [8,9] --&gt; &quot;8-&gt;9&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= nums.length &lt;= 20</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li>All the values of <code>nums</code> are <strong>unique</strong>.</li> <li><code>nums</code> is sorted in ascending order.</li> </ul>
Array
TypeScript
function summaryRanges(nums: number[]): string[] { const f = (i: number, j: number): string => { return i === j ? `${nums[i]}` : `${nums[i]}->${nums[j]}`; }; const n = nums.length; const ans: string[] = []; for (let i = 0, j = 0; i < n; i = j + 1) { j = i; while (j + 1 < n && nums[j + 1] === nums[j] + 1) { ++j; } ans.push(f(i, j)); } return ans; }
229
Majority Element II
Medium
<p>Given an integer array of size <code>n</code>, find all elements that appear more than <code>&lfloor; n/3 &rfloor;</code> times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> [3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> [1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?</p>
Array; Hash Table; Counting; Sorting
C++
class Solution { public: vector<int> majorityElement(vector<int>& nums) { int n1 = 0, n2 = 0; int m1 = 0, m2 = 1; for (int m : nums) { if (m == m1) ++n1; else if (m == m2) ++n2; else if (n1 == 0) { m1 = m; ++n1; } else if (n2 == 0) { m2 = m; ++n2; } else { --n1; --n2; } } vector<int> ans; if (count(nums.begin(), nums.end(), m1) > nums.size() / 3) ans.push_back(m1); if (count(nums.begin(), nums.end(), m2) > nums.size() / 3) ans.push_back(m2); return ans; } };
229
Majority Element II
Medium
<p>Given an integer array of size <code>n</code>, find all elements that appear more than <code>&lfloor; n/3 &rfloor;</code> times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> [3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> [1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?</p>
Array; Hash Table; Counting; Sorting
C#
public class Solution { public IList<int> MajorityElement(int[] nums) { int n1 = 0, n2 = 0; int m1 = 0, m2 = 1; foreach (int m in nums) { if (m == m1) { ++n1; } else if (m == m2) { ++n2; } else if (n1 == 0) { m1 = m; ++n1; } else if (n2 == 0) { m2 = m; ++n2; } else { --n1; --n2; } } var ans = new List<int>(); ans.Add(m1); ans.Add(m2); return ans.Where(m => nums.Count(n => n == m) > nums.Length / 3).ToList(); } }
229
Majority Element II
Medium
<p>Given an integer array of size <code>n</code>, find all elements that appear more than <code>&lfloor; n/3 &rfloor;</code> times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> [3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> [1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?</p>
Array; Hash Table; Counting; Sorting
Go
func majorityElement(nums []int) []int { var n1, n2 int m1, m2 := 0, 1 for _, m := range nums { if m == m1 { n1++ } else if m == m2 { n2++ } else if n1 == 0 { m1, n1 = m, 1 } else if n2 == 0 { m2, n2 = m, 1 } else { n1, n2 = n1-1, n2-1 } } n1, n2 = 0, 0 for _, m := range nums { if m == m1 { n1++ } else if m == m2 { n2++ } } var ans []int if n1 > len(nums)/3 { ans = append(ans, m1) } if n2 > len(nums)/3 { ans = append(ans, m2) } return ans }
229
Majority Element II
Medium
<p>Given an integer array of size <code>n</code>, find all elements that appear more than <code>&lfloor; n/3 &rfloor;</code> times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> [3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> [1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?</p>
Array; Hash Table; Counting; Sorting
Java
class Solution { public List<Integer> majorityElement(int[] nums) { int n1 = 0, n2 = 0; int m1 = 0, m2 = 1; for (int m : nums) { if (m == m1) { ++n1; } else if (m == m2) { ++n2; } else if (n1 == 0) { m1 = m; ++n1; } else if (n2 == 0) { m2 = m; ++n2; } else { --n1; --n2; } } List<Integer> ans = new ArrayList<>(); n1 = 0; n2 = 0; for (int m : nums) { if (m == m1) { ++n1; } else if (m == m2) { ++n2; } } if (n1 > nums.length / 3) { ans.add(m1); } if (n2 > nums.length / 3) { ans.add(m2); } return ans; } }
229
Majority Element II
Medium
<p>Given an integer array of size <code>n</code>, find all elements that appear more than <code>&lfloor; n/3 &rfloor;</code> times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> [3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> [1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?</p>
Array; Hash Table; Counting; Sorting
PHP
class Solution { /** * @param Integer[] $nums * @return Integer[] */ function majorityElement($nums) { $rs = []; $n = count($nums); for ($i = 0; $i < $n; $i++) { $hashmap[$nums[$i]] += 1; if ($hashmap[$nums[$i]] > $n / 3) { array_push($rs, $nums[$i]); } } return array_unique($rs); } }
229
Majority Element II
Medium
<p>Given an integer array of size <code>n</code>, find all elements that appear more than <code>&lfloor; n/3 &rfloor;</code> times.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> [3] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1] <strong>Output:</strong> [1] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [1,2] <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?</p>
Array; Hash Table; Counting; Sorting
Python
class Solution: def majorityElement(self, nums: List[int]) -> List[int]: n1 = n2 = 0 m1, m2 = 0, 1 for m in nums: if m == m1: n1 += 1 elif m == m2: n2 += 1 elif n1 == 0: m1, n1 = m, 1 elif n2 == 0: m2, n2 = m, 1 else: n1, n2 = n1 - 1, n2 - 1 return [m for m in [m1, m2] if nums.count(m) > len(nums) // 3]
230
Kth Smallest Element in a BST
Medium
<p>Given the <code>root</code> of a binary search tree, and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest value (<strong>1-indexed</strong>) of all the values of the nodes in the tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0230.Kth%20Smallest%20Element%20in%20a%20BST/images/kthtree1.jpg" style="width: 212px; height: 301px;" /> <pre> <strong>Input:</strong> root = [3,1,4,null,2], k = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0230.Kth%20Smallest%20Element%20in%20a%20BST/images/kthtree2.jpg" style="width: 382px; height: 302px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,null,1], k = 3 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?</p>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int kthSmallest(TreeNode* root, int k) { stack<TreeNode*> stk; while (root || !stk.empty()) { if (root) { stk.push(root); root = root->left; } else { root = stk.top(); stk.pop(); if (--k == 0) return root->val; root = root->right; } } return 0; } };
230
Kth Smallest Element in a BST
Medium
<p>Given the <code>root</code> of a binary search tree, and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest value (<strong>1-indexed</strong>) of all the values of the nodes in the tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0230.Kth%20Smallest%20Element%20in%20a%20BST/images/kthtree1.jpg" style="width: 212px; height: 301px;" /> <pre> <strong>Input:</strong> root = [3,1,4,null,2], k = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0230.Kth%20Smallest%20Element%20in%20a%20BST/images/kthtree2.jpg" style="width: 382px; height: 302px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,null,1], k = 3 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?</p>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func kthSmallest(root *TreeNode, k int) int { stk := []*TreeNode{} for root != nil || len(stk) > 0 { if root != nil { stk = append(stk, root) root = root.Left } else { root = stk[len(stk)-1] stk = stk[:len(stk)-1] k-- if k == 0 { return root.Val } root = root.Right } } return 0 }
230
Kth Smallest Element in a BST
Medium
<p>Given the <code>root</code> of a binary search tree, and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest value (<strong>1-indexed</strong>) of all the values of the nodes in the tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0230.Kth%20Smallest%20Element%20in%20a%20BST/images/kthtree1.jpg" style="width: 212px; height: 301px;" /> <pre> <strong>Input:</strong> root = [3,1,4,null,2], k = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0230.Kth%20Smallest%20Element%20in%20a%20BST/images/kthtree2.jpg" style="width: 382px; height: 302px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,null,1], k = 3 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?</p>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int kthSmallest(TreeNode root, int k) { Deque<TreeNode> stk = new ArrayDeque<>(); while (root != null || !stk.isEmpty()) { if (root != null) { stk.push(root); root = root.left; } else { root = stk.pop(); if (--k == 0) { return root.val; } root = root.right; } } return 0; } }
230
Kth Smallest Element in a BST
Medium
<p>Given the <code>root</code> of a binary search tree, and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest value (<strong>1-indexed</strong>) of all the values of the nodes in the tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0230.Kth%20Smallest%20Element%20in%20a%20BST/images/kthtree1.jpg" style="width: 212px; height: 301px;" /> <pre> <strong>Input:</strong> root = [3,1,4,null,2], k = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0230.Kth%20Smallest%20Element%20in%20a%20BST/images/kthtree2.jpg" style="width: 382px; height: 302px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,null,1], k = 3 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?</p>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: stk = [] while root or stk: if root: stk.append(root) root = root.left else: root = stk.pop() k -= 1 if k == 0: return root.val root = root.right
230
Kth Smallest Element in a BST
Medium
<p>Given the <code>root</code> of a binary search tree, and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest value (<strong>1-indexed</strong>) of all the values of the nodes in the tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0230.Kth%20Smallest%20Element%20in%20a%20BST/images/kthtree1.jpg" style="width: 212px; height: 301px;" /> <pre> <strong>Input:</strong> root = [3,1,4,null,2], k = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0230.Kth%20Smallest%20Element%20in%20a%20BST/images/kthtree2.jpg" style="width: 382px; height: 302px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,null,1], k = 3 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?</p>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { fn dfs(root: Option<Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>, k: usize) { if let Some(node) = root { let mut node = node.borrow_mut(); Self::dfs(node.left.take(), res, k); res.push(node.val); if res.len() >= k { return; } Self::dfs(node.right.take(), res, k); } } pub fn kth_smallest(root: Option<Rc<RefCell<TreeNode>>>, k: i32) -> i32 { let k = k as usize; let mut res: Vec<i32> = Vec::with_capacity(k); Self::dfs(root, &mut res, k); res[k - 1] } }
230
Kth Smallest Element in a BST
Medium
<p>Given the <code>root</code> of a binary search tree, and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest value (<strong>1-indexed</strong>) of all the values of the nodes in the tree</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0230.Kth%20Smallest%20Element%20in%20a%20BST/images/kthtree1.jpg" style="width: 212px; height: 301px;" /> <pre> <strong>Input:</strong> root = [3,1,4,null,2], k = 1 <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0230.Kth%20Smallest%20Element%20in%20a%20BST/images/kthtree2.jpg" style="width: 382px; height: 302px;" /> <pre> <strong>Input:</strong> root = [5,3,6,2,4,null,null,1], k = 3 <strong>Output:</strong> 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is <code>n</code>.</li> <li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?</p>
Tree; Depth-First Search; Binary Search Tree; Binary Tree
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function kthSmallest(root: TreeNode | null, k: number): number { const dfs = (root: TreeNode | null) => { if (root == null) { return -1; } const { val, left, right } = root; const l = dfs(left); if (l !== -1) { return l; } k--; if (k === 0) { return val; } return dfs(right); }; return dfs(root); }
231
Power of Two
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of two. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of two, if there exists an integer <code>x</code> such that <code>n == 2<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>0</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 16 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>4</sup> = 16 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without loops/recursion?
Bit Manipulation; Recursion; Math
C++
class Solution { public: bool isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; } };
231
Power of Two
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of two. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of two, if there exists an integer <code>x</code> such that <code>n == 2<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>0</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 16 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>4</sup> = 16 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without loops/recursion?
Bit Manipulation; Recursion; Math
Go
func isPowerOfTwo(n int) bool { return n > 0 && (n&(n-1)) == 0 }
231
Power of Two
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of two. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of two, if there exists an integer <code>x</code> such that <code>n == 2<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>0</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 16 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>4</sup> = 16 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without loops/recursion?
Bit Manipulation; Recursion; Math
Java
class Solution { public boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; } }
231
Power of Two
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of two. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of two, if there exists an integer <code>x</code> such that <code>n == 2<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>0</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 16 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>4</sup> = 16 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without loops/recursion?
Bit Manipulation; Recursion; Math
JavaScript
/** * @param {number} n * @return {boolean} */ var isPowerOfTwo = function (n) { return n > 0 && (n & (n - 1)) == 0; };
231
Power of Two
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of two. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of two, if there exists an integer <code>x</code> such that <code>n == 2<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>0</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 16 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>4</sup> = 16 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without loops/recursion?
Bit Manipulation; Recursion; Math
Python
class Solution: def isPowerOfTwo(self, n: int) -> bool: return n > 0 and (n & (n - 1)) == 0
231
Power of Two
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of two. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of two, if there exists an integer <code>x</code> such that <code>n == 2<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>0</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 16 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>4</sup> = 16 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without loops/recursion?
Bit Manipulation; Recursion; Math
Rust
impl Solution { pub fn is_power_of_two(n: i32) -> bool { n > 0 && (n & (n - 1)) == 0 } }
231
Power of Two
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of two. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of two, if there exists an integer <code>x</code> such that <code>n == 2<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>0</sup> = 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 16 <strong>Output:</strong> true <strong>Explanation: </strong>2<sup>4</sup> = 16 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without loops/recursion?
Bit Manipulation; Recursion; Math
TypeScript
function isPowerOfTwo(n: number): boolean { return n > 0 && (n & (n - 1)) === 0; }
232
Implement Queue using Stacks
Easy
<p>Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (<code>push</code>, <code>peek</code>, <code>pop</code>, and <code>empty</code>).</p> <p>Implement the <code>MyQueue</code> class:</p> <ul> <li><code>void push(int x)</code> Pushes element x to the back of the queue.</li> <li><code>int pop()</code> Removes the element from the front of the queue and returns it.</li> <li><code>int peek()</code> Returns the element at the front of the queue.</li> <li><code>boolean empty()</code> Returns <code>true</code> if the queue is empty, <code>false</code> otherwise.</li> </ul> <p><strong>Notes:</strong></p> <ul> <li>You must use <strong>only</strong> standard operations of a stack, which means only <code>push to top</code>, <code>peek/pop from top</code>, <code>size</code>, and <code>is empty</code> operations are valid.</li> <li>Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack&#39;s standard operations.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MyQueue&quot;, &quot;push&quot;, &quot;push&quot;, &quot;peek&quot;, &quot;pop&quot;, &quot;empty&quot;] [[], [1], [2], [], [], []] <strong>Output</strong> [null, null, null, 1, 1, false] <strong>Explanation</strong> MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x &lt;= 9</code></li> <li>At most <code>100</code>&nbsp;calls will be made to <code>push</code>, <code>pop</code>, <code>peek</code>, and <code>empty</code>.</li> <li>All the calls to <code>pop</code> and <code>peek</code> are valid.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Can you implement the queue such that each operation is <strong><a href="https://en.wikipedia.org/wiki/Amortized_analysis" target="_blank">amortized</a></strong> <code>O(1)</code> time complexity? In other words, performing <code>n</code> operations will take overall <code>O(n)</code> time even if one of those operations may take longer.</p>
Stack; Design; Queue
C++
class MyQueue { public: MyQueue() { } void push(int x) { stk1.push(x); } int pop() { move(); int ans = stk2.top(); stk2.pop(); return ans; } int peek() { move(); return stk2.top(); } bool empty() { return stk1.empty() && stk2.empty(); } private: stack<int> stk1; stack<int> stk2; void move() { if (stk2.empty()) { while (!stk1.empty()) { stk2.push(stk1.top()); stk1.pop(); } } } }; /** * Your MyQueue object will be instantiated and called as such: * MyQueue* obj = new MyQueue(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->peek(); * bool param_4 = obj->empty(); */